hibernate注解annotation入门

来源:互联网 发布:如何查看手机端口命令 编辑:程序博客网 时间:2024/06/16 02:40

前面的文章示例中我们写了实体类之后,都会写一个对应的*.hbm.xml配置文件,这种方式比较复杂,今天我们就来简单了解下使用注解annotation来替代配置文件的方法。

新建一个java项目,结构如下:


Book实体类,在实体类中使用注解,代码如下:

package com.test.pojo;import java.util.Date;import javax.persistence.Column;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;@Column(name="name")private String name;@Columnprivate double price;private String author;private Date pubDate;//省略get/set}
将实体类关联到hibernate.cfg.xml配置中

<hibernate-configuration><session-factory><property name="connection.driver_class">com.mysql.jdbc.Driver</property><property name="connection.url">jdbc:mysql:///hibernatetest</property><property name="connection.username">root</property><property name="connection.password">root</property><property name="dialect">org.hibernate.dialect.MySQLDialect</property><property name="show_sql">true</property><property name="format_sql">true</property><mapping class="com.test.pojo.Book" /></session-factory></hibernate-configuration>
HibernateUtil类

public class HibernateUtil {private static Configuration cfg=null;private static SessionFactory factory=null;private static Session session=null;static{cfg=new Configuration().configure();factory=cfg.buildSessionFactory(new StandardServiceRegistryBuilder()        .applySettings(cfg.getProperties()).build());}public static Session getSession(){if(factory!=null)return session=factory.openSession();factory=cfg.buildSessionFactory(new StandardServiceRegistryBuilder()        .applySettings(cfg.getProperties()).build());return session=factory.openSession();}public static void closeSession(){if(session!=null && session.isOpen())session.close();}
测试类HibernateTest

public class HibernateTest {@Testpublic void testCreateDB(){Configuration cfg=new Configuration().configure();SchemaExport se=new SchemaExport(cfg);se.create(true, true);}@Testpublic void testSave(){Session session=HibernateUtil.getSession();Transaction tx=session.beginTransaction();Book book=new Book();book.setName("读者");book.setPrice(21.5);book.setAuthor("读者出版传媒有限公司");book.setPubDate(new Date());session.save(book);tx.commit();HibernateUtil.closeSession();}}

执行testCreateDB,打印信息如下:

drop table if exists t_book    create table t_book (        id integer not null auto_increment,        author varchar(255),        name varchar(255),        price double precision,        pubDate datetime,        primary key (id)    )
执行testSave,打印信息如下:

Hibernate:     insert     into        t_book        (author, name, price, pubDate)     values        (?, ?, ?, ?)

数据库表信息如下: