一、准备工作
1,下载hibernate。地址: http://hibernate.org/orm/downloads/
2,下载数据库驱动。以MySql为例,其驱动官方称作MySql Connector。地址: http://www.mysql.com/downloads/
3,创建一个测试数据库hibernate_first,再创建一个User表,各字段如下(id为主键):
二、工程实例
1,新建一个普通Java工程,在Build Path中加入数据库驱动jar包路径及hibernate的jar包路径。最新hibernate5.0.4的jar包目录结构如下:
Required是必须的,其它的如果搞不懂作用就全部加入到Build Path中,否则可能有编译错误。
2,在src目录下新建数据库默认的配置文件:hibernate.cfg.xml,内容如下:
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<!--hibernate_first要操作的数据库-->
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate_first</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">bourne</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!--是否在控制台输出操作的sql语句-->
<property name="hibernate.show_sql">true</property>
<mapping resource="com/entity/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
3,在src下创建一个com.entity包,再创建一个User类,代码如下:
package com.entity;
import java.util.Date;
public class User {
private String id;
private String name;
private String password;
private Date createTime;
private Date expireTime;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getExpireTime() {
return expireTime;
}
public void setExpireTime(Date expireTime) {
this.expireTime = expireTime;
}
}
4,在com.entity下创建实体映射文件User.hdm.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">
<hibernate-mapping>
<class name="com.entity.User">
<id name="id">
<generator class="uuid"/>
</id>
<property name="name"/>
<property name="password"/>
<property name="createTime"/>
<property name="expireTime"/>
</class>
</hibernate-mapping>
User.hbm.xml的作用简而言之就是对实体和数据库中的表进行相呼应,保证我们对实体对象进行的操作都会在数据库中产生与之对应响应的结果。
5,在com.entity下创建测试类Client
package com.entity;
import java.util.Date;
import java.util.List;
import java.util.Iterator;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Query;
import org.hibernate.cfg.Configuration;
import com.entity.User;
public class Client {
private SessionFactory factory = null;
public Client(SessionFactory factory){
this.factory = factory;
}
@SuppressWarnings("unchecked")
public void query(){
Session session = null;
try {
session = factory.openSession();
//开启事务
session.beginTransaction();
Query query = session.createQuery("from User");
//还可以这样加限制条件
//Query query = session.createQuery("from User WHERE name='NAME1'");
System.out.printf("%-50s%-20s%-20s\n", "id", "name", "password");
List<User> users = query.list();
for(Iterator<User> iter = users.iterator(); iter.hasNext();)
{
User user =(User)iter.next();
System.out.printf("%-50s%-20s%-20s\n", user.getId(),
user.getName(), user.getPassword());
}
session.getTransaction().commit();
}catch(Exception e) {
e.printStackTrace();
//回滚事务
session.getTransaction().rollback();
}finally {
if (session != null) {
if (session.isOpen()) {
//关闭session
session.close();
}
}
}
}
public void update(){
Session session = null;
try {
session = factory.openSession();
//开启事务
session.beginTransaction();
//这里的id应先从数据库查询
User user = session.load(User.class, "402881ec5153a792015153a793e80000");
user.setName("Jack");
session.update(user);
session.getTransaction().commit();
}catch(Exception e) {
e.printStackTrace();
//回滚事务
session.getTransaction().rollback();
}finally {
if (session != null) {
if (session.isOpen()) {
//关闭session
session.close();
}
}
}
}
public void insert(){
//取得session
Session session = null;
try {
session = factory.openSession();
//开启事务
session.beginTransaction();
/*
* 插入一条user记录
*/
User user = new User();
user.setName("Mary");
user.setPassword("123456");
user.setCreateTime(new Date());
user.setExpireTime(new Date());
//session.load(User.class, arg1)
//保存User对象
session.save(user);
//提交事务
session.getTransaction().commit();
}catch(Exception e) {
e.printStackTrace();
//回滚事务
session.getTransaction().rollback();
}finally {
if (session != null) {
if (session.isOpen()) {
//关闭session
session.close();
}
}
}
}
public void delete(){
Session session = null;
try {
session = factory.openSession();
//开启事务
session.beginTransaction();
User user = new User();
//这里的id应先从数据库查询
user.setId("402881ec5153e384015153e3854f0000");
session.delete(user);
session.getTransaction().commit();
}catch(Exception e) {
e.printStackTrace();
//回滚事务
session.getTransaction().rollback();
}finally {
if (session != null) {
if (session.isOpen()) {
//关闭session
session.close();
}
}
}
}
public static void main(String[] args) {
//读取hibernate.cfg.xml文件
Configuration cfg = new Configuration().configure();
//建立SessionFactory
SessionFactory factory = cfg.buildSessionFactory();
Client client = new Client(factory);
client.query();
client.insert();
System.out.println("table after inserted:");
client.query();
client.update();
System.out.println("table after updated:");
client.query();
client.delete();
System.out.println("table after deleted:");
client.query();
}
}
最后的工程目录应该是这样的:
没有错误的话,运行Client.Java就能看到测试结果了。