我的实体出了问题。我进行交易以在这两个实体之间建立多对一的连接。我是这样做的:
User user = new User();
user.setName("a");
user.setLastName("b");
Set<Adress> a = new HashSet<Adress>();
Adress a1 = new Adress();
Adress a2 = new Adress();
a1.setCity("a1");
a2.setCity("a2");
a.add(a1);
a.add(a2);
user.setAdress(a);
userProxy.save(user);
我的邀请:
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.TABLE)
private Long id;
@NotNull
private String name;
@NotNull
private String lastName;
@OneToMany(mappedBy="user", cascade=CascadeType.ALL)
private Set<Adress> adress = new HashSet<Adress>();
public User(String name, String lastName) {
this.name = name;
this.lastName = lastName;
}
public User() {
}
public Set<Adress> getAdress() {
return adress;
}
public void setAdress(Set<Adress> adress) {
this.adress = adress;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Long getId() {
return id;
}
}
第二实体
@Entity
public class Adress {
@Id
@GeneratedValue(strategy=GenerationType.TABLE)
private Long id;
private String city;
@ManyToOne
@JoinColumn(name="user_id")
private User user;
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public Long getId() {
return id;
}
}
表格中的数据用户保存正常,但在表格地址字段中,user_id为&#34; NULL&#34;任何人都可以向我解释为什么会这样?我和@ManyToOne尝试了很多组合,但对我没用。
有关详细信息,请参阅UserProxy:
@Service
public class UserProxyDao {
private UserDao userDao;
@Autowired
public UserProxyDao(UserDao userDao) {
this.userDao = userDao;
}
public void save(User user) {
userDao.save(user);
}
}
然而,如果我将@NotNull放在Adress中的字段用户实体验证失败...我真的不知道为什么会这样
Caused by: javax.validation.ConstraintViolationException: validation failed for classes [pl.rd.j2ee.api.domain.Adress] during persist time for groups [javax.validation.groups.Default, ]
答案 0 :(得分:0)
只要您先执行此操作,就可以在一个操作中执行此操作。
a1.setUser(user);
a2.setUser(user);
您可以随时将User
添加到Address
构造函数中并在那里执行。
public Address (User user) {
this.user = user;
}