hibernate环境配置
添加相关依赖
<properties>
<hibernate-version>4.3.10.Final</hibernate-version>
<mysql-version>5.1.30</mysql-version>
</properties>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate-version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql-version}</version>
</dependency>
</dependencies>
编写hibernate配置文件(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>
<!-- 配置JDBC -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- 配置URL -->
<property name="connection.url">jdbc:mysql:///hibernatedb</property>
<!-- 配置用户名和密码 -->
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<!-- 设置数据库方言 -->
<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
<!-- 打印mysql语句 -->
<property name="show_sql">true</property>
<!-- 格式化打印sql -->
<property name="format_sql">true</property>
<!-- 数据表操作 -->
<property name="hbm2ddl.auto">update</property>
<!-- 添加映射文件 -->
<mapping resource="Teacher.hbm.xml"/>
</session-factory>
</hibernate-configuration>
编写实体类
package com.wd.pojo;
import java.util.List;
public class Teacher {
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;
}
}
编写映射文件(此处需要注意int和Integer类型属性并不能够通过length进行长度指定,在mysql中生成的表的DDL字段长度始终为11)
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping SYSTEM "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd" >
<hibernate-mapping package="com.wd.pojo">
<class name="Teacher" table="t_teacher">
<id name="id" column="id">
<generator class="native"></generator>
</id>
<property name="name" column="name" length="50"></property>
</class>
</hibernate-mapping>
SessionFactory是进程级别的,Session为线程级别
为方便调用,编写hibernateUtil
public class HibernateUtil {
private static Configuration cfg = null;
private static StandardServiceRegistry registry = null;
private static SessionFactory factory = null;
static {
cfg = new Configuration().configure();
registry = new StandardServiceRegistryBuilder().applySettings(cfg.getProperties()).build();
factory = cfg.buildSessionFactory(registry);
}
public static Session getSession() {
return factory.openSession();
}
}