hibernate 简介:
hibernate是一个开源框架,它是对象关联关系映射的框架,它对JDBC做了轻量级的封装,而我们java程序员可以使用面向对象的思想来操纵数据库。
hibernate核心接口
session:负责被持久化对象CRUD操作
sessionFactory:负责初始化hibernate,创建session对象
configuration:负责配置并启动hibernate,创建SessionFactory
Transaction:负责事物相关的操作
Query和Criteria接口:负责执行各种数据库查询
hibernate工作原理:
1.通过Configuration config = new Configuration().configure();//读取并解析hibernate.cfg.xml配置文件
2.由hibernate.cfg.xml中的<mapping resource="com/xx/User.hbm.xml"/>读取并解析映射信息
3.通过SessionFactory sf = config.buildSessionFactory();//创建SessionFactory
4.Session session = sf.openSession();//打开Sesssion
5.Transaction tx = session.beginTransaction();//创建并启动事务Transation
6.persistent operate操作数据,持久化操作
7.tx.commit();//提交事务
8.关闭Session
9.关闭SesstionFactory
简单了解,下面切入正题。
数据库(mysql):
项目结构如图(eclipse):
1.新建java项目,建一个lib文件夹,导入hibernate必须的jar包和mysql驱动jar包——>add to build path。
2.创建实体类(User):
package cn.xxs.entity;
import java.util.Date;
public class User {
private Integer id;
private String name;
private String pwd;
private Date createDate;
public User() {
super();
// TODO Auto-generated constructor stub
}
public User(Integer id, String name, String pwd, Date createDate) {
super();
this.id = id;
this.name = name;
this.pwd = pwd;
this.createDate = createDate;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", pwd=" + pwd + ", createDate=" + createDate + "]";
}
}
3.创建类的映射文件(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">
<hibernate-mapping>
<!-- name为实体类包名加类名 table为数据库表名 -->
<class name="cn.xxs.entity.User" table="user">
<!-- 主键 -->
<id name="id" column="id">
<generator class="native"/>
</id>
<!-- 字段 -->
<property name="name" type="java.lang.String" column="name"/>
<property name="pwd" type="java.lang.String" column="pwd"/>
<property name="createDate" type="java.util.Date" column="createDate"/>
</class>
</hibernate-mapping>
4.把User.hbm.xml文件加载到hibernate.cfg.xml核心配置文件中
<?xml version="1.0" encoding='utf-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings 数据库连接 -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<!-- SQL dialect 方言 -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Echo all executed SQL to stdout 显示sql语句 -->
<property name="show_sql">true</property>
<!-- 格式化sql语句 -->
<property name="hibernate.format_sql">true</property>
<mapping resource="cn/xxs/entity/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
5.测试(增删改查)
(1)创建一个工具类
package cn.xxs.util;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static SessionFactory sessionFactory;
static {
sessionFactory = new Configuration().configure().buildSessionFactory();
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
(2)创建测试类
package cn.xxs.test;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.junit.Test;
import cn.xxs.entity.User;
import cn.xxs.util.HibernateUtil;
public class HibernateTest {
// 1.导入hibernate必须的jar包和mysql驱动jar包
// 2.创建类(User)
// 3.创建类的映射文件(User.hbm.xml)
// 4.把User.hbm.xml文件加载到hibernate.cfg.xml核心配置文件中
// 5.测试
//查询数据 method1
public static void main(String[] args) {
SessionFactory sf = new Configuration().configure().buildSessionFactory();
Session session = sf.openSession();
User user = session.get(User.class, 3);
System.out.println(user == null ? "" : user.toString());
}
//查询数据 method2
@Test
public void test() {
//SessionFactory sf = new Configuration().configure().buildSessionFactory();
SessionFactory sf = HibernateUtil.getSessionFactory();
Session session = sf.openSession();
User user = session.get(User.class, 3);
System.out.println(user == null ? "" : user.toString());
}
//添加数据
@Test
public void test1() {
// 1、和获取SessionFactory
SessionFactory sf = HibernateUtil.getSessionFactory();
// 2、获取session
Session session = sf.openSession();
// 开启事务
Transaction transaction = session.beginTransaction();
//保存数据
User user = new User();
user.setName("peter");
user.setPwd("123");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String str = sdf.format(new Date());
Date date = null;
try {
date = sdf.parse(str);
} catch (ParseException e) {
e.printStackTrace();
}
user.setCreateDate(date);
session.save(user);
transaction.commit();
session.close();
}
//更新数据
@Test
public void test2() {
// 1、和获取SessionFactory
SessionFactory sf = HibernateUtil.getSessionFactory();
// 2、获取session
Session session = sf.openSession();
// 开启事务
Transaction transaction = session.beginTransaction();
//更新数据
User user = session.get(User.class, 3);
user.setName("lucy");
session.update(user);
transaction.commit();
//关闭
session.close();
}
//删除
@Test
public void test3() {
// 1、和获取SessionFactory
SessionFactory sf = HibernateUtil.getSessionFactory();
// 2、获取session
Session session = sf.openSession();
// 开启事务
Transaction transaction = session.beginTransaction();
//更新数据
User user = session.get(User.class, 4);
session.delete(user);
transaction.commit();
//关闭
session.close();
}
}
运行结果描述:
选中main()右击,Run As --> Java Application
选中test()右击,Run As --> Junit Test
选中test1()右击,Run As --> Junit Test
选中test2()右击,Run As --> JJunit Test
选中test3()右击,Run As --> Junit Test
那么下边我们用注解方式实现一下:
项目结构:
我们可以看出,少了类的映射文件(User.hbm.xml)
除此之外,我们是在实体类Person.java和hibernate.cfg.xml核心配置文件做了改动。
实体类Person.java改动后:
package cn.xxs.entity;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="user")
public class Person {
private Integer id;
private String name;
private String pwd;
private Date createDate;
public Person() {
super();
// TODO Auto-generated constructor stub
}
public Person(Integer id, String name, String pwd, Date createDate) {
super();
this.id = id;
this.name = name;
this.pwd = pwd;
this.createDate = createDate;
}
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="id")
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
@Column(name="name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Column
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
@Column
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", pwd=" + pwd + ", createDate=" + createDate + "]";
}
}
hibernate.cfg.xml核心配置文件只将
<mapping resource="cn/xxs/entity/User.hbm.xml"/>
改写成
<mapping class="cn.xxs.entity.Person"/>。
是不是注解更简单呢。