Hibernate one to many mapping example using set
In this tutorial we are going to understand how to use XML to map a one-to-many association between Java objects and database tables using Hibernate framework. We will create a sample Hibernate-based application to manage the following entity relationship:
- Creating sample database and tables
- Required Jars for project
- Coding Hibernate Model Classes
- Creating Hibernate Mapping Files
- Writing Hibernate Configuration File
- Coding a Test Program
- Creating sample database and tables
Execute the following script in MySQL Workbench’s SQL Editor to create a database
called cartdb with two tables named cart and items:
create database cartdb;
use cartdb;
CREATE TABLE `cart` (
`cart_id` int(11) NOT NULL AUTO_INCREMENT,
`total` int(11) NOT NULL,
`name` varchar(45) NOT NULL,
PRIMARY KEY (`cart_id`)
);
CREATE TABLE `items` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`cart_id` int(11) NOT NULL,
`item_id` int(11) NOT NULL,
`item_total` int(11) NOT NULL,
`quantity` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `fk_cart` (`cart_id`),
CONSTRAINT `fk_cart` FOREIGN KEY (`cart_id`) REFERENCES `cart` (`cart_id`)
);
2. Required Jars for project
hibernate-core-4.2.2.Final.jar
hibernate-commons-annotations-4.0.2.Final.jar
jboss-transaction-api_1.1_spec-1.0.1.Final.jar
hibernate-jpa-2.0-api-1.0.1.Final.jar
jboss-logging-3.1.0.GA.jar
antlr-2.7.7.jar
dom4j-1.6.1.jar
javassist-3.15.0-GA.jar
3. Coding hibernate model classes
Create two JavaBean-style classes Cart.java and Items.java to model the two tables cart and items, respectively.
File net\engineeernitesh\hibernate\Cart.java:
package net.engineeernitesh.hibernate;
import java.util.Set;
public class Cart {
private long id;
private long total;
private String name;
private Set<Items> items;
public Category() {
}
public Category(Long total,String name) {
this.total = total;
this.name = name;
}
// getters and setters...
}
File net\engineeernitesh\hibernate\Items.java:
package net.engineeernitesh.hibernate;
public class Items {
private long id;
private Cart cart;
private long item_id;
private long item_total;
private long quantity;
public Items() {
}
public Items(Cart cart,Long item_id,Long item_total,Long quantity) {
this.cart = cart;
this.item_id = item_id;
this.item_total = item_total;
this.quantity = quantity;
}
// getters and setters...
}
4. Creating hibernate mapping files
Create two XML files Cart.hbm.xml and Items.hbm.xml to tell Hibernate how to map the JavaBean classes above with the database tables.
File net\engineeernitesh\hibernate\Cart.hbm.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="net.engineeernitesh.hibernate">
<class name="Cart" table="CART">
<id name="id" column="CART_ID">
<generator class="native"/>
</id>
<property name="total" column="TOTAL" />
<property name="name" column="NAME" />
<set name="items" inverse="true" cascade="all">
<key column="CART_ID" not-null="true" />
<one-to-many class="Items"/>
</set>
</class>
</hibernate-mapping>
File net\engineeernitesh\hibernate\Items.hbm.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="net.engineeernitesh.hibernate">
<class name="Items" table="ITEMS">
<id name="id" column="ID">
<generator class="native"/>
</id>
<many-to-one name="cart" class="Cart"
column="CART_ID" not-null="true"/>
<property name="item_id" column="ITEM_ID" />
<property name="item_total" column="ITEM_TOTAL" />
<property name="quantity" column="QUANTITY" />
</class>
</hibernate-mapping>
5. Writing Hibernate Configuration File
Create the Hibernate configuration file (hibernate.cfg.xml) to specify database type, connection details and the mapping files:
<?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>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/cartdb</property>
<property name="connection.username">root</property>
<property name="connection.password">secret</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<mapping resource="net/codejava/hibernate/Cart.hbm.xml"/>
<mapping resource="net/codejava/hibernate/Items.hbm.xml"/>
</session-factory>
</hibernate-configuration>
6. Coding a Test Program
Following is code of the test program that persists some sample data:
package net.engineeernitesh.hibernate;
import java.util.HashSet;
import java.util.Set;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
/**
*
* This program demonstrates using Hibernate framework to manage a
* bidirectional one-to-many association.
* @author www.engineeernitesh.blogspot
*
*/
public class CartManager {
public static void main(String[] args) {
// loads configuration and mappings
Configuration configuration = new Configuration().configure();
ServiceRegistryBuilder registry = new ServiceRegistryBuilder();
registry.applySettings(configuration.getProperties());
ServiceRegistry serviceRegistry = registry.buildServiceRegistry();
// builds a session factory from the service registry
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
// obtains the session
Session session = sessionFactory.openSession();
session.beginTransaction();
Cart cart = new Cart(2,"Shopping");
Items bag = new Items(cart,1,2,5);
Items book = new Items(cart,2,4,5);
Set<Items> items = new HashSet<Items>();
items.add(bag);
items.add(book);
cart.setItems(items);
session.save(cart);
session.getTransaction().commit();
session.close();
}
}
Related Topics:
Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.
ReplyDeleteHibernate Training in Electronic City
https://bayanlarsitesi.com/
ReplyDeleteGüneşli
Halkalı
Florya
Akbatı
1R0
Denizli
ReplyDeleteErzurum
Samsun
Malatya
Niğde
TAT6XB
https://titandijital.com.tr/
ReplyDeletekütahya parça eşya taşıma
siirt parça eşya taşıma
tekirdağ parça eşya taşıma
adana parça eşya taşıma
51NELB
sakarya evden eve nakliyat
ReplyDeleteosmaniye evden eve nakliyat
aksaray evden eve nakliyat
çanakkale evden eve nakliyat
zonguldak evden eve nakliyat
0872Q
https://istanbulolala.biz/
ReplyDeleteX2YHİ
3B016
ReplyDeleteMersin Evden Eve Nakliyat
Malatya Evden Eve Nakliyat
Sakarya Evden Eve Nakliyat
Hakkari Evden Eve Nakliyat
Eskişehir Evden Eve Nakliyat
A4255
ReplyDeleteKocaeli Evden Eve Nakliyat
Adana Lojistik
Hakkari Evden Eve Nakliyat
İstanbul Parça Eşya Taşıma
Iğdır Evden Eve Nakliyat
FF1DB
ReplyDeletebuy deca durabolin
order steroids
buy steroid cycles
peptides for sale
testosterone propionat for sale
oxandrolone anavar for sale
buy oxandrolone anavar
order sustanon
buy trenbolone enanthate
A9EF1
ReplyDeleteTokat En İyi Rastgele Görüntülü Sohbet
yalova görüntülü sohbet siteleri
Sivas Rastgele Görüntülü Sohbet Ücretsiz
kütahya canli sohbet chat
canlı sohbet siteleri
sohbet muhabbet
çanakkale telefonda kadınlarla sohbet
Kayseri Parasız Görüntülü Sohbet Uygulamaları
nevşehir ücretsiz sohbet sitesi
02C67
ReplyDeletemuş seslı sohbet sıtelerı
sesli sohbet sitesi
konya kadınlarla rastgele sohbet
kars canlı sohbet et
Balıkesir Kadınlarla Rastgele Sohbet
gümüşhane sesli mobil sohbet
aydın random görüntülü sohbet
sohbet odaları
Çanakkale Bedava Sohbet
E9B6C
ReplyDeleteBitcoin Nasıl Alınır
Snapchat Takipçi Satın Al
Twitch Takipçi Satın Al
Keep Coin Hangi Borsada
Instagram Takipçi Hilesi
Apenft Coin Hangi Borsada
Tumblr Beğeni Hilesi
Görüntülü Sohbet
Parasız Görüntülü Sohbet
73112
ReplyDeleteyearn
uniswap
quickswap
bitbox
uwu lend
shiba
layerzero
avax
sushi
شركة مكافحة الفئران بالاحساء yKPaYXLw3d
ReplyDelete