1 下载hibernate-3.6.0 Final.zip到任意目录,解压缩后得到hibernate目录
2 下载slf4j-1.7.13.zip到任意目录,解压缩后得到slf4j-1.7.13
3 在test库中创建student表
msql -localhost -u root –p
use test
create table student(NO char(20),name varchar(20),primarykey(NO));
4 创建一个名为HibernateDemo的JavaProject
5 添加包
添加hibernate\jar中的所有包
添加slf4j-1.7.13中的slf4j-nop-1.7.13.jar
添加MySQL的驱动程序mysql-connector-Java-5.1.38-bin.jar
6添加两个配置文件和两个类
Hibernate.cfg.xml
Student.java
Student.hbm.xml
Test.java
(1)在src目录下添加目录下添加hibernate.cfg.xml
hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
true
org.hibernate.dialect.MySQLInnoDBDialect
com.mysql.jdbc.Driver
jdbc:mysql://localhost:3306/test
root
123456
(2)在src目录下的com.abc包中添加Student.java
package com.abc;
public class Student {
private String NO;
private String name;
public String getNO() {
return NO;
}
public void setNO(String NO) {
this.NO = NO;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
(3)在src目录下添加Student.hbm.xml
hibernate-mapping
PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
(4)Test.java
package com.abc;
import org.hibernate.*;
import org.hibernate.cfg.*;
public class Test {
public static void main(String[] args) {
try {
//通过Configuration获得一个SessionFactory对象
SessionFactory sf = new Configuration().configure().buildSessionFactory();
//打开一个Session
Session session = sf.openSession();
//开始一个事务
Transaction tx = session.beginTransaction();
//创建一个Student对象
Student stu = new Student();
//通过session的save()方法将Student对象保存到数据库中
stu.setNO("2016003");
stu.setName("Zhang San");
session.save(stu);
//提交事务
tx.commit();
//关闭会话
session.close();
} catch(Exception e) {
e.printStackTrace();
}
}
}
7 验证
(1)运行Test.java,结果为
Hibernate: insert into Student (name, NO)values (?, ?)
(2)从MySQL中查询数据