Hibernate List mapping annotation example
Ngày đăng:
12/01/2022
Trả lời:
0
Lượt xem:
57
CodeJava Coding Your Passion
Hibernate One-to-Many Association Annotations ExampleDetailsWritten by Nam Ha MinhLast Updated on 15 May 2020 | Print Email
1. Creating Database and TablesExecute the following MySQL script to create a database stockdb and two tables category and product:create database stockdb; use stockdb; CREATE TABLE `category` ( `category_id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(45) NOT NULL, PRIMARY KEY (`category_id`) ); CREATE TABLE `product` ( `product_id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(45) NOT NULL, `description` varchar(512) NOT NULL, `price` float NOT NULL, `category_id` int(11) NOT NULL, PRIMARY KEY (`product_id`), KEY `fk_category` (`category_id`), CONSTRAINT `fk_category` FOREIGN KEY (`category_id`) REFERENCES `category` (`category_id`) );2. Creating Maven-Eclipse ProjectIn Eclipse IDE, create a Maven project named HibernateOne2ManyAnnotationsExample with the following structure:
3. Annotating Model Classes for One-to-Many AssociationCreate two model classes called Category.java and Product.java with the following source code:File net\codejava\hibernate\Category.java:package net.codejava.hibernate; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.OneToMany; import javax.persistence.Table; @Entity @Table(name = "CATEGORY") public class Category { private long id; private String name; private Set
4. Writing Hibernate Configuration FileConfigure database connection settings and mapping classes in the hibernate.cfg.xml file as follows:5. Writing a Test ProgramSo far we have finished the configuration part. Now, lets write a test program (StockManager.java) with the following source code:package net.codejava.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 JPA annotations in Hibernate * in order to implement a one-to-many association mapping. * @author www.codejava.net * */ public class StockManager { 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(); Category category = new Category("Computer"); Product pc = new Product("DELL PC", "Quad-core PC", 1200, category); Product laptop = new Product("MacBook", "Apple High-end laptop", 2100, category); Product phone = new Product("iPhone 5", "Apple Best-selling smartphone", 499, category); Product tablet = new Product("iPad 3", "Apple Best-selling tablet", 1099, category); SetRelated Hibernate One-to-Many Tutorials:
Other Hibernate Tutorials:
About the Author:Attachments:
Add comment
Show
Notify me of follow-up comments Send Cancel Comments123 #11Alejandro Barrero2018-08-29 09:11 StockManager doesn't work; i am getting QuoteException in thread "main" org.hibernate.HibernateException: /hibernate.cfg.xml Actually you didn't specify where to put it. #10amitabh2018-06-14 09:18 Cont.... QuoteCategory table: Category_id Category_Name 1 Foods 2 Foods Product table: product_id category_id product_name 101 1 vegitable 102 2 Processed foods So now how to map so that if category_name is Food it do not insert another row as food again and i can have multiple products under one category? #9amitabh2018-06-14 09:12 One question here , There is one scenario where i used ur example, so for the first time i insert category_name as Foods (Category_id = 1) with product as vegitables. so it will insert first in category and then persist vegitable into product along with category id. QuoteNow, i want add one more product (Processed foods) under same category (Food) but in this case it created one more category_id =2 it do not refer the exiting category and insert in product table as #8Jervy2017-06-24 09:09 Im having problem with ServiceRegistryBuilder class. it seems that I need another libraries. what should I do? Quote#7Amin2017-04-09 01:49 How to get user input with your project where details form take more then 5 Products. Can you Help Me Sir. QuoteAmin 123 Refresh comments list |