一.准备工作
1.在eclipse安装好hibernate tools以便框架的开发
2.下载hibernate后,创建一个名为hibernate_001的java项目,导入hibernate中lib/required的所有jar包,同时导入junit和mysql的jar包
3.准备工作完成后可以开始编写hibernate
二.编写hibernate例子
1.新建一个hibernate配置文件(cfg.xml)
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>
<!-- hibernate.connection.driver_class : 连接数据库的驱动 -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- hibernate.connection.username : 连接数据库的用户名 -->
<property name="hibernate.connection.username">root</property>
<!-- hibernate.connection.password : 连接数据库的密码 -->
<property name="hibernate.connection.password">123</property>
<!-- hibernate.connection.url : 连接数据库的地址,路径 -->
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate?useUnicode=true&characterEncoding=UTF-8</property>
<!-- 数据库方言配置 org.hibernate.dialect.MySQLDialect (选择最短的)-->
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<!-- show_sql: 操作数据库时,会 向控制台打印sql语句 -->
<property name="show_sql">true</property>
<!-- format_sql: 打印sql语句前,会将sql语句先格式化 -->
<property name="format_sql">true</property>
<!-- 指定hibernate启动的时候自动创建表结构creat update -->
<property name="hbm2ddl.auto">create</property>
</session-factory>
</hibernate-configuration>
3.创建一个持久化类Students.java
import java.util.Date;
public class Students {
private int sid;
private String sname;
private String gendar;
private Date birthday;
private String address;
public Students(){
super();
}
public Students(int sid, String sname, String gendar, Date birthday, String address) {
super();
this.sid = sid;
this.sname = sname;
this.gendar = gendar;
this.birthday = birthday;
this.address = address;
}
public int getSid() {
return sid;
}
public void setSid(int sid) {
this.sid = sid;
}
public String getSname() {
return sname;
}
public void setSname(String sname) {
this.sname = sname;
}
public String getGendar() {
return gendar;
}
public void setGendar(String gendar) {
this.gendar = gendar;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "Students [sid=" + sid + ", sname=" + sname + ", gendar=" + gendar + ", birthday=" + birthday
+ ", address=" + address + "]";
}
}
4.创建一个对象——关系映射文件(hbm.xml)
为上一步的持久化类创建对象关系映射文件Students.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">
<!-- Generated 2019-2-1 20:23:07 by Hibernate Tools 3.5.0.Final -->
<hibernate-mapping>
<class name="Students" table="STUDENTS">
<id name="sid" type="int">
<column name="SID" />
<generator class="assigned" />
</id>
<property name="sname" type="java.lang.String">
<column name="SNAME" />
</property>
<property name="gendar" type="java.lang.String">
<column name="GENDAR" />
</property>
<property name="birthday" type="java.util.Date">
<column name="BIRTHDAY" />
</property>
<property name="address" type="java.lang.String">
<column name="ADDRESS" />
</property>
</class>
</hibernate-mapping>
5.在之前的配置文件中加一句
<mapping resource="Students.hbm.xml"/>
6.编写junit测试类
在项目中new一个source folder名为test
创建StudentsTest类
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
public class StudentsTest {
private SessionFactory sessionFactory;
private Session session;
private Transaction transaction;
@Before
public void init(){
//创建配置对象
Configuration config = new Configuration().configure();
//创建服务注册对象
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(config .getProperties()).build();
//创建会话工厂对象
sessionFactory = config.buildSessionFactory(serviceRegistry);
//会话对象
session = sessionFactory.openSession();
//开启事务
transaction = session.beginTransaction();
}
@After
public void destroy(){
transaction.commit();//提交事务
session.close();//关闭会话
sessionFactory.close();//关闭会话工厂
}
@Test
public void testSaveStudents(){
Students s = new Students(1,"张三","男",new Date(),"武汉");
session.save(s);//保存对象进入数据库
}
}
7.用junit测试testSaveStudents方法
8.测试结果
二月 02, 2019 2:21:57 下午 org.hibernate.Version logVersion
INFO: HHH000412: Hibernate Core {5.3.7.Final}
二月 02, 2019 2:21:57 下午 org.hibernate.cfg.Environment <clinit>
INFO: HHH000206: hibernate.properties not found
二月 02, 2019 2:21:57 下午 org.hibernate.annotations.common.reflection.java.JavaReflectionManager <clinit>
INFO: HCANN000001: Hibernate Commons Annotations {5.0.4.Final}
二月 02, 2019 2:21:57 下午 org.hibernate.boot.jaxb.internal.stax.LocalXmlResourceResolver resolveEntity
WARN: HHH90000012: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/hibernate-mapping. Use namespace http://www.hibernate.org/dtd/hibernate-mapping instead. Support for obsolete DTD/XSD namespaces may be removed at any time.
二月 02, 2019 2:21:58 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!)
二月 02, 2019 2:21:58 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/hibernate?useUnicode=true&characterEncoding=UTF-8]
二月 02, 2019 2:21:58 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {user=root, password=****}
二月 02, 2019 2:21:58 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
二月 02, 2019 2:21:58 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections <init>
INFO: HHH000115: Hibernate connection pool size: 20 (min=1)
二月 02, 2019 2:21:58 下午 org.hibernate.dialect.Dialect <init>
INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
Hibernate:
drop table if exists STUDENTS
二月 02, 2019 2:21:59 下午 org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@5b6e8f77] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
Hibernate:
create table STUDENTS (
SID integer not null,
SNAME varchar(255),
GENDAR varchar(255),
BIRTHDAY datetime,
ADDRESS varchar(255),
primary key (SID)
) engine=MyISAM
二月 02, 2019 2:21:59 下午 org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@2caf6912] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
二月 02, 2019 2:21:59 下午 org.hibernate.tool.schema.internal.SchemaCreatorImpl applyImportSources
INFO: HHH000476: Executing import script 'org.hibernate.tool.schema.internal.exec.ScriptSourceInputNonExistentImpl@22101c80'
Hibernate:
insert
into
STUDENTS
(SNAME, GENDAR, BIRTHDAY, ADDRESS, SID)
values
(?, ?, ?, ?, ?)
二月 02, 2019 2:21:59 下午 org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
INFO: HHH10001008: Cleaning up connection pool [jdbc:mysql://localhost:3306/hibernate?useUnicode=true&characterEncoding=UTF-8]
三.总结
1.关于测试过程中出现unknown entity,原因出自hibernate版本问题init方法的写法不同
hibernate4.3之前写法
@Before
public void init(){
Configuration config = new Configuration().configure();
ServiceRegistry serviceRegistry = new SerivceRegistryBuilder().applySettings(config.getProperties()).build();
sessionFactory = config.buildSessionFactory(serviceRegistry);
session = sessionFactory.openSession();
transaction = session.beginTransaction();
}
2.测试中出现hibernate could not execute statement
使用hibernate5导致,要在之前配置文件中修改
原来这样写
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
hibernate5要修改为
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>