From 64bc8a412d2a40d82fde575c6b542c5e18106f34 Mon Sep 17 00:00:00 2001 From: eelhazati Date: Fri, 23 Nov 2018 17:00:08 +0100 Subject: [PATCH] JPA Entity Graph. --- .../com/baeldung/jpa/entitygraph/MainApp.java | 26 ++++++ .../jpa/entitygraph/model/Comment.java | 63 +++++++++++++ .../baeldung/jpa/entitygraph/model/Post.java | 86 +++++++++++++++++ .../baeldung/jpa/entitygraph/model/User.java | 48 ++++++++++ .../jpa/entitygraph/repo/PostRepository.java | 93 +++++++++++++++++++ .../main/resources/META-INF/persistence.xml | 55 +++++++---- .../java-jpa/src/main/resources/data-init.sql | 8 ++ .../entitygraph/repo/PostRepositoryTest.java | 68 ++++++++++++++ 8 files changed, 428 insertions(+), 19 deletions(-) create mode 100644 persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entitygraph/MainApp.java create mode 100644 persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entitygraph/model/Comment.java create mode 100644 persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entitygraph/model/Post.java create mode 100644 persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entitygraph/model/User.java create mode 100644 persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entitygraph/repo/PostRepository.java create mode 100644 persistence-modules/java-jpa/src/main/resources/data-init.sql create mode 100644 persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/entitygraph/repo/PostRepositoryTest.java diff --git a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entitygraph/MainApp.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entitygraph/MainApp.java new file mode 100644 index 0000000000..88aa4389e9 --- /dev/null +++ b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entitygraph/MainApp.java @@ -0,0 +1,26 @@ +package com.baeldung.jpa.entitygraph; + +import com.baeldung.jpa.entitygraph.model.Post; +import com.baeldung.jpa.entitygraph.repo.PostRepository; + +public class MainApp { + + public static void main(String... args) { + Long postId = 1L; + Post post = null; + PostRepository postRepository = new PostRepository(); + + //Using EntityManager.find(). + post = postRepository.find(postId); + post = postRepository.findWithEntityGraph(postId); + post = postRepository.findWithEntityGraph2(postId); + + //Using JPQL: Query and TypedQuery + post = postRepository.findUsingJpql(postId); + + //Using Criteria API + post = postRepository.findUsingCriteria(postId); + + postRepository.clean(); + } +} \ No newline at end of file diff --git a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entitygraph/model/Comment.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entitygraph/model/Comment.java new file mode 100644 index 0000000000..40ecd3262b --- /dev/null +++ b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entitygraph/model/Comment.java @@ -0,0 +1,63 @@ +package com.baeldung.jpa.entitygraph.model; + +import javax.persistence.*; + +@Entity +public class Comment { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + + private String reply; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn + private Post post; + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn + private User user; + //... + + public Comment() { + } + + public Comment(String reply, Post post, User user) { + this.reply = reply; + this.post = post; + this.user = user; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getReply() { + return reply; + } + + public void setReply(String reply) { + this.reply = reply; + } + + public Post getPost() { + return post; + } + + public void setPost(Post post) { + this.post = post; + } + + public User getUser() { + return user; + } + + public void setUser(User user) { + this.user = user; + } +} \ No newline at end of file diff --git a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entitygraph/model/Post.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entitygraph/model/Post.java new file mode 100644 index 0000000000..59f17ae0c5 --- /dev/null +++ b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entitygraph/model/Post.java @@ -0,0 +1,86 @@ +package com.baeldung.jpa.entitygraph.model; + +import javax.persistence.*; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.List; + +@NamedEntityGraph( + name = "post-entity-graph", + attributeNodes = { + @NamedAttributeNode("subject"), + @NamedAttributeNode("user"), + @NamedAttributeNode("comments"), + } +) +@NamedEntityGraph( + name = "post-entity-graph-with-comment-users", + attributeNodes = { + @NamedAttributeNode("subject"), + @NamedAttributeNode("user"), + @NamedAttributeNode(value = "comments", subgraph = "comments-subgraph"), + }, + subgraphs = { + @NamedSubgraph( + name = "comments-subgraph", + attributeNodes = { + @NamedAttributeNode("user") + } + ) + } +) +@Entity +public class Post { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + private String subject; + @OneToMany(mappedBy = "post") + private List comments = new ArrayList<>(); + + @ManyToOne(fetch = FetchType.LAZY) + @JoinColumn + private User user; + //... + + public Post() { + } + + public Post(String subject, User user) { + this.subject = subject; + this.user = user; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getSubject() { + return subject; + } + + public void setSubject(String subject) { + this.subject = subject; + } + + public List getComments() { + return comments; + } + + public void setComments(List comments) { + this.comments = comments; + } + + public User getUser() { + return user; + } + + public void setUser(User user) { + this.user = user; + } +} diff --git a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entitygraph/model/User.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entitygraph/model/User.java new file mode 100644 index 0000000000..b712100d4e --- /dev/null +++ b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entitygraph/model/User.java @@ -0,0 +1,48 @@ +package com.baeldung.jpa.entitygraph.model; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; + +@Entity +public class User { + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private Long id; + private String name; + private String email; + + //... + + public User() { + } + + public User(String email) { + this.email = email; + } + + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public String getEmail() { + return email; + } + + public void setEmail(String email) { + this.email = email; + } +} diff --git a/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entitygraph/repo/PostRepository.java b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entitygraph/repo/PostRepository.java new file mode 100644 index 0000000000..28f1e1b93c --- /dev/null +++ b/persistence-modules/java-jpa/src/main/java/com/baeldung/jpa/entitygraph/repo/PostRepository.java @@ -0,0 +1,93 @@ +package com.baeldung.jpa.entitygraph.repo; + +import com.baeldung.jpa.entitygraph.model.Post; + +import javax.persistence.*; +import javax.persistence.criteria.CriteriaBuilder; +import javax.persistence.criteria.CriteriaQuery; +import javax.persistence.criteria.Root; +import java.util.HashMap; +import java.util.Map; + +public class PostRepository { + private EntityManagerFactory emf = null; + + + public PostRepository() { + Map properties = new HashMap(); + properties.put("hibernate.show_sql", "true"); + properties.put("hibernate.format_sql", "true"); + emf = Persistence.createEntityManagerFactory("entity-graph-pu", properties); + } + + public Post find(Long id) { + EntityManager entityManager = emf.createEntityManager(); + + Post post = entityManager.find(Post.class, id); + + entityManager.close(); + return post; + } + + public Post findWithEntityGraph(Long id) { + EntityManager entityManager = emf.createEntityManager(); + + EntityGraph entityGraph = entityManager.getEntityGraph("post-entity-graph"); + Map properties = new HashMap<>(); + properties.put("javax.persistence.fetchgraph", entityGraph); + Post post = entityManager.find(Post.class, id, properties); + + entityManager.close(); + return post; + } + + public Post findWithEntityGraph2(Long id) { + EntityManager entityManager = emf.createEntityManager(); + + EntityGraph entityGraph = entityManager.createEntityGraph(Post.class); + entityGraph.addAttributeNodes("subject"); + entityGraph.addAttributeNodes("user"); + entityGraph.addSubgraph("comments") + .addAttributeNodes("user"); + + Map properties = new HashMap<>(); + properties.put("javax.persistence.fetchgraph", entityGraph); + Post post = entityManager.find(Post.class, id, properties); + + entityManager.close(); + return post; + } + + public Post findUsingJpql(Long id) { + EntityManager entityManager = emf.createEntityManager(); + + EntityGraph entityGraph = entityManager.getEntityGraph("post-entity-graph-with-comment-users"); + Post post = entityManager.createQuery("Select p from Post p where p.id=:id", Post.class) + .setParameter("id", id) + .setHint("javax.persistence.fetchgraph", entityGraph) + .getSingleResult(); + + entityManager.close(); + return post; + } + + public Post findUsingCriteria(Long id) { + EntityManager entityManager = emf.createEntityManager(); + + EntityGraph entityGraph = entityManager.getEntityGraph("post-entity-graph-with-comment-users"); + CriteriaBuilder criteriaBuilder = entityManager.getCriteriaBuilder(); + CriteriaQuery criteriaQuery = criteriaBuilder.createQuery(Post.class); + Root root = criteriaQuery.from(Post.class); + criteriaQuery.where(criteriaBuilder.equal(root.get("id"), id)); + TypedQuery typedQuery = entityManager.createQuery(criteriaQuery); + typedQuery.setHint("javax.persistence.loadgraph", entityGraph); + Post post = typedQuery.getSingleResult(); + + entityManager.close(); + return post; + } + + public void clean() { + emf.close(); + } +} diff --git a/persistence-modules/java-jpa/src/main/resources/META-INF/persistence.xml b/persistence-modules/java-jpa/src/main/resources/META-INF/persistence.xml index 3fdc8ce27c..433d456cc9 100644 --- a/persistence-modules/java-jpa/src/main/resources/META-INF/persistence.xml +++ b/persistence-modules/java-jpa/src/main/resources/META-INF/persistence.xml @@ -9,12 +9,12 @@ org.hibernate.jpa.HibernatePersistenceProvider com.baeldung.sqlresultsetmapping.ScheduledDay - + - - - + value="jdbc:h2:mem:test;INIT=RUNSCRIPT FROM 'classpath:database.sql'"/> + + + @@ -25,28 +25,45 @@ org.hibernate.jpa.HibernatePersistenceProvider com.baeldung.jpa.stringcast.Message - - - - - - + + + + + + - + org.hibernate.jpa.HibernatePersistenceProvider com.baeldung.jpa.model.Car - - - - - - + + + + + + - + + + com.baeldung.jpa.entitygraph.model.Post + com.baeldung.jpa.entitygraph.model.User + com.baeldung.jpa.entitygraph.model.Comment + true + + + + + + + + + + + \ No newline at end of file diff --git a/persistence-modules/java-jpa/src/main/resources/data-init.sql b/persistence-modules/java-jpa/src/main/resources/data-init.sql new file mode 100644 index 0000000000..86c3f2a651 --- /dev/null +++ b/persistence-modules/java-jpa/src/main/resources/data-init.sql @@ -0,0 +1,8 @@ +INSERT INTO `USER` (`ID`,`NAME`,`EMAIL`) VALUES (1,'user1','user1@test.com'); +INSERT INTO `USER` (`ID`,`NAME`,`EMAIL`) VALUES (2,'user2','user2@test.com'); +INSERT INTO `USER` (`ID`,`NAME`,`EMAIL`) VALUES (3,'user3','user3@test.com'); + +INSERT INTO `POST` (`ID`,`SUBJECT`,`USER_ID`) VALUES (1,'JPA Entity Graph In Action',1); + +INSERT INTO `COMMENT` (`ID`,`REPLY`,`POST_ID`,`USER_ID`) VALUES (1,'Nice !!',1,2); +INSERT INTO `COMMENT` (`ID`,`REPLY`,`POST_ID`,`USER_ID`) VALUES (2,'Cool !!',1,3); diff --git a/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/entitygraph/repo/PostRepositoryTest.java b/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/entitygraph/repo/PostRepositoryTest.java new file mode 100644 index 0000000000..382742f223 --- /dev/null +++ b/persistence-modules/java-jpa/src/test/java/com/baeldung/jpa/entitygraph/repo/PostRepositoryTest.java @@ -0,0 +1,68 @@ +package com.baeldung.jpa.entitygraph.repo; + +import com.baeldung.jpa.entitygraph.model.Comment; +import com.baeldung.jpa.entitygraph.model.Post; +import com.baeldung.jpa.entitygraph.model.User; +import org.hibernate.LazyInitializationException; +import org.junit.AfterClass; +import org.junit.BeforeClass; +import org.junit.Test; + +import static org.junit.Assert.*; + +public class PostRepositoryTest { + + private static PostRepository postRepository = null; + + @BeforeClass + public static void once() { + postRepository = new PostRepository(); + } + + @Test(expected = LazyInitializationException.class) + public void find() { + Post post = postRepository.find(1L); + assertNotNull(post.getUser()); + String email = post.getUser().getEmail(); + assertNull(email); + } + + @Test + public void findWithEntityGraph() { + Post post = postRepository.findWithEntityGraph(1L); + assertNotNull(post.getUser()); + String email = post.getUser().getEmail(); + assertNotNull(email); + } + + @Test(expected = LazyInitializationException.class) + public void findWithEntityGraph_Comment_Without_User() { + Post post = postRepository.findWithEntityGraph(1L); + assertNotNull(post.getUser()); + String email = post.getUser().getEmail(); + assertNotNull(email); + assertNotNull(post.getComments()); + assertEquals(post.getComments().size(), 2); + Comment comment = post.getComments().get(0); + assertNotNull(comment); + User user = comment.getUser(); + user.getEmail(); + } + + @Test + public void findWithEntityGraph2_Comment_With_User() { + Post post = postRepository.findWithEntityGraph2(1L); + assertNotNull(post.getComments()); + assertEquals(post.getComments().size(), 2); + Comment comment = post.getComments().get(0); + assertNotNull(comment); + User user = comment.getUser(); + assertNotNull(user); + assertEquals(user.getEmail(), "user2@test.com"); + } + + @AfterClass + public static void destroy() { + postRepository.clean(); + } +} \ No newline at end of file