For example, the following will not persist your ElementCollection.
@Entity
@Table(name = "ParentEntity")
public class ParentEntity {
@Id
@GeneratedValue
@Column(name= "ParentId")
private long parentId;
@ElementCollection(fetch = FetchType.EAGER)
@CollectionTable(name = "ChildrenNames", joinColumns = @JoinColumn(name = "ParentId"))
@Column(name = "ChildName")
private Set<String> children;
public Set<String> getChildren() {
return children;
}
public void setChildren(Set<String> children) {
this.children = children;
}
@Column(name = "ParentName")
private String parentName;
public String getParentName() {
return parentName;
}
public void setParentName(String parentName) {
this.parentName = parentName;
}
}
@Service
public class ParentServiceImpl implements ParentService {
@Autowired
ParentRepository parentRepository;
@Transactional
public void saveParent(ParentEntity parentEntity){
parentRepository.saveParent(parentEntity);
parentRepository.detach(parentEntity);
}
}
@Repository
public class ParentRepository {
@PersistenceContext
EntityManager entityManager;
public void saveParent(ParentEntity parentEntity){
entityManager.persist(parentEntity);
}
public void detachParent(ParentEntity parentEntity){
entityManager.detach(parentEntity);
}
public ParentEntity getParentByName(String parentName){
TypedQuery<ParentEntity> query = entityManager.createQuery("SELECT p FROM ParentEntity p WHERE p.parentName = :parentName", ParentEntity.class);
query.setParameter("parentName", parentName);
return query.getSingleResult();
}
}
You will likely not run into situations like this, however I'm posting as I ran into some code that I was refactoring for Spring 3.1. 3.1 did not like nested @Transactions on a particular thread, and in the code's original design, it was detaching the entity on the nested item to avoid conflicts, I removed the nested @Transaction but did not notice the detach, and spent days figuring out why hibernate was not persisting the collection. The answer is, as stated above, hibernate does not persist the collection at .persist, but on commit.
Adam,
ReplyDeleteI hate to bug you, so delete or ignore this comment if need be. But I was impressed with the few posts on your blog and figured I'd reach out. If you're looking for a career change, or just something better, check out www.objectpartners.com, or better yet, check out http://www.objectpartners.com/careers/why-opi/ to see if you'd be interested. Again, don't want to be an annoying recruiter so reply only if interested.
Happy new year, and go GOP! :)
--Ehren Seim