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

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

 
阅读更多


其实一对多和多对一是一样的,只是看问题的角度不同。


需要的注解标签请参考前面的文章,那些标签是我从前面项目总结下来的


SQL脚本:


-- 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=2 DEFAULT CHARSET=utf-8;
/*!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,'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-08 22:34:53
 


//Category.java

package com.zyp.examples;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

import org.hibernate.annotations.GenericGenerator;

/**
 * Category entity. @author MyEclipse Persistence Tools
 */

@Entity
@Table(name="category")
public class Category implements java.io.Serializable {

	// Fields
	private static final long serialVersionUID = 3763960444574701564L;

	@Id
	@GenericGenerator(name="incrementGenerator", strategy="increment")
	@GeneratedValue(generator="incrementGenerator", strategy=GenerationType.IDENTITY)
	@Column(name="id")
	private Integer id;
	
	@Column(name="name",nullable=false, insertable=true)
	private String name;
	
	@Column(name="description", nullable=false, insertable=true)
	private String description;

	// Constructors

	/** default constructor */
	public Category() {
	}

	/** full constructor */
	public Category(String name, String description) {
		this.name = name;
		this.description = description;
	}

	// Property accessors

	public Integer getId() {
		return this.id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getName() {
		return this.name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getDescription() {
		return this.description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

}
 



//Product.java

package com.zyp.examples;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

import org.hibernate.annotations.GenericGenerator;

/**
 * Product entity. @author MyEclipse Persistence Tools
 */

@Entity
@Table(name="product")
public class Product implements java.io.Serializable {

	// Fields

	private static final long serialVersionUID = -485648626582047874L;

	@Id
	@GenericGenerator(name="incrementGenerator", strategy="increment")
	@GeneratedValue(generator="incrementGenerator", strategy=GenerationType.IDENTITY)
	@Column(name="id")
	private Integer id;
	
	@Column(name="name")
	private String name;
	
	@Column(name="price")
	private Integer price;
	
	@Column(name="description")
	private String description;
	
	@ManyToOne(targetEntity=Category.class, fetch=FetchType.LAZY, cascade={CascadeType.ALL})
	@JoinColumn(name="category_id")
	private Category category;

	// Constructors

	/** default constructor */
	public Product() {
	}

	// Property accessors

	public Integer getId() {
		return this.id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getName() {
		return this.name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Integer getPrice() {
		return this.price;
	}

	public void setPrice(Integer price) {
		this.price = price;
	}

	public String getDescription() {
		return this.description;
	}

	public void setDescription(String description) {
		this.description = description;
	}

	public Category getCategory() {
		return category;
	}

	public void setCategory(Category category) {
		this.category = category;
	}
	
	

}
 



//HibernateUti.java


package com.zyp.examples;

import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
	private static SessionFactory sessionFactory;
	static {
		try {
			sessionFactory = new AnnotationConfiguration().configure()
					.buildSessionFactory();
		} catch (Throwable ex) {
			throw new ExceptionInInitializerError(ex);
		}
	}

	public static SessionFactory getSessionFactory() {
		return sessionFactory;
	}

	public static void shutdown() {
		getSessionFactory().close();
	}
}
 


//Hibernate.cfg.xml

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>

<session-factory>
	<property name="dialect">
		org.hibernate.dialect.MySQLDialect
	</property>
	<property name="connection.url">
		jdbc:mysql://localhost:3306/hibernate_demo
	</property>
	<property name="connection.username">root</property>
	<property name="connection.password">123</property>
	<property name="connection.driver_class">
		com.mysql.jdbc.Driver
	</property>
	<property name="myeclipse.connection.profile">mysql</property>
	<property name="show_sql">true</property>
	<property name="format_sql">true</property>
	
	<mapping class="com.zyp.examples.Category" />
	<mapping class="com.zyp.examples.Product" />

</session-factory>

</hibernate-configuration>
 


经过这个例子,我也发现主键生成方式参数的设定了,呵呵。。

	@Id
	@GenericGenerator(name="incrementGenerator(可以随便取一个名字)", strategy="increment(主键生成策略)")
	@GeneratedValue(generator="incrementGenerator(和上面的保持一致)", strategy=GenerationType.IDENTITY(根据需要从注解中选一个值))
	@Column(name="id")
	private Integer id;
分享到:
评论

相关推荐

    Hibernate Annotation 唯一外键一对一双向关联

    唯一外键是指在一对一关联中,一方的主键同时也作为另一方的外键,确保两个实体共享同一个ID。这可以通过在没有`@JoinColumn`的情况下让两个实体共享相同的主键生成策略来实现。例如,使用`GenerationType.IDENTITY`...

    Hibernate一对一单向外键关联 (联合主键annotation)

    在单向一对一关联中,只有一个实体知道另一个实体的存在,而另一个实体并不知情。这里我们讨论的是单向外键关联,即一方实体持有了另一方的外键。 在Hibernate中,一对一关联可以通过`@OneToOne`注解来实现。这个...

    Hibernate Annotation 基于连接表的单向一对多关联

    本篇文章将详细讲解如何利用Hibernate的注解实现基于连接表的单向一对多关联。 首先,理解一对多关联:在数据库设计中,一对多关联意味着一个实体(表)可以与多个其他实体(表)相对应。例如,一个学生可以有多个...

    Hibernate一对一单向外键关联(annotation/xml)

    // 单向一对一关联 @OneToOne(mappedBy = "person") private IdentityCard identityCard; // getters and setters } @Entity public class IdentityCard { @Id @GeneratedValue(strategy = GenerationType....

    Hibernate多对多单向关联(annotation/xml)

    本篇将详细讲解如何使用Hibernate实现多对多单向关联,包括注解(Annotation)和XML配置方式。 一、多对多关联的基本概念 多对多关联意味着一个实体可以与多个其他实体关联,反之亦然。例如,学生和课程的关系,一...

    Hibernate一对多单向关联(annotation/xml)

    在本教程中,我们将探讨如何使用注解和XML配置实现Hibernate的一对多单向关联。 首先,让我们理解一对多关联的概念。在数据库中,一对多关联意味着在一个表(父表)中的一个记录可以对应另一个表(子表)中的多个...

    Hibernate多对一单向关联(annotation/xml)

    在Java的持久化框架Hibernate中,多对一的单向关联是一种常见的关系映射方式,它主要用于处理数据库中两个实体间的一种关联关系。在这种关系中,一个实体(多个实例)可以与另一个实体(单个实例)相关联。本文将...

    Hibernate_Annotation关联映射

    以上是一对一关联的三种形式,下面介绍多对一关联。 多对一(Many-to-One) 使用@ManyToOne批注来实现多对一关联。 @ManyToOne批注有一个名为targetEntity的参数,该参数定义了目标实体名,通常不需要定义该参数...

    详解Hibernate一对一映射配置

    这里,Person和Address类共享同一主键`PERSON_ID`,表明它们一对一关联。 2. **单方外键关联(Unidirectional Foreign Key Join)** 在单方外键关联中,一个实体通过外键字段引用另一个实体。配置如下: ```xml ...

    Hibernate ORMapping Annotation XML PDF

    根据给定文件的信息,本文将详细介绍...以上内容仅覆盖了一对一的几种常见关联方式及其配置方法,接下来还可以进一步探讨其他类型的关系映射,包括一对多、多对多等,以及这些关系在Hibernate中的具体实现方式。

    Hibernate一对多映射配置详解

    -- 多对一关联 --&gt; ``` 在`&lt;many-to-one&gt;`标签中,`name`属性指定了关联的属性名,`column`属性指定了数据库表中的外键列名,`class`属性指定了关联的实体类全限定名。 ##### 2. 双向关联 双向关联则指两个实体...

    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_学习笔记.

    - **一对一关联映射** - **唯一外键关联-单向**:一个对象有一个唯一的外键指向另一个对象。 - **唯一外键关联-双向**:两个对象互相引用对方。 - **主键关联-单向**:一个对象的主键作为另一个对象的外键。 - *...

    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 ...

Global site tag (gtag.js) - Google Analytics