`
paladin1988
  • 浏览: 320420 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

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

阅读更多

一对多,一个分类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",我们可以把多样性从多对多改变为一对多。

分享到:
评论

相关推荐

    Hibernate关联映射

    Hibernate 多对多单向关联 Hibernate 一对一外键双向关联 Hibernate 一对一主键双向关联 Hibernate 一对一连接表双向关联 Hibernate 一对多外键双向关联 Hibernate 一对多连接表双向关联 Hibernate 多对多双向关联

    Hibernate 一对多外键单向关联

    Hibernate 一对多 外键 单向关联,有例子。

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

    NULL 博文链接:https://paladin1988.iteye.com/blog/1633417

    Hibernate关联关系映射目录

    Hibernate关联关系映射...│ └─ 多对多单向关联 └─双向关联 ├─ 一对一外键双向关联 ├─ 一对一主键双向关联 ├─ 一对一连接表双向关联 ├─ 一对多外键双向关联 ├─ 一对多连接表双向关联 └─ 多对多双向关联

    hibernate学习笔记

    hibernate一对多双向自连接关联映射 15 hibernate多对多关联映射(单向User----&gt;Role) 19 hibernate多对多关联映射(双向User&lt;----&gt;Role) 20 Hibernate的继承关系 21 每棵继承树映射成一张表(hibernate_extends_1) 22 ...

    Hibernate学习笔记

    014 一对多关联映射 单向 015 一对多关联映射 双向 016 多对多关联映射 单向 017 多对多关联映射 双向 018 关联映射文件中标签中的 lazy(懒加载)属性 019 关联映射文件中集合标签中的 lazy(懒加载)属性 020 、单端...

    JSP开发之hibernate之单向多对一关联的实例

    一对多的基础上来测试单向多对一的关联 hibernate多对一的关联关系定义: 和单向一对多不同的是:一对多是在意的一方的一方定义set集合,在映射文件中 :单向多对一,简单很多在多的一方定义一的一方类的...

    Hibernate_Annotation关联映射

    通过在被拥有的实体端(owned entity)增加一个外键列来实现一对多单向关联是很少见的,也是不推荐的,建议通过一个联接表来实现这种关联(下面会讲到)。 @JoinColoumn批注来描述这种单向关联关系 @Entity Public class...

    Hibernate_实体关联关系映射--学习总结

    Hibernate 实体关联关系映射 学习总结 把一对一 一对多 单向 双向 主键 外键 链接表等讲的比较清楚

    Hibernate注释大全收藏

    这种策略支持双向的一对多关联,但不支持 IDENTIFY 生成器策略,因为ID必须在多个表间共享。一旦使用就不能使用AUTO和IDENTIFY生成器。 每个类层次结构一张表 @Entity @Inheritance(strategy=InheritanceType....

    Hibernate+中文文档

    7.4.1. 一对多(one to many) / 多对一(many to one) 7.4.2. 一对一(one to one) 7.5. 使用连接表的双向关联(Bidirectional associations with join tables) 7.5.1. 一对多(one to many) /多对一( many ...

    hibernate3.2中文文档(chm格式)

    7.5.1. 一对多(one to many) /多对一( many to one) 7.5.2. 一对一(one to one) 7.5.3. 多对多(many to many) 7.6. 更复杂的关联映射 8. 组件(Component)映射 8.1. 依赖对象(Dependent objects) ...

    HibernateAPI中文版.chm

    7.5.1. 一对多(one to many) /多对一( many to one) 7.5.2. 一对一(one to one) 7.5.3. 多对多(many to many) 7.6. 更复杂的关联映射 8. 组件(Component)映射 8.1. 依赖对象(Dependent objects) ...

    Hibernate中文详细学习文档

    7.4.1. 一对多(one to many) / 多对一(many to one) 7.4.2. 一对一(one to one) 7.5. 使用连接表的双向关联(Bidirectional associations with join tables) 7.5.1. 一对多(one to many) /多对一( many ...

    Hibernate 中文 html 帮助文档

    7.5.1. 一对多(one to many) /多对一( many to one) 7.5.2. 一对一(one to one) 7.5.3. 多对多(many to many) 7.6. 更复杂的关联映射 8. 组件(Component)映射 8.1. 依赖对象(Dependent objects) 8.2. 在...

    Hibernate教程

    8.4.1. 一对多(one to many) / 多对一(many to one) 8.4.2. 一对一(one to one) 8.5. 使用连接表的双向关联(Bidirectional associations with join tables) 8.5.1. 一对多(one to many) /多对一( many ...

    最全Hibernate 参考文档

    7.4.1. 一对多(one to many) / 多对一(many to one) 7.4.2. 一对一(one to one) 7.5. 使用连接表的双向关联(Bidirectional associations with join tables) 7.5.1. 一对多(one to many) /多对一( many to ...

    精通 Hibernate:Java 对象持久化技术详解(第2版).part2

     15.3.4 把多对多关联分解为两个一对多关联  15.4 小结  15.5 思考题 第16章 Hibernate的检索策略  16.1 Hibernate的检索策略简介  16.2 类级别的检索策略  16.2.1 立即检索  16.2.2 延迟检索  16.3 一对多...

    hibernate 体系结构与配置 参考文档(html)

    一对多(one to many) /多对一( many to one) 7.5.2. 一对一(one to one) 7.5.3. 多对多(many to many) 7.6. 更复杂的关联映射 8. 组件(Component)映射 8.1. 依赖对象(Dependent objects) 8.2. 在...

Global site tag (gtag.js) - Google Analytics