我有两个DTO:
@Entity
@Table( name = "USER" )
public class UserDto implements Serializable
{
@Id
@GeneratedValue( generator = "trigger_gen" )
@GenericGenerator( name = "trigger_gen", strategy = "path.TriggerAssignedIdentityGenerator" )
@Column( nullable = true, length = 14, name = "USER_ID" )
private Long userId;
@OneToMany( cascade =
{ CascadeType.ALL }, mappedBy = "userIdOwner" )
private Set< AdressDto > addresses;
//getters and setters
}
@Entity
@Table( name = "ADDRESS" )
public class AddressDto implements Serializable
{
@Id
@GeneratedValue( generator = "trigger_gen" )
@GenericGenerator( name = "trigger_gen", strategy = "path.TriggerAssignedIdentityGenerator" )
@Column( nullable = true, length = 14, name = "ADDRESS_ID" )
private Long addressId;
@Column( nullable = true, length = 14, name = "USER_ID", insertable = false, updatable = false )
private Long userId;
@ManyToOne( fetch = FetchType.LAZY )
@JoinColumn( name = "USER_ID", insertable = true, updatable = true )
private UserDto userIdOwner;
//getters and setters
}
我想做类似的事情:
AddressDto address = new AddressDto();
Set<AddressDto> addresses = Sets.newHashSet();
addresses.add(address);
UserDto user = new UserDto()
user.setAddresses(addresses);
session.persist(user);
但是我有一个错误ConstraintViolationException无法将'NULL'设置为addressId。 我究竟做错了什么?我该怎么做才能使它有效?
答案 0 :(得分:1)
您需要在两个方向上关联实体才能使级联工作。
AddressDto address = new AddressDto();
UserDto user = new UserDto()
user.getAddresses().add(address);
address.setUser(user);
session.persist(user);
我在你的地址实体中注意到了这一点:
@Column( nullable = true, length = 14, name = "USER_ID", insertable = false, updatable = false )
private Long userId;
这似乎是不必要的,因为您User
映射为@ManyToOne
正好在