导读
1.简介及搭建
2.Hibernate基本操作(增删改查)并封装
简介及搭建
1.Hibernate是一个轻量级持久层(DAO层)ORM框架
2.ORM:Object-Relationship-Mapping:对象关系映射
第一步:
官网下载jar包
http://hibernate.org/orm/releases/
下载最新的稳定版
第二步:
如何在自己的工程中创建lib包来存放jar包?
右键工程如图,文件名字取为lib即可
解压下载好的hibernate压缩包,在如下目录中,将required中的jar包全部导入到上边建好的lib文件夹中,并buildPath
然后要导入相应的jdbc驱动jar包
第三步:
在下载好的文件夹下搜索hibernate.cfg.xml,他是Hibernate的配置文件,将其复制到工程中自己建好的src包下,然后搜索xxx.hbm.xml,他是Hibernate映射文件,xxx是从hibernate.cfg.xml文件中<mapping resource="..."/>
…中获得的,但这两个文件都只是一个模版,都要根据自己的需求修改
如下工程结构:
配置文件参考
hibernate.cfg.xml配置文件
<?xml version='1.0' encoding='utf-8'?>
<!--
~ Hibernate, Relational Persistence for Idiomatic Java
~
~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
-->
<!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>
<!-- 配置数据库方言 MySQL5.0之后要这样写 -->
<!-- MySQL5.0之前的写法 <property name="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</property> -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
<!-- 配置数据库链接4要素-->
<!-- 这里的配置参数其实和使用C3P0链接池配置的参数是一样的,可以参考那个 -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- 端口号忘记了可以在数据库链接那边查看 -->
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/message</property>
<property name="hibernate.connection.username">hala</property>
<property name="hibernate.connection.password">hala</property>
<!-- 映射文件的路径 -->
<mapping resource="com/hala/entity/Book.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Book.hbm.xml映射文件
<?xml version="1.0"?>
<!--
~ Hibernate, Relational Persistence for Idiomatic Java
~
~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
-->
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="org.hibernate.tutorial.hbm">
<!-- 这里name是与实体类做关联,而table是与表做关联,如果不写table默认实体类的名字就是表的名字 -->
<class name="com.hala.entity.Book" table="book">
<!-- id标签是指表的主键,在这里是指Book中的id,name指实体类中的属性名,column指表中的字段名-->
<id name="id" column="id" type="int">
<generator class="increment"/><!-- generator指主键生成策略 assigned指自定义 increment指自动增长-->
</id>
<!-- property指除了主键外的其他属性 -->
<property name="name"/><!-- column可以不写,不写默认为和name值相同 -->
<property name="price"/>
<property name="author"/>
</class>
</hibernate-mapping>
实体类
package com.hala.entity;
public class Book {
private int id;
private String name;
private double price;
private String author;
public Book() {
super();
}
public Book(String name, double price, String author) {
super();
this.name = name;
this.price = price;
this.author = author;
}
public Book(int id, String name, double price, String author) {
super();
this.id = id;
this.name = name;
this.price = price;
this.author = author;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
@Override
public String toString() {
return "Book [id=" + id + ", name=" + name + ", price=" + price + ", author=" + author + "]";
}
}
CreateTable.java
package com.hala.test;
import java.util.EnumSet;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.hibernate.tool.schema.TargetType;
public class CreateTable {
public static void main(String[] args) {
//这段代码的作用是在制定数据库里边建表
//这是Hibernate5.2以上版本的写法
ServiceRegistry sr =new StandardServiceRegistryBuilder().configure().build();
Metadata md =new MetadataSources(sr).buildMetadata();
SchemaExport se = new SchemaExport();
se.create(EnumSet.of(TargetType.DATABASE),md);
}
}
以上就完成了一次hibernate项目搭建
Hibernate基本操作(增删改查)并封装
工程目录
Book.java
package com.hala.entity;
public class Book {
private int id;
private String name;
private double price;
private String author;
public Book() {
super();
}
public Book(String name, double price, String author) {
super();
this.name = name;
this.price = price;
this.author = author;
}
public Book(int id, String name, double price, String author) {
super();
this.id = id;
this.name = name;
this.price = price;
this.author = author;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
@Override
public String toString() {
return "Book [id=" + id + ", name=" + name + ", price=" + price + ", author=" + author + "]";
}
}
Book.hbm.xml
<?xml version="1.0"?>
<!--
~ Hibernate, Relational Persistence for Idiomatic Java
~
~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
-->
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping ><!-- 属性default-lazy="false" 表示关闭懒加载-->
<!-- 这里name是与实体类做关联,而table是与表做关联,如果不写table默认实体类的名字就是表的名字 -->
<class name="com.hala.entity.Book" table="book">
<!-- id标签是指表的主键,在这里是指Book中的id,name指实体类中的属性名,column指表中的字段名-->
<id name="id" column="id" type="int">
<generator class="increment"/><!-- generator指主键生成策略 assigned指自定义 increment指自动增长-->
</id>
<!-- property指除了主键外的其他属性 -->
<property name="name"/><!-- column可以不写,不写默认为和name值相同 -->
<property name="price"/>
<property name="author"/>
</class>
</hibernate-mapping>
hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!--
~ Hibernate, Relational Persistence for Idiomatic Java
~
~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
-->
<!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>
<!-- 配置数据库方言 MySQL5.0之后要这样写 -->
<!-- MySQL5.0之前的写法 <property name="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</property> -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
<!-- 配置数据库链接4要素-->
<!-- 这里的配置参数其实和使用C3P0链接池配置的参数是一样的,可以参考那个 -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- 端口号忘记了可以在数据库链接那边查看 -->
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/message</property>
<property name="hibernate.connection.username">hala</property>
<property name="hibernate.connection.password">hala</property>
<!-- 这个语句可以自动建表 -->
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- 映射文件的路径 -->
<mapping resource="com/hala/entity/Book.hbm.xml"/>
</session-factory>
</hibernate-configuration>
HBUtil.java
package com.hala.util;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.service.ServiceRegistry;
public class HBUtil {
private static SessionFactory factory=null;
private static Session session=null;
//封装技巧,如果只需要加载一次,则放在静态代码块中,如果需要反复加载,就放在方法中
static {
// 在Hibernate中操作数据库不是使用Statement而是使用session
//这是Hibernate5.0版本以后的写法
//1.创建服务注册对象
ServiceRegistry serviceRegistry =new StandardServiceRegistryBuilder()
.configure().build();
//2.创建会话工厂对象
factory = new MetadataSources(serviceRegistry).
buildMetadata().buildSessionFactory();
}
public static Session getSession() {
return factory.openSession();
}
public static void closeFactory() {
factory.close();
}
}
BookTest.java
package com.hala.test;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import com.hala.entity.Book;
import com.hala.util.HBUtil;
public class BookTest {
private Session session=null;
private Transaction ts=null;
//BeforeEach注解的作用是这个方法会自动在@Test之前运行
@BeforeEach
public void before() {
// 1,2步在HBUtil类中封装执行
// 3.创建session
session = HBUtil.getSession();
// 4.开启事务
ts=session.beginTransaction();
}
//Hibernate针对对象操作,且只能通过主键id删改查
//5.添加数据
@Test
public void add() {
Book book=new Book("Game of Thrones",100.3,"J.J.Martain");
session.save(book);
}
// 5.修改数据
@Test
public void update() {
// 先查再改,避免影响其他数据
Book book = (Book) session.get(Book.class, 2);
book.setPrice(88.0);
session.update(book);
}
//5.添加或修改数据
@Test
public void saveOrUpdate() {
//含有主键id就修改,不含主键id就添加
Book book1=new Book("Sherlock",29.7,"Conan");
Book book2=new Book(4,"Holmes",30.5,"Vonan");
session.saveOrUpdate(book1);
session.saveOrUpdate(book2);
}
//5.删除数据
@Test
public void delete() {
Book book=new Book();
book.setId(1);
session.delete(book);
}
//5.查询数据(立即加载)
@Test
public void query() {
Book book=(Book)session.get(Book.class, 2);
System.out.println(book);
}
//5.查询数据(懒加载,需要使用时才去加载)
@Test
public void load() {
Book book=(Book)session.load(Book.class, 2);
System.out.println(book);
}
//AfterEach注解的作用是这个方法会自动在@Test之后运行
@AfterEach
public void after() {
//6.Hibernate不自动提交事务,需要手动
ts.commit();
//关闭会话
session.close();
//关闭会话工厂
HBUtil.closeFactory();
}
}