纠结了好久呀,因为没有set,关联关系没有保存对,导致插入数据的时候老是空的,我还以为注解用过了呢。
//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=5 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,'fruit2','fruit category2'),(2,'fruit2','fruit category2'),(3,'fruit2','fruit category2');
/*!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 AUTO_INCREMENT,
`name` varchar(30) NOT NULL,
`price` int(11) NOT NULL,
`description` varchar(30) NOT NULL,
`category_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `category_id` (`category_id`)
) ENGINE=MyISAM AUTO_INCREMENT=9 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,'orige2',20,'orige2',1),(2,'apple2',10,'apple2',1),(3,'orige2',20,'orige2',2),(4,'apple2',10,'apple2',2),(5,'orige2',20,'orige2',3),(6,'apple2',10,'apple2',3);
/*!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-22 23:27:56
//Category.java
@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)
private String name;
@Column(name="description", nullable=false)
private String description;
@OneToMany(targetEntity=Product.class, cascade=CascadeType.ALL, mappedBy="category")
@JoinColumn(name="category_id")//可有可无,告诉一端category_id是外键
private Set<Product> products = new HashSet<Product>();
//Product.java
@Entity
@Table(name="product")
public class Product implements java.io.Serializable {
// Fields
private static final long serialVersionUID = -7292036796553578847L;
@Id
@GenericGenerator(name="incrementGenerator", strategy="increment")
@GeneratedValue(generator="incrementGenerator", strategy=GenerationType.IDENTITY)
@Column(name="id")
private Integer id;
@Column(name="name", nullable=false)
private String name;
@Column(name="price", nullable=false)
private Integer price;
@Column(name="description",nullable=false)
private String description;
@ManyToOne(targetEntity=Category.class, cascade=CascadeType.ALL)
//指出category_id是外键,参考其他表的主键列id
@JoinColumn(name="category_id", referencedColumnName="id",nullable=false)
private Category category;
//HibernateTest.java
package com.zyp.examples;
import java.util.HashSet;
import java.util.Set;
import org.hibernate.Session;
import org.hibernate.Transaction;
public class HibernateTest {
public static void main(String[] args) {
//同时保存分类和产品
addAll();
// deleteByCategory();
}
public static void deleteByCategory()
{
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
Category cat = (Category) session.load(Category.class, new Integer(3));
session.delete(cat);
tx.commit();
session.close();
HibernateUtil.shutdown();
}
public static void addAll()
{
Category category = new Category();
category.setDescription("fruit category2");
category.setName("fruit2");
Product product = new Product();
product.setDescription("apple2");
product.setName("apple2");
product.setPrice(10);
product.setCategory(category);
Product product1 = new Product();
product1.setDescription("orige2");
product1.setName("orige2");
product1.setPrice(20);
//之前忘记加的关联
product1.setCategory(category);
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(product1);
// session.save(product);
//启用级联操作
// session.save(product);
// session.save(product1);
tx.commit();
session.close();
HibernateUtil.shutdown();
}
public static void addCategory()
{
Category category = new Category();
category.setName("fruit");
category.setDescription("fruit category");
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
session.save(category);
tx.commit();
HibernateUtil.shutdown();
}
public static void addProduct()
{
Product product = new Product();
product.setDescription("banana");
product.setName("banana");
product.setPrice(10);
Product product1 = new Product();
product1.setDescription("tom");
product1.setName("tom");
product1.setPrice(20);
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
Category category = (Category)session.load(Category.class, new Integer(1));
Set<Product> products = new HashSet<Product>();
products.add(product);
products.add(product1);
category.setProducts(products);
session.save(category);
//启用级联操作
// session.save(product);
// session.save(product1);
tx.commit();
session.close();
HibernateUtil.shutdown();
}
}
之前在保存数据的时候没有在product中保存category,导致外键列总是空的。反复弄之后才发现。。晕。
基于外键关联的一对多
在多对一双向关联关系中,几乎总是双向关联中的多端作为主体(owner)端, 而一的这段关联注解为@OneToMany( mappedBy=... )
此时保存数据只需要3条sql(两条max(id)除外),1条插入cateogry, 2条插入product.
也就是说,在一对多关系中,最好有多端来维护关联关系,这样可以减少两条update语句。
我们需要在从表(即多段配置@joinColumn,标志外键关系,而不是在多端配置)
而如果我们把关联关系交给1端来维护,即Category来维护,则我们需要多出两条update语句。
此时,我们的实体类应该这样配置。
对于一对多的双向映射,如果要一对多这一端维护关联关系, 你需要删除mappedBy元素并将多对一这端的 @JoinColumn的insertable和updatable设置为false. 很明显,这种方案不会得到什么明显的优化,而且还会增加一些附加的UPDATE语句.
@Entity
public class Troop {
@OneToMany
@JoinColumn(name="troop_fk") //we need to duplicate the physical information
public Set<Soldier> getSoldiers() {
...
}
@Entity
public class Soldier {
@ManyToOne
@JoinColumn(name="troop_fk", insertable=false, updatable=false)
public Troop getTroop() {
...
}