JAVA-4: renamed to hibernate-annotations, moved couple of articles

This commit is contained in:
sampadawagde 2020-03-15 12:37:57 +05:30
parent 9017080633
commit d2d2a890fa
15 changed files with 799 additions and 4 deletions

View File

@ -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)

View File

@ -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;
}
}

View File

@ -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<Items> itemsSet = new HashSet<Items>();
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();
}
}
}
}

View File

@ -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<Items> itemsSet = new HashSet<Items>();
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();
}
}
}
}

View File

@ -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<ItemsOIO> itemsSet = new HashSet<ItemsOIO>();
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();
}
}
}
}

View File

@ -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> items;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Set<Items> getItems() {
return items;
}
public void setItems(Set<Items> items) {
this.items = items;
}
}

View File

@ -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<ItemsOIO> items;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Set<ItemsOIO> getItems() {
return items;
}
public void setItems(Set<ItemsOIO> items) {
this.items = items;
}
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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<User> 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<User> getUsers() {
return users;
}
public void setUsers(List<User> users) {
this.users = users;
}
@Override
public String toString() {
return "Group [name=" + name + "]";
}
}

View File

@ -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<Group> 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<Group> 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<Group> getGroups() {
return groups;
}
public void setGroups(List<Group> groups) {
this.groups = groups;
}
public void setModeratorGroups(List<Group> moderatorGroups) {
this.moderatorGroups = moderatorGroups;
}
public List<Group> getModeratorGroups() {
return moderatorGroups;
}
@Override
public String toString() {
return "User [name=" + name + "]";
}
}

View File

@ -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;
}
}

View File

@ -0,0 +1,7 @@
package com.baeldung.hibernate.wherejointable;
public enum UserGroupRole {
MEMBER, MODERATOR
}

View File

@ -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<Items> cartItems = new HashSet<>();
cartItems = cart.getItems();
Assert.assertNull(cartItems);
Items item1 = new Items();
item1.setCart(cart);
assertNotNull(item1);
Set<Items> itemsSet = new HashSet<Items>();
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();
}
}

View File

@ -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<Group> groups = user1.getGroups();
assertEquals(2, groups.size());
assertTrue(groups.contains(group1));
assertTrue(groups.contains(group2));
}
@Test
public void givenUser1_getModeratorGroups_returnsOnlyModeratorGroups() {
List<Group> 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);
}
}