借用官方的demo稍加改编进行分析,
1.pom.xml配置参考http://my.oschina.net/u/555061/blog/506049
2.hibernate.cfg.xml配置实体关系表,
<?xml version='1.0' encoding='utf-8'?> <!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> <!-- Database connection settings --> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql://192.168.191.1:3306/mysql</property> <property name="connection.username">root</property> <property name="connection.password">root</property> <!-- JDBC connection pool (use the built-in) --> <property name="connection.pool_size">1</property> <!-- SQL dialect --> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <!-- Disable the second-level cache --> <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property> <!-- Echo all executed SQL to stdout --> <property name="show_sql">true</property> <!-- Drop and re-create the database schema on startup --> <property name="hbm2ddl.auto">create</property> <!-- Names the annotated entity class --> <mapping class="org.hibernate.tutorial.annotations.Event"/> </session-factory> </hibernate-configuration>
跟链接提到的配置都一样,除了mapping这里,
由原来的<mapping resource="UserModel.hbm.xml"/>--配置映射
改为现在的<mapping class="org.hibernate.tutorial.annotations.Event"/>--类(注解)映射
3.看下这个实体Entity如何应用注解替代了配置映射
package org.hibernate.tutorial.annotations; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.Table; import javax.persistence.Temporal; import javax.persistence.TemporalType; import org.hibernate.annotations.GenericGenerator; @Entity @Table(name = "EVENTS") public class Event { @Id @GeneratedValue(generator = "increment") @GenericGenerator(name = "increment", strategy = "increment") @Column(name="EVENT_ID") private Long id; private String title; @Temporal(TemporalType.TIMESTAMP) @Column(name = "EVENT_DATE") private Date date; private int times; private boolean isSerious; public Event() { // this form used by Hibernate } public Event(String title, Date date, int times, boolean isSerious) { // for application use, to create new events this.title = title; this.date = date; this.times = times; this.isSerious = isSerious; } getters和setters省略。。。 }
解释下,
3.1表头的注解
这里@Entity固定写法,@Table是映射数据库表,表名为EVENTS
3.2主键的注解
@Id标识id属性为主键
@GeneratedValue(generator = "increment")和@GenericGenerator(name = "increment", strategy = "increment")是主键自增配置,等效于xml那里的native/increment
@Column(name="EVENT_ID")这里的id映射数据库里的EVENT_ID字段,不过现在本人觉得还是统一数据库字段名称和object的属性名一致要好,也就是这里写成@Column(name="ID"),或者不写@Column注解,它会自动同步属性为数据库表字段,以免以后出现不匹配的问题
3.3特殊类型的注解(Date类型)
这里解释下,主要是Date这种类型比较特别,所以需要@Temporal(TemporalType.TIMESTAMP)来特别注解,像String/int/boolean都不需要特别注解
可以看到TemporalType一共有3种类型可选:DATE/TIME/TIMESTAMP
3.4hibernate处理boolean的原理
从生成的sql语句可以看到hibernate处理boolean类型是用的tinyint类型
CREATE TABLE `events` ( `EVENT_ID` bigint(20) NOT NULL, `EVENT_DATE` datetime DEFAULT NULL, `isSerious` tinyint(1) NOT NULL, `times` int(11) NOT NULL, `title` varchar(255) DEFAULT NULL, PRIMARY KEY (`EVENT_ID`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
4.测试,跟xml映射配置没区别,注解和xml映射配置功效都是一样的,类似于spring
public void testBasicUsage() { // create a couple of events... Session session = sessionFactory.openSession(); session.beginTransaction(); session.save( new Event( "Our very first event!", new Date(), 3, false ) ); session.save( new Event( "A follow up event", new Date(), 5, true ) ); session.save( new HibernateEmployee( "uuid", 123, "ayu", true ) ); session.getTransaction().commit(); session.close(); // now lets pull events from the database and list them session = sessionFactory.openSession(); session.beginTransaction(); List<Event> result = session.createQuery( "from Event" ).list(); for ( Event event : result ) { System.out.println( "Event (" + event.getDate() + ") : " + event.getTitle() ); System.out.println( "info : " + event.getTimes() + "|" + event.isSerious() ); } session.getTransaction().commit(); session.close(); }
这里from Event是用的hqsql语法,打印结果如下,