1.Book类
package cn.siggy.pojo;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
//entity表示需要持久化的实体类
@Entity
//实体类 所对应的表
@Table(name="t_book")
public class Book {
//id主键
@Id
//指定 主键生成策略
@GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String name;
private double price;
private String author;
private Date pubDate;
/*get/set*/
}
2.hibernate.cfg.xml【注解方式不需要Book.hbm.xml映射文件,但需要在*.cfg.xml中引入:<mapping class="cn.siggy.pojo.Book" />】
<!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> <!--hibernate可选项 --> <property name="dialect"> org.hibernate.dialect.MySQLDialect </property> <property name="show_sql">true</property> <property name="format_sql">true</property> <property name="hbm2ddl.auto">update</property> <!-- hbm文件 --> <mapping class="cn.siggy.pojo.Book" /> </session-factory> </hibernate-configuration>
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.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());
Transaction tx = session.beginTransaction();
session.save(book);
tx.commit();
HibernateUtil.closeSession();
}
}
4.测试结果
原文:http://www.cnblogs.com/chxbar/p/6686648.html