1.Book类和Category类
package cn.siggy.pojo;import java.util.Date;import javax.persistence.CascadeType;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;//entity表示需要持久化的实体类@Entity//实体类 所对应的表@Tablepublic class Book { //id主键 @Id //指定 主键生成策略 @GeneratedValue(strategy=GenerationType.AUTO) private int id; private String name; private double price; private String author; private Date pubDate; @ManyToOne(cascade=CascadeType.ALL) @JoinColumn(name="category_id") private Category category; /*get/set*/}
===========================package cn.siggy.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@Tablepublic class Category { @Id @GeneratedValue(strategy=GenerationType.AUTO) private int id; private String name; @OneToMany(mappedBy="category") private Setbooks = new HashSet (); /*get/set*/}
2.Hibernate.cfg.xml
com.mysql.jdbc.Driver jdbc:mysql:///hibernate4 root root org.hibernate.dialect.MySQLDialect true true update
3.测试代码
package cn.siggy.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 cn.siggy.pojo.Book;import cn.siggy.pojo.Category;import cn.siggy.util.HibernateUtil;public class HibernateTest { @Test public void testCreateDB(){ //3.x //Configuration cfg = new AnnotationConfiguration().configure(); Configuration cfg = new Configuration().configure(); SchemaExport se = new SchemaExport(cfg); se.create(true, true); } @Test public void testSave(){ Session session = HibernateUtil.getSession(); Book book = new Book(); book.setName("丰乳肥臀"); book.setPrice(60.5); book.setAuthor("莫言"); book.setPubDate(new Date()); Category category = new Category(); category.setName("文学"); book.setCategory(category); Transaction tx = session.beginTransaction(); 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.getName()+"---"+book.getCategory().getName()); tx.commit(); HibernateUtil.closeSession(); }}