上一节已经简单的讲了怎么样使用hibernate的annotation,这节就来说一下多对一映射(单向/多向)
先说单向多对一
新建一个java项目,结构如下:
jar和hibernate官网获取方法,以及hibernate.cfg.xml配置,参见《Hibernate环境搭建和配置》
实体类Book代码:
package com.ghibernate.pojo;
import java.util.Date;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
/**
* entiry表示需要持久化的实体类
* Table表示实体类所对应的表
*/
@Entity
@Table(name="t_book")
public class Book {
//Id主键
@Id
//指定主键生成策略
@GeneratedValue(strategy=GenerationType.AUTO)
private int id ;
@Column(name="book_name")
private String name ;
@Column
private double price ;
private String author ;
private Date pubDate ;
//manyToOne表示映射关系
@ManyToOne(cascade=CascadeType.ALL)
//JoinColumn指明外键
@JoinColumn(name="categry_id")
private Category category ;
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public Date getPubDate() {
return pubDate;
}
public void setPubDate(Date pubDate) {
this.pubDate = pubDate;
}
}
实体类Category代码:
package com.ghibernate.pojo;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table
public class Category {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id ;
private String name ;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
hibernate.cfg.xml代码:
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- 配置数据库连接信息 -->
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="connection.url">jdbc:mysql:///hibernate4</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<!-- 数据库方言 -->
<property name="hibernate.dialect">
org.hibernate.dialect.MySQL5Dialect
</property>
<!-- 是否打印sql语句 -->
<property name="show_sql">true</property>
<!-- 格式化sql语句 -->
<property name="format_sql">true</property>
<!-- 数据库更新方式:
1、create:每次更新都先把原有数据库表删除,然后创建该表;
2、create-drop:使用create-drop时,在显示关闭SessionFacroty时(sessionFactory.close()),将drop掉数据库Schema(表)
3、validate:检测;
4、update(常用):如果表不存在则创建,如果存在就不创建
-->
<property name="hbm2ddl.auto">update</property>
<!-- hbm映射文件 -->
<mapping class="com.ghibernate.pojo.Book" />
<mapping class="com.ghibernate.pojo.Category" />
</session-factory>
</hibernate-configuration>
HIbernateUtil代码:
package com.robert.util;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
/**
* hibernate工具类
*/
public class HibernateUtil {
private static Configuration cfg = null;
private static SessionFactory factory = null;
private static Session session = null ;
static {
init();
}
/**
* 初始化获得Configuration和SessionFacroty对象
*/
public static void init() {
cfg = new Configuration().configure();
factory = cfg.buildSessionFactory(new StandardServiceRegistryBuilder()
.applySettings(cfg.getProperties()).build());
}
/**
* 获得Session对象
* @return
*/
public static Session getSession() {
if (factory != null){
return session = factory.openSession();
}
init();
return session = factory.openSession();
}
/**
* 关闭Session
*/
public static void closeSession() {
if(session!=null && session.isOpen())
session.close();
}
}
测试类HibernateTest代码:
package com.ghibernate.test;
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.junit.Test;
import com.ghibernate.pojo.Book;
import com.ghibernate.pojo.Category;
import com.robert.util.HibernateUtil;
public class HibernateTest {
@Test
public void testCreateDB() {
Configuration cfg = new Configuration().configure();
SchemaExport se = new SchemaExport(cfg);
// 第一个参数:是否生成ddl脚本
// 第二个参数:是否执行到数据库中
se.create(true, true);
}
@Test
public void testSave() {
Session session = HibernateUtil.getSession() ;
Transaction tx = session.beginTransaction() ;
Category category = new Category() ;
category.setName("文学类") ;
Book book = new Book() ;
book.setName("读者") ;
book.setPrice(5.6) ;
book.setAuthor("众人") ;
book.setPubDate(new Date()) ;
book.setCategory(category) ;
session.save(book) ;
tx.commit() ;
HibernateUtil.closeSession();
}
@Test
public void testGet() {
Session session = HibernateUtil.getSession() ;
Transaction tx = session.beginTransaction() ;
Book book = (Book) session.get(Book.class, 1) ;
System.out.println("book_name="+book.getName() +"-----category="+book.getCategory().getName());
tx.commit() ;
HibernateUtil.closeSession();
}
}
运行testCreateDB重新生成代码
运行testSave保存数据
运行testGet获取数据
===============================================================================
双向多对一
双向多对一和单向多对一代码的区别就是在上面的代码的一端Category类中增加多端Book的关联,其他的不变,
Category代码:
package com.ghibernate.pojo;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Table
public class Category {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private int id ;
private String name ;
//在多对一中的一端,设置了OneToMany后,必须指定mappedBy=多端的属性,这里的多端是Book
@OneToMany(mappedBy="category")
private Set<Book> books = new HashSet<Book>() ;
public Set<Book> getBooks() {
return books;
}
public void setBooks(Set<Book> books) {
this.books = books;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}