1. 什么是hibernate
ORM框架/持久层框架 jdbc的一个框架
object reference mapping
通过管理对象来改变数据库中的数据
通过管理对象来操作数据库
2. 如何在项目中添加hibernate支持(手动添加)
2.1 添加hibernate相关依赖
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.tt</groupId>
<artifactId>Hibernate</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>Hibernate Maven Webapp</name>
<url>http://maven.apache.org</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>
<junit.version>4.12</junit.version>
<servlet.version>4.0.0</servlet.version>
<hibernate.version>5.3.0.Final</hibernate.version>
<mysql.driver.version>5.1.46</mysql.driver.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${servlet.version}</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.driver.version}</version>
</dependency>
</dependencies>
<build>
<finalName>Hibernate</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<source>${maven.compiler.source}</source>
<target>${maven.compiler.target}</target>
<encoding>${project.build.sourceEncoding}</encoding>
</configuration>
</plugin>
</plugins>
</build>
</project>
2.2 在resource目录下添加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>
<!-- 1. 数据库相关 -->
<property name="connection.username">root</property>
<property name="connection.password">123</property>
<property name="connection.url">jdbc:mysql://localhost:3306/tt?useUnicode=true&characterEncoding=UTF-8
</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- 配置本地事务(No CurrentSessionContext configured!) -->
<property name="hibernate.current_session_context_class">thread</property>
<!-- 2. 调试相关 -->
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<!-- 3. 添加实体映射文件 -->
<mapping resource="com/tt/one/entity/User.hbm.xml" />
<!-- 主键生成策略 -->
<!-- <mapping resource="com/javaxl/two/entity/Student.hbm.xml" />
<mapping resource="com/javaxl/two/entity/Worker.hbm.xml" /> -->
</session-factory>
</hibernate-configuration>
2.2.1 添加DTD支持
hibernate-core-5.3.0.Final.jar下的dtd
2.2.2 添加Hibernate的配置
<?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>
<!-- 1. 数据库相关 -->
<property name="connection.username">root</property>
<property name="connection.password">123</property>
<property name="connection.url">jdbc:mysql://localhost:3306/tt?useUnicode=true&characterEncoding=UTF-8
</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- 配置本地事务(No CurrentSessionContext configured!) -->
<property name="hibernate.current_session_context_class">thread</property>
<!-- 2. 调试相关 -->
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<!-- 3. 添加实体映射文件 -->
<mapping resource="com/tt/one/entity/User.hbm.xml" />
<!-- 主键生成策略 -->
<!-- <mapping resource="com/javaxl/two/entity/Student.hbm.xml" />
<mapping resource="com/javaxl/two/entity/Worker.hbm.xml" /> -->
</session-factory>
</hibernate-configuration>
2.2.1 数据库相关
(connection.username|connection.password|connection.url|connection.driver_class|dialect)
2.2.2 调试相关(show_sql|format_sql)
2.3 在开发阶段再创建实体类和实体映射文件(*.hbm.xml)
实体类
package com.tt.one.entity;
import java.sql.Date;
import java.sql.Timestamp;
public class User {
private Integer id;
private String userName;
private String userPwd;
private String sex;
private Date birthday;
private String realName;
private Timestamp createDatetime;
private String remark;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserPwd() {
return userPwd;
}
public void setUserPwd(String userPwd) {
this.userPwd = userPwd;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getRealName() {
return realName;
}
public void setRealName(String realName) {
this.realName = realName;
}
public Timestamp getCreateDatetime() {
return createDatetime;
}
public void setCreateDatetime(Timestamp createDatetime) {
this.createDatetime = createDatetime;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public User(Integer id, String userName, String userPwd, String sex, Date birthday, String realName,
Timestamp createDatetime, String remark) {
this.id = id;
this.userName = userName;
this.userPwd = userPwd;
this.sex = sex;
this.birthday = birthday;
this.realName = realName;
this.createDatetime = createDatetime;
this.remark = remark;
}
public User() {
super();
}
@Override
public String toString() {
return "User [id=" + id + ", userName=" + userName + ", userPwd=" + userPwd + ", sex=" + sex + ", birthday="
+ birthday + ", realName=" + realName + ", createDatetime=" + createDatetime + ", remark=" + remark + "]";
}
}
实体类的配置
<?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:对应的是需要映射的实体类的全路径名
table:实体类对应的数据库中的表
id标签: 配置的是表中的主键
name: 对应类对应的数据库中的表
type: 指的实体类数据类型
column :数据库对应的列段
property : 配置出去主键以外的列段对应的类属性映射关系
name: 对应类对应的数据库中的表
type: 指的实体类数据类型
column :数据库对应的列段
insert="false" update="false"
上面的表示的含义是,该列段或者说该属性只做查询用,不做跟新
-->
<class name="com.tt.one.entity.User" table="t_hibernate_user">
<id name="id" type="java.lang.Integer" column="id">
<generator class="increment" />
</id>
<property name="userName" type="java.lang.String" column="user_name">
</property>
<property name="userPwd" type="java.lang.String" column="user_pwd">
</property>
<property name="realName" type="java.lang.String" column="real_name">
</property>
<property name="sex" type="java.lang.String" column="sex">
</property>
<property name="birthday" type="java.sql.Date" column="birthday">
</property>
<property insert="false" update="false" name="createDatetime"
type="java.sql.Timestamp" column="create_datetime">
</property>
<property name="remark" type="java.lang.String" column="remark">
</property>
</class>
</hibernate-mapping>
实体必须实现Serializable接口
小结:hibernate.cfg.xml(1)/*.hbm.xml(N)
实体映射文件一定要加到核心配置文件
3 Session(N)
- delete(先查再删除,保证程序的健壮性)
User u = (User) session.get(User.class,99);
if(null!=u){
session.delete(u);//比如id=99不存在,直接删除就会报错
}
2.update
先查再改,局部修改
3.Transaction(自动事务和手动事务讲解)
commit/rollback - Query(hql一章讲)
查全部/批量修改或删除
list
setXxx(String name,Xxx value);
setParameter(String name, Object value)
setParameterList(String name, Collection values)
setParameterList(String name, Object[] values)
setFirstResult/setMaxResults
4. 如何使用hibernate完成CRUD操作
4.1 CRUD操作步骤
4.1.1 读取配置
4.1.2 创建SessionFactory
4.1.3 打开Session
4.1.4 开启事务
4.1.5 CURD
4.1.6 提交事务/回滚事务
4.1.7 关闭Session
4.2 注意事项
4.2.1 hibernate默认使用的是手动事务,因此必须显示的开启和提交事务
4.2.2 删除操作时,必须先查再删
- 工具类SessionFactoryUtil
查所有
package com.tt.one.demo;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
/**
* hibernate查询演示
* @author tt
*
*/
public class QueryDemo {
public static void main(String[] args) {
Configuration configure = new Configuration().configure("/hibernate.cfg.xml");
SessionFactory sessionFactory = configure.buildSessionFactory();
//会话、而这里的会话指的是操作数据库的连接
Session session = sessionFactory.openSession();
List list = session.createQuery("from User").list();
for(Object obj : list) {
System.out.println(obj);
}
session.close();
}
}
增
package com.tt.one.demo;
import java.sql.Date;
import java.sql.Timestamp;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import com.tt.one.entity.User;
/**
* hibernate新增演示
* @author tt
*
*/
public class InsertDemo {
public static void main(String[] args) {
Configuration configure = new Configuration().configure("/hibernate.cfg.xml");
SessionFactory sessionFactory = configure.buildSessionFactory();
//会话、而这里的会话指的是操作数据库的连接
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
session.save(new User(null, "实木楼梯", "123", "妖", new Date(System.currentTimeMillis()), "李毅", new Timestamp(System.currentTimeMillis()), "巨头是"));
transaction.commit();
session.close();
}
}
改
package com.tt.one.demo;
import java.sql.Date;
import java.sql.Timestamp;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import com.tt.one.entity.User;
/**
* hibernate新增演示
* @author tt
*
*/
public class UpdateDemo {
public static void main(String[] args) {
Configuration configure = new Configuration().configure("/hibernate.cfg.xml");
SessionFactory sessionFactory = configure.buildSessionFactory();
//会话、而这里的会话指的是操作数据库的连接
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
// session.save(new User(null, "实木楼梯", "123", "妖", new Date(System.currentTimeMillis()), "李毅", new Timestamp(System.currentTimeMillis()), "巨头是"));
//不改变数据库内容,临时状态
// User u = new User(null, "实木楼梯", "123", "妖", new Date(System.currentTimeMillis()), "李毅", new Timestamp(System.currentTimeMillis()), "巨头是");
// u.setRealName("天天2232");
//交给hibernate,持久状态,会改变数据库
User user = session.get(User.class, 4);
user.setRealName("天天");
System.out.println(user);
transaction.commit();
session.close();
//关闭以后,游离状态
user.setRealName("天天22");
}
}
删
package com.tt.one.demo;
import java.sql.Date;
import java.sql.Timestamp;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import com.tt.one.entity.User;
/**
* hibernate新增演示
* @author tt
*
*/
public class DeleteDemo {
public static void main(String[] args) {
Configuration configure = new Configuration().configure("/hibernate.cfg.xml");
SessionFactory sessionFactory = configure.buildSessionFactory();
//会话、而这里的会话指的是操作数据库的连接
Session session = sessionFactory.openSession();
Transaction transaction = session.beginTransaction();
User u = new User();
u.setId(4);
session.delete(u);
transaction.commit();
session.close();
}
}
6. OID属性
与数据库主键列映射的属性
SessionFactory对象的创建代价很昂贵,它是线程安全的对象,它为所有的应用程序线程所共享。它只创建一次,通常是在应用程序启动的时候,由一个Configuraion的实例来创建
Session对象的创建代价比较小,是非线程安全的,对于单个请求,单个会话、单个的 工作单元而言,它只被使用一次,然后就丢弃。只有在需要的时候,一个Session对象 才会获取一个JDBC的Connection(或一个Datasource) 对象,因此假若不使用的时候它不消费任何资源。
Hibernate3.3.2版本中getSession().connection()已被弃用,hibernate4中官方推荐使用Session doWork()方法进行jdbc操作