gpt4 book ai didi

java - Spring Boot 数据休息 JPA : @ManyToOne not populating the ForeignKey column in DB

转载 作者:行者123 更新时间:2023-11-30 02:21:46 26 4
gpt4 key购买 nike

我在 TomCat 中使用 Spring Boot Data Rest 和 JPA 将数据保存在 MySQL 中。

The problem: When a JSON to add a User is sent to the Rest endpoint, both MySQL tables are updated, BUT the values in the mapping column (phone.user_id) are set to 'NULL' (should be set to the corresponding User.uid)... What is missing from the code to work as intended ?

生成的 SQL 表和值:

// "user" table                  // "phone" table
uid | first_name pid | number | user_id
---------------- ------------------------
1 | John 1 | 03432453 | NULL <--- should show 1
2 | 02451254 | NULL <--- should show 1

@OneToMany 方面:

@Entity    
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long uid;
private String firstName;

@OneToMany(cascade=CascadeType.ALL, mappedBy="user", orphanRemoval=true)
private List<Phone> phones;

/* getters and setters */

public void addPhone(Phone phone) {
this.phones.add(phone);
phone.setUser(this);
}

/* UPDATED - method added */
public User updatePhoneUserId(User user) {
List<Phone> phs = user.getPhones();
for (Phone ph : phs ) {
ph.setUser(user);
}
return user;
}
}

@ManyToOne 方面:

@Entity
public class Phone {

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long pid;

private String number;

@ManyToOne(fetch=FetchType.LAZY)
@JoinColumn(name="user_id")
private User user;

/* getters and setters*/

}

UserRepository 和 PhoneRepository:

public interface UserRepository extends JpaRepository<User, Long> { }
public interface PhoneRepository extends JpaRepository<Phone, Long> { }

休息 Controller :

@RestController  
@RequestMapping(path="/api")
public class UserController {

@Autowired
private UserRepository ur;

@PostMapping(path="/add")
public @ResponseBody String addNewUserPost(@RequestBody User user) {
// ur.save(user); /* UPDATED - line removed */
ur.save(user.updatePhoneUserId(user)); /* UPDATED - line added */

return "Saved";
}
}

最佳答案

将用户保存到数据库存储库后,模型返回具有更新值(例如 id)的用户对象。

所以只需执行以下操作:

user = ur.save(user);

因此用户对象将被存储库返回的对象替换,并且 id 不再为空。

关于java - Spring Boot 数据休息 JPA : @ManyToOne not populating the ForeignKey column in DB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46637167/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com