[JAVA-11226] Fix and update Hibernate OneToMany code (#12031)

This commit is contained in:
Haroon Khan 2022-04-11 15:55:30 +01:00 committed by GitHub
parent 813b27588e
commit 4ad546c702
15 changed files with 243 additions and 182 deletions

View File

@ -82,7 +82,7 @@
<!-- Spring -->
<org.springframework.version>5.0.2.RELEASE</org.springframework.version>
<org.springframework.data.version>1.10.6.RELEASE</org.springframework.data.version>
<hibernate-core.version>5.4.7.Final</hibernate-core.version>
<hibernate-core.version>5.6.7.Final</hibernate-core.version>
<maven.deploy.skip>true</maven.deploy.skip>
<spring-boot.version>2.1.7.RELEASE</spring-boot.version>
<h2.version>1.4.200</h2.version>

View File

@ -1,34 +1,51 @@
package com.baeldung.hibernate.oneToMany.config;
import com.baeldung.hibernate.oneToMany.model.Cart;
import com.baeldung.hibernate.oneToMany.model.CartOIO;
import com.baeldung.hibernate.oneToMany.model.Item;
import com.baeldung.hibernate.oneToMany.model.ItemOIO;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.model.naming.ImplicitNamingStrategyJpaCompliantImpl;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.service.ServiceRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HibernateAnnotationUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(HibernateAnnotationUtil.class);
private static SessionFactory sessionFactory;
public static SessionFactory getSessionFactory() {
if (sessionFactory == null) {
sessionFactory = buildSessionFactory();
}
return 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();
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
.configure("hibernate-annotation.cfg.xml")
.build();
return sessionFactory;
Metadata metadata = new MetadataSources(serviceRegistry)
.addAnnotatedClass(Cart.class)
.addAnnotatedClass(CartOIO.class)
.addAnnotatedClass(Item.class)
.addAnnotatedClass(ItemOIO.class)
.getMetadataBuilder()
.applyImplicitNamingStrategy(ImplicitNamingStrategyJpaCompliantImpl.INSTANCE)
.build();
return metadata.getSessionFactoryBuilder().build();
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
ex.printStackTrace();
LOGGER.error("Initial SessionFactory creation failed.", ex);
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.Item;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HibernateManyIsOwningSide {
private static final Logger LOGGER = LoggerFactory.getLogger(HibernateManyIsOwningSide.class);
public static void main(String[] args) {
Cart cart = new Cart();
Cart cart2 = new Cart();
Item item1 = new Item(cart);
Item item2 = new Item(cart2);
Set<Item> itemsSet = new HashSet<>();
itemsSet.add(item1);
itemsSet.add(item2);
cart.setItems(itemsSet);
// Get Session
SessionFactory sessionFactory = HibernateAnnotationUtil.getSessionFactory();
Session session = sessionFactory.getCurrentSession();
try {
LOGGER.info("Session created");
// start transaction
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 = session.get(Item.class, 1L);
item2 = session.get(Item.class, 2L);
tx.commit();
LOGGER.info("item1 ID={}, Foreign Key CartOIO ID={}", item1.getId(), item1.getCart().getId());
LOGGER.info("item2 ID={}, Foreign Key CartOIO ID={}", item2.getId(), item2.getCart().getId());
} catch (Exception e) {
LOGGER.error("Exception occurred", e);
} finally {
if (!sessionFactory.isClosed()) {
LOGGER.info("Closing SessionFactory");
sessionFactory.close();
}
}
}
}

View File

@ -1,71 +0,0 @@
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

@ -9,57 +9,59 @@ 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;
import com.baeldung.hibernate.oneToMany.model.ItemOIO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HibernateOneIsOwningSide {
private static final Logger LOGGER = LoggerFactory.getLogger(HibernateOneIsOwningSide.class);
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>();
ItemOIO item1 = new ItemOIO(cart);
ItemOIO item2 = new ItemOIO(cart2);
Set<ItemOIO> itemsSet = new HashSet<>();
itemsSet.add(item1);
itemsSet.add(item2);
cart.setItems(itemsSet);
SessionFactory sessionFactory = null;
Session session = null;
Transaction tx = null;
SessionFactory sessionFactory = HibernateAnnotationUtil.getSessionFactory();
Session session = sessionFactory.getCurrentSession();
LOGGER.info("Session created");
Transaction tx;
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));
item1 = session.get(ItemOIO.class, 1L);
item2 = session.get(ItemOIO.class, 2L);
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());
LOGGER.info("item1 ID={}, Foreign Key CartOIO ID={}", item1.getId(), item1.getCartOIO().getId());
LOGGER.info("item2 ID={}, Foreign Key CartOIO ID={}", item2.getId(), item2.getCartOIO().getId());
} catch (Exception e) {
System.out.println("Exception occured. " + e.getMessage());
e.printStackTrace();
LOGGER.error("Exception occurred", e);
} finally {
if (!sessionFactory.isClosed()) {
System.out.println("Closing SessionFactory");
LOGGER.info("Closing SessionFactory");
sessionFactory.close();
}
}

