hibernate 是一个(Object/Relation Mapping)对象关系映射 的框架。什么意思呢:表示我们只需要关心实体类的设计,数据库自动帮我们生成和管理数据库,存取到找 hibernate,我们底层数据库甚至可以任意更换(不用关系数据库直接的方言)。
首先来个demo:
目录结构:
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 name="foo">
<!-- 配置数据库信息 -->
<!-- dialect方言:数据库适配器,使用Oracle 时就需要使用Oracle 的方言 -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- characterEncoding=utf-8 这个编码记得和数据库编码相同,否者会出现乱码 -->
<property name="connection.url">jdbc:mysql:///hibernate?characterEncoding=utf-8</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<!-- 其他配置 -->
<!-- 控制台 显示代码 -->
<property name="hibernate.show_sql">true</property>
<!-- 控制台 格式化显示代码,方便查看 -->
<property name="hibernate.format_sql">false</property>
<!--
hbm2ddl.auto 更加映射文件或者注解 在数据库创建表结构。
create:先删除,再创建
update:如果表不存在就创建,不一样就更新,一样就什么都不做。(注意:更新字段属性,比如 字段长度,不会执行的,因为可能会影响已经存在的数据)
create-drop:初始化时创建表,SessionFactory执行close()时删除表。
validate:验证表结构是否一致,如果不一致,就抛异常。
-->
<property name="hbm2ddl.auto">update</property>
<!--
设置默认的事务隔离级别:
隔离级别 对应的整数表示
read uncommited 1
read commited 2
repeatable read 4
serializeable 8
-->
<property name="connection.isolation">2</property>
<!-- 导入映射文件 -->
<mapping resource="com/zll/test/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
注意:1、 第一自动生成,只能生成表,数据库还得需要自己创建。create database hibernate charset=utf8;
2、乱码问题:请查看数据库和表的编码是否是 utf8 (查看命令: show create database hibernate);并检查数据库连接配置信息的 connection.url 是否加了编码 jdbc:mysql:///hibernate?characterEncoding=utf-8。
User.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- package:表示使用哪个包下的对象。下面的class name就可以直接使用简单名称 -->
<hibernate-mapping package="com.zll.test">
<!-- table 属性不写默认为类的简单名称 -->
<class name="User" table="t_user">
<id name="id" type="int" column="id">
<generator class="native"/>
</id>
<property name="name" type="string" column="name" length="20"/>
</class>
</hibernate-mapping>
user.java
public class User {
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;
}
@Override
public String toString() {
return "[User: id=" + id + ", name=" + name + "]";
}
}
TestApp(junit 测试)
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test;
public class TestApp {
private static SessionFactory sessionFactory;
static {
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml"); // 读取指定的主配置文件
sessionFactory = cfg.buildSessionFactory(); // 根据生成Session工厂
}
@Test
public void testSave() throws Exception {
User user = new User();
user.setName("张三");
Session session = sessionFactory.openSession(); // 打开一个新的Session
Transaction tx = session.beginTransaction(); // 开始事务
session.save(user);// 保存
tx.commit(); // 提交事务
session.close(); // 关闭Session,释放资源
}
@Test
public void testGet() throws Exception {
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
User user = (User) session.get(User.class, 1); // 获取
System.out.println(user);
tx.commit();
session.close();
}
}
最后一个是用于项目部署和生成脚本使用(不适于程序代码,可生成脚本独立运行):
CreateSchema.java
import org.hibernate.cfg.Configuration;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.junit.Test;
public class CreateSchema {
// 根据配置生成表结构
@Test
public void test() throws Exception {
Configuration cfg = new Configuration().configure();
SchemaExport schemaExport = new SchemaExport(cfg);
// 第一个参数script的作用: print the DDL to the console
// 第二个参数export的作用: export the script to the database
schemaExport.create(true, true);
}
}