欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Hibernate基于外键的一对多单向关联

程序员文章站 2022-05-23 21:06:06
...

一对多,一个分类Category下有多个Product,从Cateogry角度去保存数据。

 

创建数据库脚本如下:(参看附件)

 

-- MySQL dump 10.13  Distrib 5.1.55, for Win32 (ia32)
--
-- Host: localhost    Database: hibernate_demo
-- ------------------------------------------------------
-- Server version	5.1.55-community

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;

--
-- Table structure for table `category`
--

DROP TABLE IF EXISTS `category`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `category` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(30) NOT NULL,
  `description` varchar(30) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `category`
--

LOCK TABLES `category` WRITE;
/*!40000 ALTER TABLE `category` DISABLE KEYS */;
INSERT INTO `category` VALUES (1,'fruit','fruit category');
/*!40000 ALTER TABLE `category` ENABLE KEYS */;
UNLOCK TABLES;

--
-- Table structure for table `product`
--

DROP TABLE IF EXISTS `product`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `product` (
  `id` int(11) NOT NULL,
  `name` varchar(30) NOT NULL,
  `price` int(11) NOT NULL,
  `description` varchar(30) NOT NULL,
  `category_id` int(11) NOT NULL,
  PRIMARY KEY (`id`),
  KEY `product_fk` (`category_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
/*!40101 SET character_set_client = @saved_cs_client */;

--
-- Dumping data for table `product`
--

LOCK TABLES `product` WRITE;
/*!40000 ALTER TABLE `product` DISABLE KEYS */;
INSERT INTO `product` VALUES (1,'orige',20,'orige',1),(2,'apple',10,'apple',1);
/*!40000 ALTER TABLE `product` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;

/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

-- Dump completed on 2012-08-09 21:40:19
 

 

 

这是一个非常不错的例子,呵呵,至少整个过程大家可以很清楚的明白。。


//Category.java

public class Category implements java.io.Serializable {

	// Fields

	private Integer id;
	private String name;
	private String description;
	private Set<Product> products = new HashSet<Product>();
 

 

//Product.java

public class Product implements java.io.Serializable {

	// Fields

	private Integer id;
	private String name;
	private Integer price;
	private String description;
 


//Category.hbm.xml

 

        <!-- 基于外键的单向一对多关联 -->
        <!-- 单向一对多在一端进行配置 -->
        <!-- set的name代表一端的set属性,table指向多端的关联表-->
        <!-- key的column属性代表外键 -->
        <!-- cascade="save-update" ,使用保存数据的级联操作-->
        <set name="products" table="product" cascade="save-update">
        <key column="category_id"  not-null="true" />
        <one-to-many class="com.v512.examples.Product"/>
        </set>
 

 

 

//HibernateTest.java

//保存数据

	public static void addProduct()
	{
		Product product = new Product();
		product.setDescription("apple");
		product.setName("apple");
		product.setPrice(10);
		
		
		Product product1 = new Product();
		product1.setDescription("orige");
		product1.setName("orige");
		product1.setPrice(20);
		
		Category category = new Category();
		category.setDescription("fruit category");
		category.setName("fruit");
		
		
		Set<Product> products = new HashSet<Product>();
		products.add(product);
		products.add(product1);
		
		category.setProducts(products);
		
		Session session = HibernateUtil.getSessionFactory().openSession();
		Transaction tx = session.beginTransaction();
		session.save(category);
		//启用级联操作
//		session.save(product);
//		session.save(product1);
		tx.commit();
		session.close();
		HibernateUtil.shutdown();
		
	}

 

 

输入信息如下:

 

21:15:48,906 DEBUG JDBCTransaction:87 - current autocommit status: false
21:15:48,906 DEBUG IncrementGenerator:104 - fetching initial value: select max(id) from category
21:15:48,906 DEBUG AbstractBatcher:410 - about to open PreparedStatement (open PreparedStatements: 0, globally: 0)
21:15:48,937 DEBUG SQL:111 - 
    select
        max(id) 
    from
        category
Hibernate: 
    select
        max(id) 
    from
        category
21:15:48,953 DEBUG IncrementGenerator:119 - first free id: 1
21:15:48,953 DEBUG AbstractBatcher:418 - about to close PreparedStatement (open PreparedStatements: 1, globally: 1)
21:15:48,953 DEBUG AbstractSaveEventListener:135 - generated identifier: 1, using strategy: org.hibernate.id.IncrementGenerator
21:15:48,968 DEBUG IncrementGenerator:104 - fetching initial value: select max(id) from product
21:15:48,968 DEBUG AbstractBatcher:410 - about to open PreparedStatement (open PreparedStatements: 0, globally: 0)
21:15:48,968 DEBUG SQL:111 - 
    select
        max(id) 
    from
        product
Hibernate: 
    select
        max(id) 
    from
        product
21:15:48,968 DEBUG IncrementGenerator:119 - first free id: 1
21:15:48,968 DEBUG AbstractBatcher:418 - about to close PreparedStatement (open PreparedStatements: 1, globally: 1)
21:15:48,968 DEBUG AbstractSaveEventListener:135 - generated identifier: 1, using strategy: org.hibernate.id.IncrementGenerator
21:15:48,968 DEBUG AbstractSaveEventListener:135 - generated identifier: 2, using strategy: org.hibernate.id.IncrementGenerator
21:15:48,968 DEBUG JDBCTransaction:134 - commit
21:15:48,968 DEBUG AbstractFlushingEventListener:134 - processing flush-time cascades
21:15:48,968 DEBUG AbstractFlushingEventListener:177 - dirty checking collections
21:15:48,968 DEBUG Collections:199 - Collection found: [com.v512.examples.Category.products#1], was: [<unreferenced>] (initialized)
21:15:48,984 DEBUG AbstractFlushingEventListener:108 - Flushed: 3 insertions, 0 updates, 0 deletions to 3 objects
21:15:48,984 DEBUG AbstractFlushingEventListener:114 - Flushed: 1 (re)creations, 0 updates, 0 removals to 1 collections
21:15:48,984 DEBUG Printer:106 - listing entities:
21:15:48,984 DEBUG Printer:113 - com.v512.examples.Product{id=1, price=10, description=apple, name=apple}
21:15:48,984 DEBUG Printer:113 - com.v512.examples.Category{id=1, description=fruit category, name=fruit, products=[com.v512.examples.Product#2, com.v512.examples.Product#1]}
21:15:48,984 DEBUG Printer:113 - com.v512.examples.Product{id=2, price=20, description=orige, name=orige}
21:15:48,984 DEBUG AbstractBatcher:410 - about to open PreparedStatement (open PreparedStatements: 0, globally: 0)
21:15:48,984 DEBUG SQL:111 - 
    insert 
    into
        hibernate_demo.category
        (name, description, id) 
    values
        (?, ?, ?)
Hibernate: 
    insert 
    into
        hibernate_demo.category
        (name, description, id) 
    values
        (?, ?, ?)
21:15:48,984 DEBUG AbstractBatcher:66 - Executing batch size: 1
21:15:48,984 DEBUG AbstractBatcher:418 - about to close PreparedStatement (open PreparedStatements: 1, globally: 1)
21:15:48,984 DEBUG AbstractBatcher:410 - about to open PreparedStatement (open PreparedStatements: 0, globally: 0)
21:15:48,984 DEBUG SQL:111 - 
    insert 
    into
        hibernate_demo.product
        (name, price, description, category_id, id) 
    values
        (?, ?, ?, ?, ?)
Hibernate: 
    insert 
    into
        hibernate_demo.product
        (name, price, description, category_id, id) 
    values
        (?, ?, ?, ?, ?)
21:15:48,984 DEBUG AbstractBatcher:248 - reusing prepared statement
21:15:48,984 DEBUG SQL:111 - 
    insert 
    into
        hibernate_demo.product
        (name, price, description, category_id, id) 
    values
        (?, ?, ?, ?, ?)
Hibernate: 
    insert 
    into
        hibernate_demo.product
        (name, price, description, category_id, id) 
    values
        (?, ?, ?, ?, ?)
21:15:48,984 DEBUG AbstractBatcher:66 - Executing batch size: 2
21:15:48,984 DEBUG AbstractBatcher:418 - about to close PreparedStatement (open PreparedStatements: 1, globally: 1)
21:15:48,984 DEBUG AbstractCollectionPersister:1112 - Inserting collection: [com.v512.examples.Category.products#1]
21:15:48,984 DEBUG AbstractBatcher:410 - about to open PreparedStatement (open PreparedStatements: 0, globally: 0)
21:15:48,984 DEBUG SQL:111 - 
    update
        hibernate_demo.product 
    set
        category_id=? 
    where
        id=?
Hibernate: 
    update
        hibernate_demo.product 
    set
        category_id=? 
    where
        id=?
21:15:48,984 DEBUG AbstractBatcher:248 - reusing prepared statement
21:15:48,984 DEBUG SQL:111 - 
    update
        hibernate_demo.product 
    set
        category_id=? 
    where
        id=?
Hibernate: 
    update
        hibernate_demo.product 
    set
        category_id=? 
    where
        id=?
21:15:48,984 DEBUG AbstractCollectionPersister:1194 - done inserting collection: 2 rows inserted
21:15:48,984 DEBUG AbstractBatcher:66 - Executing batch size: 2
21:15:48,984 DEBUG AbstractBatcher:418 - about to close PreparedStatement (open PreparedStatements: 1, globally: 1)
21:15:48,984 DEBUG JDBCTransaction:147 - committed JDBC Connection
21:15:48,984 DEBUG ConnectionManager:427 - aggressively releasing JDBC connection
21:15:48,984 DEBUG ConnectionManager:464 - releasing JDBC connection [ (open PreparedStatements: 0, globally: 0) (open ResultSets: 0, globally: 0)]
21:15:49,000  INFO SessionFactoryImpl:853 - closing
21:15:49,000  INFO DriverManagerConnectionProvider:170 - cleaning up connection pool: jdbc:mysql://localhost:3306/hibernate_demo
 

 

如果我们不使用级联操作,即cascade=“save-update”,则需要先保存category,然后再保存product。

那么保存数据就是这样

 

		session.save(category);
		//启用级联操作
		session.save(product);
		session.save(product1);
		tx.commit();

 

而启用级联,则只需要保存category就行。

 

cascade取值如下:


all : 所有情况下均进行关联操作。
none:所有情况下均不进行关联操作。(默认值)
save-update:在执行save/update/saveOrUpdate时进行关联操作。
delete:在执行delete时进行关联操作。

 


请注意看一下sql,以Hibernate:开头的才是hibernate执行的sql,其他的代表发送给hibernate执行的sql语句。刚开始看错了,还以为hibernate执行了多条sql。

 

 

这种方法Hibernate reference称之为
基于外键关联的单向一对多关联是一种很少见的情况,并不推荐使用。


推荐使用:
基于连接表的单向一对多关联 应该优先被采用。请注意,通过指定unique="true",我们可以把多样性从多对多改变为一对多。