View File

@ -9,52 +9,53 @@ 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.Item;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HibernateOneToManyAnnotationMain {
private static final Logger LOGGER = LoggerFactory.getLogger(HibernateOneToManyAnnotationMain.class);
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>();
Item item1 = new Item(cart);
Item item2 = new Item(cart);
Set<Item> itemsSet = new HashSet<>();
itemsSet.add(item1);
itemsSet.add(item2);
cart.setItems(itemsSet);
SessionFactory sessionFactory = null;
Session session = null;
Transaction tx = null;
SessionFactory sessionFactory = HibernateAnnotationUtil.getSessionFactory();
Session session = sessionFactory.getCurrentSession();
LOGGER.info("Session created");
try {
// Get Session
sessionFactory = HibernateAnnotationUtil.getSessionFactory();
session = sessionFactory.getCurrentSession();
System.out.println("Session created");
// start transaction
tx = session.beginTransaction();
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());
LOGGER.info("Cart ID={}", cart.getId());
LOGGER.info("item1 ID={}, Foreign Key Cart ID={}", item1.getId(), item1.getCart().getId());
LOGGER.info("item2 ID={}, Foreign Key Cart ID={}", item2.getId(), item2.getCart().getId());
} catch (Exception e) {
System.out.println("Exception occured. " + e.getMessage());
e.printStackTrace();
LOGGER.error("Exception occurred", e);
} finally {
if (!sessionFactory.isClosed()) {
System.out.println("Closing SessionFactory");
LOGGER.info("Closing SessionFactory");
sessionFactory.close();
}
}
}
}

View File

