Merge pull request #7257 from amit2103/BAEL-14774
[BAEL-14774] - Updated Hibernate @OneToMany article code
This commit is contained in:
@@ -9,7 +9,6 @@
|
||||
- [Stored Procedures with Hibernate](http://www.baeldung.com/stored-procedures-with-hibernate-tutorial)
|
||||
- [Hibernate: save, persist, update, merge, saveOrUpdate](http://www.baeldung.com/hibernate-save-persist-update-merge-saveorupdate)
|
||||
- [Eager/Lazy Loading In Hibernate](http://www.baeldung.com/hibernate-lazy-eager-loading)
|
||||
- [Hibernate One to Many Annotation Tutorial](http://www.baeldung.com/hibernate-one-to-many)
|
||||
- [The DAO with Spring and Hibernate](http://www.baeldung.com/persistence-layer-with-spring-and-hibernate)
|
||||
|
||||
### Quick Start
|
||||
|
||||
@@ -1,37 +0,0 @@
|
||||
package com.baeldung.hibernate.oneToMany.config;
|
||||
|
||||
import org.hibernate.SessionFactory;
|
||||
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
|
||||
import org.hibernate.cfg.Configuration;
|
||||
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
|
||||
Configuration configuration = new Configuration();
|
||||
configuration.configure("hibernate-annotation.cfg.xml");
|
||||
System.out.println("Hibernate Annotation Configuration loaded");
|
||||
|
||||
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
|
||||
System.out.println("Hibernate Annotation serviceRegistry created");
|
||||
|
||||
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,60 +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;
|
||||
|
||||
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();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,67 +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.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();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,50 +0,0 @@
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE hibernate-configuration PUBLIC
|
||||
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
|
||||
"http://hibernate.org/dtd/hibernate-configuration-3.0.dtd">
|
||||
<hibernate-configuration>
|
||||
<session-factory>
|
||||
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
|
||||
<property name="hibernate.connection.password">mypassword</property>
|
||||
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/spring_hibernate_one_to_many?createDatabaseIfNotExist=true</property>
|
||||
<property name="hibernate.connection.username">myuser</property>
|
||||
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
|
||||
<property name="hbm2ddl.auto">create</property>
|
||||
<property name="hibernate.current_session_context_class">thread</property>
|
||||
<property name="hibernate.show_sql">true</property>
|
||||
|
||||
<mapping class="com.baeldung.hibernate.oneToMany.model.Cart"/>
|
||||
<mapping class="com.baeldung.hibernate.oneToMany.model.Items"/>
|
||||
<mapping class="com.baeldung.hibernate.oneToMany.model.CartOIO"/>
|
||||
<mapping class="com.baeldung.hibernate.oneToMany.model.ItemsOIO"/>
|
||||
</session-factory>
|
||||
</hibernate-configuration>
|
||||
@@ -1,12 +0,0 @@
|
||||
CREATE TABLE `Cart` (
|
||||
`cart_id` int(11) unsigned NOT NULL AUTO_INCREMENT,
|
||||
PRIMARY KEY (`cart_id`)
|
||||
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
|
||||
|
||||
CREATE TABLE `Items` (
|
||||
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
|
||||
`cart_id` int(11) unsigned NOT NULL,
|
||||
PRIMARY KEY (`id`),
|
||||
KEY `cart_id` (`cart_id`),
|
||||
CONSTRAINT `items_ibfk_1` FOREIGN KEY (`cart_id`) REFERENCES `Cart` (`cart_id`)
|
||||
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;
|
||||
@@ -1,94 +0,0 @@
|
||||
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.HSQLDialect;
|
||||
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", HSQLDialect.class.getName())
|
||||
.setProperty("hibernate.connection.driver_class", org.hsqldb.jdbcDriver.class.getName())
|
||||
.setProperty("hibernate.connection.url", "jdbc:hsqldb: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();
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user