I have a problem where I evict an entity, but changes made to it will still change the database. This is part of the method in my DAO.
@Entity
public class Profile {
@Id
@GeneratedValue
private Long id;
@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name = "PROFILE_ID")
@LazyCollection(LazyCollectionOption.FALSE)
private List<Avatar> avatars;
...
}
In a DAO method:
Profile profile = getProfile(...);
// Clear from hibernate
currentSession.evict(profile);
profile.setId(null);
for (Avatar a : profile.getAvatars()) {
currentSession.evict(a);
a.setId(null);
}
currentSession.save(profile); // save a copy of Profile (not update)
before:
PUBLIC.PROFILE
ID, DOMAIN, STATUS
1, "test", "MEMBER"
PUBLIC.AVATAR
ID, NAME, PROFILE_ID
1, "main", 1
after method
PUBLIC.PROFILE
ID, DOMAIN, STATUS
1, "test", "MEMBER"
2, "test", "MEMBER"
PUBLIC.AVATAR
ID, NAME, PROFILE_ID
1, "main", null
2, "main", 2
So as you can see, the original row in AVATAR has now a null foreign key.
Why? This is happening in a unit / integration test using Unitils and Spring and this might influence how the Hibernate DAO works, maybe.
It's all in a in-memory H2 database..
After adding a line
profile.setAvatars(new ArrayList<>(profile.getAvatars());
it works ...
So I guess the problem was Hibernate's implementation of List
, but how could that affect the behavior??