@ -19,9 +19,8 @@ public class Cart {
@Column(name = "cart_id")
private long id;
@OneToMany(mappedBy = "cart")
private Set<Items> items;
private Set<Item> items;
public long getId() {
return id;
@ -31,12 +30,11 @@ public class Cart {
this.id = id;
}
public Set<Items> getItems() {
public Set<Item> getItems() {
return items;
}
public void setItems(Set<Items> items) {
public void setItems(Set<Item> items) {
this.items = items;
}

View File

@ -9,8 +9,6 @@ import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Table(name = "CARTOIO")
public class CartOIO {
@ -21,7 +19,7 @@ public class CartOIO {
@OneToMany
@JoinColumn(name = "cart_id") // we need to duplicate the physical information
private Set<ItemsOIO> items;
private Set<ItemOIO> items;
public long getId() {
return id;
@ -31,11 +29,11 @@ public class CartOIO {
this.id = id;
}
public Set<ItemsOIO> getItems() {
public Set<ItemOIO> getItems() {
return items;
}
public void setItems(Set<ItemsOIO> items) {
public void setItems(Set<ItemOIO> items) {
this.items = items;
}

View File

@ -11,23 +11,22 @@ import javax.persistence.Table;
@Entity
@Table(name = "ITEMS")
public class Items {
public class Item {
@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 Item() {
}
public Items(Cart c) {
public Item(Cart c) {
this.cart = c;
}

View File

@ -10,7 +10,7 @@ import javax.persistence.Table;
@Entity
@Table(name = "ITEMSOIO")
public class ItemsOIO {
public class ItemOIO {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@ -21,10 +21,10 @@ public class ItemsOIO {
private CartOIO cart;
// Hibernate requires no-args constructor
public ItemsOIO() {
public ItemOIO() {
}
public ItemsOIO(CartOIO c) {
public ItemOIO(CartOIO c) {
this.cart = c;
}

View File

@ -0,0 +1,18 @@
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">org.h2.Driver</property>
<property name="hibernate.connection.username">sa</property>
<property name="hibernate.connection.password"/>
<property name="hibernate.connection.url">jdbc:h2:mem:spring_hibernate_one_to_many</property>
<property name="hibernate.dialect">org.hibernate.dialect.H2Dialect</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.show_sql">true</property>
<property name="hbm2ddl.auto">create</property>
</session-factory>
</hibernate-configuration>

View File

@ -0,0 +1,31 @@
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d %-5p [%t] %C{2} (%F:%L) - %m%n"/>
</layout>
</appender>
<logger name="org.hibernate">
<level value="info" />
</logger>
<logger name="org.hibernate.SQL">
<level value="info" />
</logger>
<logger name="org.hibernate.type.descriptor.sql">
<level value="info" />
</logger>
<logger name="org.hibernate.stat">
<level value="info" />
</logger>
<root>
<priority value ="info" />
<appender-ref ref="STDOUT" />
</root>
</log4j:configuration>

View File

@ -1,26 +1,21 @@
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 com.baeldung.hibernate.oneToMany.config.HibernateAnnotationUtil;
import com.baeldung.hibernate.oneToMany.model.Cart;
import com.baeldung.hibernate.oneToMany.model.Item;
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;
import java.util.HashSet;
import java.util.Set;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
public class HibernateOneToManyAnnotationMainIntegrationTest {
@ -28,20 +23,9 @@ public class HibernateOneToManyAnnotationMainIntegrationTest {
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);
sessionFactory = HibernateAnnotationUtil.getSessionFactory();
}
@Before
@ -52,32 +36,38 @@ public class HibernateOneToManyAnnotationMainIntegrationTest {
@Test
public void givenSession_checkIfDatabaseIsEmpty() {
Cart cart = (Cart) session.get(Cart.class, new Long(1));
Cart cart = session.get(Cart.class, 1L);
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();
Set<Item> cartItems = cart.getItems();
assertNull(cartItems);
Item item1 = new Item();
item1.setCart(cart);
assertNotNull(item1);
Set<Items> itemsSet = new HashSet<Items>();
itemsSet.add(item1);
assertNotNull(itemsSet);
cart.setItems(itemsSet);
Set<Item> itemSet = new HashSet<>();
itemSet.add(item1);
assertNotNull(itemSet);
cart.setItems(itemSet);
assertNotNull(cart);
session.persist(cart);
session.getTransaction().commit();
session.close();
session = sessionFactory.openSession();
session.beginTransaction();
cart = (Cart) session.get(Cart.class, new Long(1));
cart = session.get(Cart.class, 1L);
assertNotNull(cart);
}

View File

@ -1,24 +1,31 @@
<?xml version="1.0" encoding="UTF-8"?>
<configuration xmlns:log4j='http://jakarta.apache.org/log4j/'>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
<appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d %-5p [%t] %C{2} (%F:%L) - %m%n"/>
</layout>
</appender>
<logger name="org.hibernate">
<level value="info" />
</logger>
<logger name="org.hibernate.SQL">
<level value="info" />
</logger>
<logger name="org.hibernate.type.descriptor.sql">
<level value="info" />
</logger>
</logger>
<logger name="org.hibernate.stat">
<level value="info" />
</logger>
<root>
<priority value ="info" />
<appender-ref ref="STDOUT" />
</root>
</configuration>
</log4j:configuration>

Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.1 KiB