0

I Have two DTOs:

@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
}

I want to do something like:

AddressDto address = new AddressDto();
Set<AddressDto> addresses = Sets.newHashSet();
addresses.add(address);

UserDto user = new UserDto()
user.setAddresses(addresses);

session.persist(user);

But I've got an error ConstraintViolationException cannot set 'NULL' into addressId. What am I doing wrong? What should I do to make it works?

dzuma
  • 171
  • 5
  • 17

1 Answers1

1

You need to associate entities in both directions in order for cascading to work.

AddressDto address = new AddressDto();
UserDto user = new UserDto()

user.getAddresses().add(address);
address.setUser(user);

session.persist(user);

I noticed this in your Address entity:

   @Column( nullable = true, length = 14, name = "USER_ID", insertable = false, updatable = false )
   private Long userId;

which seems unnecessary since you've got the User mapped as @ManyToOne just below

isah
  • 5,221
  • 3
  • 26
  • 36