Created
August 12, 2013 17:40
-
-
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…
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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; | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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(); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@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