Hibernate Annotation 基于外键的单向多对一联系关系
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;