diff --git a/persistence-modules/hibernate5-annotations/README.md b/persistence-modules/hibernate5-annotations/README.md index da3c5ad1fd..2813dbdda3 100644 --- a/persistence-modules/hibernate5-annotations/README.md +++ b/persistence-modules/hibernate5-annotations/README.md @@ -1,10 +1,10 @@ -## Hibernate 5 +## Hibernate Annotations -This module contains articles about Hibernate 5. +This module contains articles about Hibernate Annotations. ### Relevant Articles: - [Custom Types in Hibernate and the @Type Annotation](https://www.baeldung.com/hibernate-custom-types) -- [@Immutable in Hibernate](http://www.baeldung.com/hibernate-immutable) - [@JoinColumn Annotation Explained](https://www.baeldung.com/jpa-join-column) - [Difference Between @JoinColumn and mappedBy](https://www.baeldung.com/jpa-joincolumn-vs-mappedby) - +- [Hibernate One to Many Annotation Tutorial](http://www.baeldung.com/hibernate-one-to-many) +- [Hibernate @WhereJoinTable Annotation](https://www.baeldung.com/hibernate-wherejointable) diff --git a/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java new file mode 100644 index 0000000000..46e6824f42 --- /dev/null +++ b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/oneToMany/config/HibernateAnnotationUtil.java @@ -0,0 +1,34 @@ +package com.baeldung.hibernate.oneToMany.config; + +import org.hibernate.SessionFactory; +import org.hibernate.boot.Metadata; +import org.hibernate.boot.MetadataSources; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.service.ServiceRegistry; + +public class HibernateAnnotationUtil { + + private static SessionFactory sessionFactory; + + private static SessionFactory buildSessionFactory() { + try { + // Create the SessionFactory from hibernate-annotation.cfg.xml + ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().configure("hibernate-annotation.cfg.xml").build(); + Metadata metadata = new MetadataSources(serviceRegistry).getMetadataBuilder().build(); + SessionFactory sessionFactory = metadata.getSessionFactoryBuilder().build(); + + return sessionFactory; + + } catch (Throwable ex) { + System.err.println("Initial SessionFactory creation failed." + ex); + ex.printStackTrace(); + throw new ExceptionInInitializerError(ex); + } + } + + public static SessionFactory getSessionFactory() { + if (sessionFactory == null) + sessionFactory = buildSessionFactory(); + return sessionFactory; + } +} diff --git a/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateManyisOwningSide.java b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateManyisOwningSide.java new file mode 100644 index 0000000000..372fb2fc07 --- /dev/null +++ b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateManyisOwningSide.java @@ -0,0 +1,71 @@ +package com.baeldung.hibernate.oneToMany.main; + +import java.util.HashSet; +import java.util.Set; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; + +import com.baeldung.hibernate.oneToMany.config.HibernateAnnotationUtil; +import com.baeldung.hibernate.oneToMany.model.Cart; +import com.baeldung.hibernate.oneToMany.model.Items; +import com.baeldung.hibernate.oneToMany.model.ItemsOIO; + +public class HibernateManyisOwningSide { + public static void main(String[] args) { + + Cart cart = new Cart(); + Cart cart2 = new Cart(); + + Items item1 = new Items(cart); + Items item2 = new Items(cart2); + Set itemsSet = new HashSet(); + itemsSet.add(item1); + itemsSet.add(item2); + + cart.setItems(itemsSet); + + + + SessionFactory sessionFactory = null; + Session session = null; + Transaction tx = null; + try { + // Get Session + sessionFactory = HibernateAnnotationUtil.getSessionFactory(); + session = sessionFactory.getCurrentSession(); + System.out.println("Session created"); + // start transaction + tx = session.beginTransaction(); + // Save the Model object + session.save(cart); + session.save(cart2); + session.save(item1); + session.save(item2); + // Commit transaction + tx.commit(); + session = sessionFactory.getCurrentSession(); + tx = session.beginTransaction(); + + item1 = (Items) session.get(Items.class, new Long(1)); + item2 = (Items) session.get(Items.class, new Long(2)); + tx.commit(); + + + System.out.println("item1 ID=" + item1.getId() + ", Foreign Key CartOIO ID=" + item1.getCart() + .getId()); + System.out.println("item2 ID=" + item2.getId() + ", Foreign Key CartOIO ID=" + item2.getCart() + .getId()); + + } catch (Exception e) { + System.out.println("Exception occured. " + e.getMessage()); + e.printStackTrace(); + } finally { + if (!sessionFactory.isClosed()) { + System.out.println("Closing SessionFactory"); + sessionFactory.close(); + } + } + } +} diff --git a/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMain.java b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMain.java new file mode 100644 index 0000000000..2bc5e514f7 --- /dev/null +++ b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMain.java @@ -0,0 +1,60 @@ +package com.baeldung.hibernate.oneToMany.main; + +import java.util.HashSet; +import java.util.Set; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; + +import com.baeldung.hibernate.oneToMany.config.HibernateAnnotationUtil; +import com.baeldung.hibernate.oneToMany.model.Cart; +import com.baeldung.hibernate.oneToMany.model.Items; + +public class HibernateOneToManyAnnotationMain { + + public static void main(String[] args) { + + Cart cart = new Cart(); + + Items item1 = new Items(cart); + Items item2 = new Items(cart); + Set itemsSet = new HashSet(); + itemsSet.add(item1); + itemsSet.add(item2); + + cart.setItems(itemsSet); + + + SessionFactory sessionFactory = null; + Session session = null; + Transaction tx = null; + try { + // Get Session + sessionFactory = HibernateAnnotationUtil.getSessionFactory(); + session = sessionFactory.getCurrentSession(); + System.out.println("Session created"); + // start transaction + tx = session.beginTransaction(); + // Save the Model object + session.save(cart); + session.save(item1); + session.save(item2); + // Commit transaction + tx.commit(); + System.out.println("Cart ID=" + cart.getId()); + System.out.println("item1 ID=" + item1.getId() + ", Foreign Key Cart ID=" + item1.getCart().getId()); + System.out.println("item2 ID=" + item2.getId() + ", Foreign Key Cart ID=" + item1.getCart().getId()); + + } catch (Exception e) { + System.out.println("Exception occured. " + e.getMessage()); + e.printStackTrace(); + } finally { + if (!sessionFactory.isClosed()) { + System.out.println("Closing SessionFactory"); + sessionFactory.close(); + } + } + } + +} diff --git a/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneisOwningSide.java b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneisOwningSide.java new file mode 100644 index 0000000000..0777664dd0 --- /dev/null +++ b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/oneToMany/main/HibernateOneisOwningSide.java @@ -0,0 +1,67 @@ +package com.baeldung.hibernate.oneToMany.main; + +import java.util.HashSet; +import java.util.Set; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.Transaction; + +import com.baeldung.hibernate.oneToMany.config.HibernateAnnotationUtil; +import com.baeldung.hibernate.oneToMany.model.CartOIO; +import com.baeldung.hibernate.oneToMany.model.ItemsOIO; + +public class HibernateOneisOwningSide { + public static void main(String[] args) { + + CartOIO cart = new CartOIO(); + CartOIO cart2 = new CartOIO(); + + ItemsOIO item1 = new ItemsOIO(cart); + ItemsOIO item2 = new ItemsOIO(cart2); + Set itemsSet = new HashSet(); + itemsSet.add(item1); + itemsSet.add(item2); + + cart.setItems(itemsSet); + + SessionFactory sessionFactory = null; + Session session = null; + Transaction tx = null; + try { + // Get Session + sessionFactory = HibernateAnnotationUtil.getSessionFactory(); + session = sessionFactory.getCurrentSession(); + System.out.println("Session created"); + // start transaction + tx = session.beginTransaction(); + // Save the Model object + session.save(cart); + session.save(cart2); + session.save(item1); + session.save(item2); + // Commit transaction + tx.commit(); + + session = sessionFactory.getCurrentSession(); + tx = session.beginTransaction(); + item1 = (ItemsOIO) session.get(ItemsOIO.class, new Long(1)); + item2 = (ItemsOIO) session.get(ItemsOIO.class, new Long(2)); + tx.commit(); + + System.out.println("item1 ID=" + item1.getId() + ", Foreign Key CartOIO ID=" + item1.getCartOIO() + .getId()); + System.out.println("item2 ID=" + item2.getId() + ", Foreign Key CartOIO ID=" + item2.getCartOIO() + .getId()); + + } catch (Exception e) { + System.out.println("Exception occured. " + e.getMessage()); + e.printStackTrace(); + } finally { + if (!sessionFactory.isClosed()) { + System.out.println("Closing SessionFactory"); + sessionFactory.close(); + } + } + } +} diff --git a/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java new file mode 100644 index 0000000000..b8b991831e --- /dev/null +++ b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Cart.java @@ -0,0 +1,43 @@ +package com.baeldung.hibernate.oneToMany.model; + +import java.util.Set; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.OneToMany; +import javax.persistence.Table; + +@Entity +@Table(name = "CART") +public class Cart { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "cart_id") + private long id; + + + @OneToMany(mappedBy = "cart") + private Set items; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + + public Set getItems() { + return items; + } + + public void setItems(Set items) { + this.items = items; + } + +} diff --git a/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/CartOIO.java b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/CartOIO.java new file mode 100644 index 0000000000..8a5ed5e7a4 --- /dev/null +++ b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/CartOIO.java @@ -0,0 +1,42 @@ +package com.baeldung.hibernate.oneToMany.model; + +import java.util.Set; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.OneToMany; +import javax.persistence.Table; + + + +@Entity +@Table(name = "CARTOIO") +public class CartOIO { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private long id; + + @OneToMany + @JoinColumn(name = "cart_id") // we need to duplicate the physical information + private Set items; + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + + public Set getItems() { + return items; + } + + public void setItems(Set items) { + this.items = items; + } + +} diff --git a/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Items.java b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Items.java new file mode 100644 index 0000000000..f63a4855b5 --- /dev/null +++ b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/Items.java @@ -0,0 +1,50 @@ +package com.baeldung.hibernate.oneToMany.model; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.Table; + +@Entity +@Table(name = "ITEMS") +public class Items { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + @Column(name = "id") + private long id; + + + @ManyToOne + @JoinColumn(name = "cart_id", nullable = false) + private Cart cart; + + // Hibernate requires no-args constructor + public Items() { + } + + public Items(Cart c) { + this.cart = c; + } + + public Cart getCart() { + return cart; + } + + public void setCart(Cart cart) { + this.cart = cart; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + +} diff --git a/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/ItemsOIO.java b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/ItemsOIO.java new file mode 100644 index 0000000000..a3d6a796c5 --- /dev/null +++ b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/oneToMany/model/ItemsOIO.java @@ -0,0 +1,47 @@ +package com.baeldung.hibernate.oneToMany.model; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.GenerationType; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.ManyToOne; +import javax.persistence.Table; + +@Entity +@Table(name = "ITEMSOIO") +public class ItemsOIO { + + @Id + @GeneratedValue(strategy = GenerationType.IDENTITY) + private long id; + + @ManyToOne + @JoinColumn(name = "cart_id", insertable = false, updatable = false) + private CartOIO cart; + + // Hibernate requires no-args constructor + public ItemsOIO() { + } + + public ItemsOIO(CartOIO c) { + this.cart = c; + } + + public CartOIO getCartOIO() { + return cart; + } + + public void setCartOIO(CartOIO cart) { + this.cart = cart; + } + + public long getId() { + return id; + } + + public void setId(long id) { + this.id = id; + } + +} diff --git a/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/wherejointable/Group.java b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/wherejointable/Group.java new file mode 100644 index 0000000000..04684eceac --- /dev/null +++ b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/wherejointable/Group.java @@ -0,0 +1,56 @@ +package com.baeldung.hibernate.wherejointable; + +import java.util.ArrayList; +import java.util.List; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.ManyToMany; + +@Entity(name = "e_group") +public class Group { + + @Id + @GeneratedValue + private Long id; + + private String name; + + @ManyToMany(mappedBy = "groups") + private List users = new ArrayList<>(); + + public Group(String name) { + this.name = name; + } + + 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 List getUsers() { + return users; + } + + public void setUsers(List users) { + this.users = users; + } + + @Override + public String toString() { + return "Group [name=" + name + "]"; + } + +} diff --git a/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/wherejointable/User.java b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/wherejointable/User.java new file mode 100644 index 0000000000..7fc077eeb2 --- /dev/null +++ b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/wherejointable/User.java @@ -0,0 +1,74 @@ +package com.baeldung.hibernate.wherejointable; + +import java.util.ArrayList; +import java.util.List; + +import javax.persistence.Entity; +import javax.persistence.GeneratedValue; +import javax.persistence.Id; +import javax.persistence.JoinColumn; +import javax.persistence.JoinTable; +import javax.persistence.ManyToMany; + +import org.hibernate.annotations.WhereJoinTable; + +@Entity +public class User { + + @Id + @GeneratedValue + private Long id; + + private String name; + + @ManyToMany + @JoinTable(name = "r_user_group", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "group_id")) + private List groups = new ArrayList<>(); + + @WhereJoinTable(clause = "role='MODERATOR'") + @ManyToMany + @JoinTable(name = "r_user_group", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "group_id")) + private List moderatorGroups = new ArrayList<>(); + + public User(String name) { + this.name = name; + } + + 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 List getGroups() { + return groups; + } + + public void setGroups(List groups) { + this.groups = groups; + } + + public void setModeratorGroups(List moderatorGroups) { + this.moderatorGroups = moderatorGroups; + } + + public List getModeratorGroups() { + return moderatorGroups; + } + + @Override + public String toString() { + return "User [name=" + name + "]"; + } + +} diff --git a/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/wherejointable/UserGroupRelation.java b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/wherejointable/UserGroupRelation.java new file mode 100644 index 0000000000..00dd19699c --- /dev/null +++ b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/wherejointable/UserGroupRelation.java @@ -0,0 +1,31 @@ +package com.baeldung.hibernate.wherejointable; + +import java.io.Serializable; + +import javax.persistence.Column; +import javax.persistence.Entity; +import javax.persistence.EnumType; +import javax.persistence.Enumerated; +import javax.persistence.Id; + +@Entity(name = "r_user_group") +public class UserGroupRelation implements Serializable { + + @Id + @Column(name = "user_id", insertable = false, updatable = false) + private final Long userId; + + @Id + @Column(name = "group_id", insertable = false, updatable = false) + private final Long groupId; + + @Enumerated(EnumType.STRING) + private final UserGroupRole role; + + public UserGroupRelation(Long userId, Long groupId, UserGroupRole role) { + this.userId = userId; + this.groupId = groupId; + this.role = role; + } + +} diff --git a/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/wherejointable/UserGroupRole.java b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/wherejointable/UserGroupRole.java new file mode 100644 index 0000000000..62d9cb28ea --- /dev/null +++ b/persistence-modules/hibernate5-annotations/src/main/java/com/baeldung/hibernate/wherejointable/UserGroupRole.java @@ -0,0 +1,7 @@ +package com.baeldung.hibernate.wherejointable; + +public enum UserGroupRole { + + MEMBER, MODERATOR + +} diff --git a/persistence-modules/hibernate5-annotations/src/test/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMainIntegrationTest.java b/persistence-modules/hibernate5-annotations/src/test/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMainIntegrationTest.java new file mode 100644 index 0000000000..3bc5a6e12a --- /dev/null +++ b/persistence-modules/hibernate5-annotations/src/test/java/com/baeldung/hibernate/oneToMany/main/HibernateOneToManyAnnotationMainIntegrationTest.java @@ -0,0 +1,95 @@ +package com.baeldung.hibernate.oneToMany.main; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; + +import java.util.HashSet; +import java.util.Set; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.cfg.Configuration; +import org.hibernate.dialect.H2Dialect; +import org.hibernate.service.ServiceRegistry; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +import com.baeldung.hibernate.oneToMany.model.Cart; +import com.baeldung.hibernate.oneToMany.model.Items; + +public class HibernateOneToManyAnnotationMainIntegrationTest { + + private static SessionFactory sessionFactory; + + private Session session; + + public HibernateOneToManyAnnotationMainIntegrationTest() { + } + + @BeforeClass + public static void beforeTests() { + Configuration configuration = new Configuration().addAnnotatedClass(Cart.class).addAnnotatedClass(Items.class) + .setProperty("hibernate.dialect", H2Dialect.class.getName()) + .setProperty("hibernate.connection.driver_class", org.h2.Driver.class.getName()) + .setProperty("hibernate.connection.url", "jdbc:h2:mem:test") + .setProperty("hibernate.connection.username", "sa").setProperty("hibernate.connection.password", "") + .setProperty("hibernate.hbm2ddl.auto", "update"); + ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() + .applySettings(configuration.getProperties()).build(); + sessionFactory = configuration.buildSessionFactory(serviceRegistry); + } + + @Before + public void setUp() { + session = sessionFactory.openSession(); + session.beginTransaction(); + } + + @Test + public void givenSession_checkIfDatabaseIsEmpty() { + Cart cart = (Cart) session.get(Cart.class, new Long(1)); + assertNull(cart); + + } + + @Test + public void givenSession_checkIfDatabaseIsPopulated_afterCommit() { + Cart cart = new Cart(); + Set cartItems = new HashSet<>(); + cartItems = cart.getItems(); + Assert.assertNull(cartItems); + Items item1 = new Items(); + item1.setCart(cart); + assertNotNull(item1); + Set itemsSet = new HashSet(); + itemsSet.add(item1); + assertNotNull(itemsSet); + cart.setItems(itemsSet); + assertNotNull(cart); + session.persist(cart); + session.getTransaction().commit(); + session.close(); + + session = sessionFactory.openSession(); + session.beginTransaction(); + cart = (Cart) session.get(Cart.class, new Long(1)); + assertNotNull(cart); + } + + @After + public void tearDown() { + session.getTransaction().commit(); + session.close(); + } + + @AfterClass + public static void afterTests() { + sessionFactory.close(); + } + +} diff --git a/persistence-modules/hibernate5-annotations/src/test/java/com/baeldung/hibernate/wherejointable/HibernateWhereJoinTableIntegrationTest.java b/persistence-modules/hibernate5-annotations/src/test/java/com/baeldung/hibernate/wherejointable/HibernateWhereJoinTableIntegrationTest.java new file mode 100644 index 0000000000..93783216ce --- /dev/null +++ b/persistence-modules/hibernate5-annotations/src/test/java/com/baeldung/hibernate/wherejointable/HibernateWhereJoinTableIntegrationTest.java @@ -0,0 +1,118 @@ +package com.baeldung.hibernate.wherejointable; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; + +import java.util.List; + +import org.hibernate.Session; +import org.hibernate.SessionFactory; +import org.hibernate.boot.registry.StandardServiceRegistryBuilder; +import org.hibernate.cfg.Configuration; +import org.hibernate.dialect.H2Dialect; +import org.hibernate.service.ServiceRegistry; +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; + +public class HibernateWhereJoinTableIntegrationTest { + + private static SessionFactory sessionFactory; + + private Session session; + + /** + * Test data + */ + private User user1; + private User user2; + private User user3; + private Group group1; + private Group group2; + + @BeforeClass + public static void beforeTests() { + Configuration configuration = new Configuration().addAnnotatedClass(User.class) + .addAnnotatedClass(Group.class) + .addAnnotatedClass(UserGroupRelation.class) + .setProperty("hibernate.dialect", H2Dialect.class.getName()) + .setProperty("hibernate.connection.driver_class", org.h2.Driver.class.getName()) + .setProperty("hibernate.connection.url", "jdbc:h2:mem:test") + .setProperty("hibernate.connection.username", "sa") + .setProperty("hibernate.connection.password", "") + .setProperty("hibernate.hbm2ddl.auto", "update"); + + ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() + .applySettings(configuration.getProperties()) + .build(); + + sessionFactory = configuration.buildSessionFactory(serviceRegistry); + } + + @Before + public void setUp() { + session = sessionFactory.openSession(); + session.beginTransaction(); + + user1 = new User("user1"); + user2 = new User("user2"); + user3 = new User("user3"); + + group1 = new Group("group1"); + group2 = new Group("group2"); + + session.save(group1); + session.save(group2); + + session.save(user1); + session.save(user2); + session.save(user3); + + saveRelation(user1, group1, UserGroupRole.MODERATOR); + saveRelation(user2, group1, UserGroupRole.MODERATOR); + saveRelation(user3, group1, UserGroupRole.MEMBER); + + saveRelation(user1, group2, UserGroupRole.MEMBER); + saveRelation(user2, group2, UserGroupRole.MODERATOR); + } + + @After + public void tearDown() { + session.getTransaction().commit(); + session.close(); + } + + @AfterClass + public static void afterTests() { + sessionFactory.close(); + } + + @Test + public void givenUser1_getGroups_returnsAllGroups() { + List groups = user1.getGroups(); + assertEquals(2, groups.size()); + + assertTrue(groups.contains(group1)); + assertTrue(groups.contains(group2)); + } + + @Test + public void givenUser1_getModeratorGroups_returnsOnlyModeratorGroups() { + List groups = user1.getModeratorGroups(); + assertEquals(1, groups.size()); + + assertTrue(groups.contains(group1)); + } + + private void saveRelation(User user, Group group, UserGroupRole role) { + UserGroupRelation relation = new UserGroupRelation(user.getId(), group.getId(), role); + + session.save(relation); + session.flush(); + session.refresh(user); + session.refresh(group); + } + +}