I want to move the entities in one association to another association, but failed.
The following is what I did. What is wrong in my code?
Thanks for your help.
The case is:
one Guard owns many Devices. The following is the entity definitions:
Code:
@Entity
@org.hibernate.annotations.Entity( dynamicInsert=true, dynamicUpdate=true )
@Table(name="GUARD",
uniqueConstraints={@UniqueConstraint(columnNames={"name"})})
public class Guard implements Serializable {
...
@OneToMany(mappedBy="guard", cascade={CascadeType.ALL}, fetch = FetchType.LAZY )
private List<Device> devices = new ArrayList<Device>() ;
...
}
@Entity
@org.hibernate.annotations.Entity( dynamicInsert=true, dynamicUpdate=true )
@Table(name="DEVICE",
uniqueConstraints={@UniqueConstraint(columnNames={"identifier"})})
public class Device implements Serializable {
...
@ManyToOne(fetch = FetchType.EAGER )
@JoinColumn(name="GUARD_FK_ID")
@org.hibernate.annotations.ForeignKey(name = "GUARD_FK")
private Guard guard ;
...
}
The following is the code to move the devices owned by one Guard to another Guard, but the code has no effect on the database.
Code:
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT)
public void reassignDevicesTo(Guard from, Guard to) {
Guard fromAttached = entityManager.getReference( Guard.class, from.getId() ) ;
List<Device> fromDevices = fromAttached.getDevices() ;
Guard toAttached = entityManager.getReference( Guard.class, to.getId() ) ;
List<Device> toDevices = toAttached.getDevices() ;
//reassign
toDevices.addAll( fromDevices ) ;
fromDevices.clear() ;
}