1. 什么是 hibernate
ORM框架/持久层框架
jdbc的一个框架 object reference mapping
通过管理对象来改变数据库中的数据
通过管理对象来操作数据库
2.配置文件
- 创建一个maven项目
- 配置pom.xml 依赖文件
<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.wr</groupId>
<artifactId>T237_hibernate</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>T237_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>T237_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>
- 配置web.xml版本 3.1
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<display-name>Archetype Created Web Application</display-name>
</web-app>
- 在src/main/resources目录下添加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">1234</property> //数据库的密码
<property name="connection.url">jdbc:mysql://localhost:3306/t235? useUnicode=true&characterEncoding=UTF-8 //连接数据库的
</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- 如果使用别的数据库,换一种方言即可 org.hibernate.dialect.MySQLDialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- (固定配置)配置本地事务(No CurrentSessionContext configured!) -->
<property name="hibernate.current_session_context_class">thread</property>
<!-- 2. 调试sql相关 -->
<!--在控制台 显示sql语句 -->
<property name="show_sql">true</property>
<!--sql语句可以 换行 (让格式变漂亮一些) -->
<property name="format_sql">true</property>
</session-factory>
</hibernate-configuration>
- 在开发阶段再创建 实体类 和 实体映射文件 (*.hbm.xml)
实体类 User
package com.wr.one.entity;
import java.sql.Date;
import java.sql.Timestamp;
public class User {
private Integer id;
private String username;
private String userpwd;
private String realname;
private String sex;
private Date birthday;
private Timestamp createDatetime;
private String remark;
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = 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 getRealname() {
return realname;
}
public void setRealname(String realname) {
this.realname = realname;
}
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 Timestamp getCreateDatetime() {
return createDatetime;
}
public void setCreateDatetime(Timestamp createDatetime) {
this.createDatetime = createDatetime;
}
public User(Integer id, String username, String userpwd, String realname, String sex, Date birthday,
Timestamp createDatetime, String remark) {
super();
this.id = id;
this.username = username;
this.userpwd = userpwd;
this.realname = realname;
this.sex = sex;
this.birthday = birthday;
this.createDatetime = createDatetime;
this.remark = remark;
}
public User(String username, String userpwd, String realname, String sex, Date birthday, Timestamp createDatetime,
String remark) {
super();
this.username = username;
this.userpwd = userpwd;
this.realname = realname;
this.sex = sex;
this.birthday = birthday;
this.createDatetime = createDatetime;
this.remark = remark;
}
public User() {
super();
// TODO Auto-generated constructor stub
}
@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", userpwd=" + userpwd + ", realname=" + realname
+ ", sex=" + sex + ", birthday=" + birthday + ", createDatetime=" + createDatetime + "]";
}
}
实体类的映射文件
class标签下的属性
name:数据库中的表 映射的 实体类的全路径名
table:要映射的数据库
id标签 (id标签 和property标签是一样的 ,id标签 用来标识主键的)
name:数据库表的列段名映射到实体类中的属性名
type:实体类中属性的类型 column:数据库表的列段名
property标签
name:数据库表的列段名 映射到实体类中的属性名
type:实体类中属性的类型
column:数据库表的列段名
<?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="com.wr.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>
6、 实体映射文件一定要加到核心配置文件
在hibernate.cfg.xml里面的 “session-factory“ 标签下添加下面这一段代码
<!-- 3. 添加实体映射文件 -->
<mapping resource="com/wr/one/entity/User.hbm.xml" />
3.hibernate的增删改查
步骤:
1.对hibernate.cfg.xml这个核心的配置文件进行建模
2.建模后的对象去获取sessionfactory对像,sessionfactory对象中包含数据相关信息
3.通过sessionfactory对象去获取session会话
4.session开启事务(查询中不需要)
5.操作数据库
6.提交事务(查询中不需要)
7.释放资源
查 QueryDemo
package com.wr.one.Test;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
/**
* hibernate查询
*
* @author Administrator
*
*/
public class QueryDemo {
public static void main(String[] args) {
// 对hibernate.cfg.xml进行建模
Configuration configure = new Configuration().configure("/hibernate.cfg.xml");
// 建模后的对象去获取sessionfactory对像,sessionfactory对象中包含数据相关信息
SessionFactory sessionFactory = configure.buildSessionFactory();
// 通过sessionfactory对象去获取session会话
Session session = sessionFactory.openSession();
// 操作数据库
List list = session.createQuery("from User").list(); //查询所有
for (Object object : list) { // 遍历集合
System.out.println(object);
}
// 释放资源
session.close();
}
}
增 AddDemo
package com.wr.one.Test;
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.wr.one.entity.User;
/**
* herinate的添加
* @author Administrator
*
*/
public class AddDemo {
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("zs", "1234", "张三", "男", new Date(System.currentTimeMillis()),
new Timestamp(System.currentTimeMillis()), "haha");
session.save(u);
transaction.commit();
session.close();
}
}
删 delDemo
package com.wr.one.Test;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import com.wr.one.entity.User;
public class DelDemo {
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 user=new User();
user.setId(15);
session.delete(user);
transaction.commit();
session.close();
}
}
改 EditDemo
package com.wr.one.Test;
import java.sql.Date;
import java.sql.Timestamp;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import com.wr.one.entity.User;
/**
*hibernate的修改
* @author Administrator
*
*/
public class EditDemo {
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("ww", "123456", "张三", "男", new Date(System.currentTimeMillis()),
// new Timestamp(System.currentTimeMillis()), "haha");
// u.setId(15);
// session.update(u);
// ②
// 先通过编号查询到这个人
User u=session.get(User.class,15);
// 再给属性重新赋值
u.setRealname("老刘");
transaction.commit();
session.close();
}
}
执行的sql语句 都显示在控制台上
具体结果 结合数据库来看