Skip to content

Instantly share code, notes, and snippets.

@aweigold
Created August 12, 2013 17:40
Show Gist options
  • Save aweigold/6213179 to your computer and use it in GitHub Desktop.
Save aweigold/6213179 to your computer and use it in GitHub Desktop.
Hibernate, ElementCollection, and Transactions http://www.adamweigold.com/2011/11/hibernate-elementcollection-and.html Hibernate implemented @ElementCollection in the JPA by binding the persistence of the ElementCollection of a new entity at the end of the transaction, and NOT at the time you tell the EntityManager to persist. Under most use cas…
@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;
}
}
@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();
}
}
@Service
public class ParentServiceImpl implements ParentService {
@Autowired
ParentRepository parentRepository;
@Transactional
public void saveParent(ParentEntity parentEntity){
parentRepository.saveParent(parentEntity);
parentRepository.detach(parentEntity);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment