使用工具
IDEA、Maven、Java8、Hibernate5.3.7
具体步骤
创建项目
选择mavan->quickStart->输入groupId以及项目名称
添加依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>cn.hibernate</groupId>
<artifactId>abc</artifactId>
<version>1.0-SNAPSHOT</version>
<name>abc</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<!-- junit单元测试 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- 添加Hibernate依赖 -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.3.7.Final</version>
</dependency>
<!-- 添加mysql数据库驱动包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<!-- 添加slf4j依赖 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.25</version>
</dependency>
<!-- 添加slf4j-log4j转换包 -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.25</version>
</dependency>
<!-- 添加log4j依赖 -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
</dependencies>
<build>
<finalName>hibernate-abc</finalName>
<!-- 读取配置文件 -->
<resources>
<resource>
<directory>src/main/resources</directory>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
</project>
编写核心配置文件hibernate.cfg.xml
将官方资源包etc路径下复制hibernate.cfg.xml到resources目录下
从官方文档中可以得知以下配置主要作用于JDBC的连接,方言的选择和数据库更新方式
何为方言?
hibernate.dialect就是“方言”,因为hibernate是要把Java对象转换成关系数据库来描述的,而关系数据库虽然有一些统一的标准,如SQL-92等,但是实际上各数据库如Oracle, MySQL, MS SQL Server等等为了提高性能或增加功能都提供了一些额外的标准或语法,因此,hibernate为了更好适配各种关系数据库,针对每种数据库都指定了一个方言dialect。hibernate里面实际上方言只是一个类,它里面将不同数据类型、SQL语法转换成hibernate能理解的统一的格式。如果没有对应的dialect,Hibernate是无法使用这种数据库进行对象关系转换的。说白了,就是告诉Hibernate,将你写的那些HQL、QBC等等,翻译成哪种数据库的SQL。
何为数据库更新方式?
hibernate.hbm2ddl.auto参数的作用主要用于:自动创建|更新|验证数据库表结构。
- create:每次执行前都先把原有数据表删除,然后创建该表,这就是导致数据库表数据丢失的一个重要原因。
- create-drop:每次执行前都先把原有数据表删除,然后创建该表,关闭SessionFactory时,将删除掉数据库表。
- validate:每次加载hibernate时,验证创建数据库表结构,只会和数据库中的表进行比较,不会创建新表,如果不一致就抛出异常,但是会插入新值。
- update:最常用的属性,第一次加载hibernate时根据model类会自动建立起表的结构(前提是先建立好数据库),以后加载hibernate时根据 model类自动更新表结构,即使表结构改变了但表中的行仍然存在不会删除以前的行。要注意的是当部署到服务器后,表结构是不会被马上建立起来的,是要等应用第一次运行起来后才会。
<?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>
<!-- 配置数据库连接信息 -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property
name="connection.url">jdbc:mysql://localhost:3306/hibernate5?useUnicode=true&characterEncoding=UTF-8</property>
<property name="connection.username">root</property>
<property name="connection.password">0000</property>
<!-- 数据库方言 -->
<property name="dialect">org.hibernate.dialect.MySQL57Dialect</property>
<!-- 数据库更新方式 -->
<property name="hbm2ddl.auto">update</property>
<!-- 是否打印sql -->
<property name="show_sql">true</property>
<!-- 格式化sql -->
<property name="format_sql">true</property>
<!-- 添加*.hbm.xml映射 -->
<mapping resource="cn/hibernate/pojo/Function.hbm.xml"/>
<mapping resource="cn/hibernate/pojo/Role.hbm.xml"/>
</session-factory>
</hibernate-configuration>
创建POJO对象
public class User implements Serializable {
private Integer id;
private String userName;
private String userPwd;
//省略getter、setter、构造器
//一定要实现Serializable接口
}
编写*.hbm.xml文件
一般为POJO类名称,比如User.hbm.xml,该文件放在POJO类所在包下。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="cn.hibernate.pojo.User" >
<id name="id">
<!-- 主键生成策略 -->
<generator class="native"></generator>
</id>
<!-- 实体类的属性 -->
<property name="userName"/>
<property name="userPwd"/>
</class>
</hibernate-mapping>
测试
@Test
public void testSave(){
SessionFactory sessionFactory = null;
Session session = null;
Transaction transaction = null;
try {
/*
// 新建Configuration对象
Configuration cfg = new Configuration().configure();
// 通过Configuration创建SessionFactory对象
// 在hibernate3.x中是这种写法项目结构和测试结果
SessionFactory sf = cfg.buildSessionFactory();
// 在hibernate4.x中是这种写法
StandardServiceRegistry sr = new StandardServiceRegistryBuilder()
.applySettings(cfg.getProperties()).build();
SessionFactory sf = cfg.buildSessionFactory(sr);
*/
// 在hibernate5.x中是这种写法,不需要自己创建Configuration()对象
// .configure()如果不写参数,表示默认获取的是hibernate.cfg.xml,
// 配置文件的名字是不能改的,如果改掉之后,就应该在configure()方法中传入配置文件名字,有必要的话还要传入路径。
// 创建服务注册对象
StandardServiceRegistry standardServiceRegistry = new StandardServiceRegistryBuilder().configure().build();
// 通过Metadata创建SessionFactory
sessionFactory = new MetadataSources(standardServiceRegistry).buildMetadata().buildSessionFactory();
// 通过SessionFactory得到Session
session = sessionFactory.openSession();
// 通过Session对象得到Transaction对象--开启事务
transaction = session.beginTransaction();
// 保存数据
User user = new User();
user.setUserName("张三");
user.setUserPwd("111");
session.save(user);
// 提交事务
transaction.commit();
}catch (Exception e){
e.printStackTrace();
// 回滚事务
transaction.rollback();
}finally {
// 关闭session
if (null != session && session.isOpen()){
session.close();
}
}
}