导读

1.HQL查询
2.Hibernate命名查询,对原生SQL的支持,Criteria(了解)
3.集合属性
4.一对多,多对一及多对多关系
5.乐观锁与悲观锁
6.缓存:提高效率
7.Hibernate注解使用

HQL查询

工程结构

Book.java,
Book.hbm.xml,
HBUtil.java,
hibername.cfg.xml与基本查询一致

HQLTest.java

package com.hala.test;import java.util.List;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.dao.BookDao;
import com.hala.entity.Book;
import com.hala.util.HBUtil;public class HQLTest {private Session session=null;private Transaction ts=null;private BookDao bd=new BookDao();@BeforeEachpublic void before() {// 1,2步在HBUtil类中封装执行// 3.创建sessionsession = HBUtil.getSession();// 4.开启事务ts=session.beginTransaction();}//   @Testpublic void deleteByPrice() {System.out.println(bd.deleteByPrice(session, 100));}//   @Testpublic void queryNameAndPrice() {List<Object[]> books=bd.queryNameAndPrice(session);for (Object[] obj : books) {System.out.println("书名:"+obj[0]+" 价格:"+obj[1]);}}//   @Testpublic void queryCountByAuthor() {List<Object[]> objs=bd.queryCountByAuthor(session);for (Object[] obj : objs) {System.out.println("作者:"+obj[1]+" 作品数量:"+obj[0]);}}// @Testpublic void queryPage() {List<Book> books=bd.queryPage(session, 1, 2);for (Book book : books) {System.out.println(book);}}//   @Testpublic void addIntroductions() {Book book=(Book)session.get(Book.class,2);book.getIntroductions().add("wonderful!");book.getIntroductions().add("beautiful!!!");book.getIntroductions().add("extraordinary");session.save(book);}@AfterEachpublic void after() {//6.Hibernate不自动提交事务,需要手动ts.commit();//关闭会话session.close();//关闭会话工厂HBUtil.closeFactory();}
}

Book.Dao.java

package com.hala.dao;import java.util.List;import org.hibernate.Session;
import org.hibernate.query.Query;import com.hala.entity.Book;public class BookDao {/*** 根据价格删除数据* @param session price* @return*/public int deleteByPrice(Session session,double price) {String hql="delete from Book where price>= ?1";Query query=session.createQuery(hql);//占位符下标从0开始query.setParameter(1, price);return query.executeUpdate();}/*** 根据名字更改价格* @param session* @param name* @param price* @return*/public int updateByname(Session session,String name,double price) {String hql="update Book set price= :price where author= :author";Query query=session.createQuery(hql);query.setParameter("price", price);query.setParameter("author", name);return query.executeUpdate();}/*** 查询所有(结果是一个集合)* @param session* @return*/public List<Book> queryAll(Session session){String hql="from Book";//相当于select * from book;Query query=session.createQuery(hql);return query.list();//可以执行查询语句,并将查询结果封装到list中}/*** 根据id查询(结果只有一个)* @param session* @param id* @return*/public Book queryById(Session session,int id) {String hql="from Book where id= :id";Query query=session.createQuery(hql).setParameter("id",id);return (Book)query.uniqueResult();//当查询结果只有单行时使用}/*** 统计Book表里记录个数* @param session* @return*/public long queryCount(Session session){String hql="select count(1) from Book";return (long)session.createQuery(hql).uniqueResult();}/*** 只查询名称和价格* @param session* @return*/public List<Object[]> queryNameAndPrice(Session session){//利用二维数组的思维String hql="select name,price from Book";return session.createQuery(hql).list();}/*** 查询每个作者作品数量(分组查询)* @param session* @return*/public List<Object[]> queryCountByAuthor(Session session){String hql="select count(1),author from Book group by author";return session.createQuery(hql).list();}/*** 分页查询* 每当我们点击一页时,只查询这一页的数据* hhibernate的分页方法对所有数据库都适用* @param session* @param currentPage :当前页数* @param pageSize :每页显示多少条* @return*/public List<Book> queryPage(Session session,int currentPage,int pageSize){String hql="from Book";List<Book> list=session.createQuery(hql).setFirstResult((currentPage-1)*pageSize)//设置从第几条开始查,从0开始.setMaxResults(pageSize)//设置本次查询最多条数.list();return list;}}

Hibernate命名查询,对原生SQL的支持,Criteria(了解)

集合属性

一对多,多对一及多对多关系

一对多,多对一

一个部门有多个员工

一个部门有一个父部门,多个子部门(自身关联)


多对多关系

一个课程有多个学生选择,一个学生可以学多门课程


乐观锁与悲观锁

在hibernate配置文件中设置隔离级别

乐观锁

在数据库表中提供一个版本号的字段,每次提交数据时,hibernate会比对用户的versionno和数据库的versionno是否一致,如果一致,则允许提交,如果不一致,则阻止提交,每次提交之后,versionno会自动加1

隔离级别2+乐观锁≈隔离级别4

悲观锁

悲观锁很少被使用,他是一种独占的方法

基本原理:使用数据库的独占锁:select ....for update;

缓存:提高效率

1.缓存可以减少内存跟服务器的交互次数,从而提高程序效率
2.一级缓存:session,自动开启
3.Hibernate中对象的状态:
①临时状态: 使用new 关键字创建一个对象时,这个对象处于临时状态
②持久状态: 数据已经持久化,并且保存在session中
③游离状态: 数据已经持久化,但是不在session中
④删除状态: 调用delete方法,并且提交事务
4.二级缓存
针对需要频繁访问,且不会经常修改的数据,一般会将它们加入到二级缓存

在hibernate中使用二级缓存


上图是使用hibernate自带的,这种并不常用,常用的是下边使用第三方的,
第一步:将下图三个jar包导入工程

第二步:在hibernate.cfg.xml配置文件中配置

第三步:在官方下载的压缩包里搜索ehcache.xml文件,将其导入到工程src包下
可以指定自己的缓存区,如下KeyBoard缓存区

<!--~ 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>.-->
<ehcache><!-- Sets the path to the directory where cache .data files are created.If the path is a Java System Property it is replaced byits value in the running VM.The following properties are translated:user.home - User's home directoryuser.dir - User's current working directoryjava.io.tmpdir - Default temp file path --><diskStore path="./target/tmp"/><!--当缓存在内存中过多时,转存到磁盘中的位置--><!--Default Cache configuration. These will applied to caches programmatically created throughthe CacheManager.The following attributes are required for defaultCache:maxInMemory       - Sets the maximum number of objects that will be created in memoryeternal           - Sets whether elements are eternal. If eternal,  timeouts are ignored and the elementis never expired.timeToIdleSeconds - Sets the time to idle for an element before it expires. Is only usedif the element is not eternal. Idle time is now - last accessed timetimeToLiveSeconds - Sets the time to live for an element before it expires. Is only usedif the element is not eternal. TTL is now - creation timeoverflowToDisk    - Sets whether elements can overflow to disk when the in-memory cachehas reached the maxInMemory limit.--><!-- maxElementsInMemory:在内存中存放的最大对象数量eternal:缓存数据是否持久保存timeToIdleSeconds:eternal是false的情况下,允许对象最大处于空闲状态的时间,单位是秒,超过这个时间则被销毁timeToLiveSeconds:eternal是false的情况下,允许对象在缓存中最大存放时间,单位是秒,超过则销毁overflowToDisk:当内存满时,是否将缓存保存到磁盘--><!-- 默认缓存区 --><defaultCachemaxElementsInMemory="10000"eternal="false"timeToIdleSeconds="120"timeToLiveSeconds="120"overflowToDisk="true"/><!--Predefined caches.  Add your cache configuration settings here.If you do not have a configuration for your cache a WARNING will be issued when theCacheManager startsThe following attributes are required for defaultCache:name              - Sets the name of the cache. This is used to identify the cache. It must be unique.maxInMemory       - Sets the maximum number of objects that will be created in memoryeternal           - Sets whether elements are eternal. If eternal,  timeouts are ignored and the elementis never expired.timeToIdleSeconds - Sets the time to idle for an element before it expires. Is only usedif the element is not eternal. Idle time is now - last accessed timetimeToLiveSeconds - Sets the time to live for an element before it expires. Is only usedif the element is not eternal. TTL is now - creation timeoverflowToDisk    - Sets whether elements can overflow to disk when the in-memory cachehas reached the maxInMemory limit.--><!-- Sample cache named sampleCache1This cache contains a maximum in memory of 10000 elements, and will expirean element if it is idle for more than 5 minutes and lives for more than10 minutes.If there are more than 10000 elements it will overflow to thedisk cache, which in this configuration will go to wherever java.io.tmp isdefined on your system. On a standard Linux system this will be /tmp"--><!-- 指定缓存区,将name指定的内容存到缓存区 --><cache name="keyBoard"maxElementsInMemory="10000"eternal="false"timeToIdleSeconds="300"timeToLiveSeconds="600"overflowToDisk="true"/><!-- Sample cache named sampleCache2This cache contains 1000 elements. Elements will always be held in memory.They are not expired. --><cache name="sampleCache2"maxElementsInMemory="1000"eternal="true"timeToIdleSeconds="0"timeToLiveSeconds="0"overflowToDisk="false"/> --><!-- Place configuration for your caches following --></ehcache>

第四步:配置映射文件KeyBoard.hbm.xml文件

Hibernate注解使用

工程目录

注意导入的包是javax,不是hibernate
Person.java

package com.hala.entity;import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;@Entity
@Table(name="t_person")//指定表名,不加的话默认与实体类类名一致
public class Person {@Id@GeneratedValue(strategy=GenerationType.AUTO)//id自增长@Column(name="person_id")//可以自定义在数据库中字段的名字private int id;@Basic//表示普通字段,可以省略private String name;@Basicprivate int age;@Basicprivate String gender;@Transient//表示忽略该属性,不会在表中建字段private int abc;public Person() {super();}public Person(String name, int age, String gender) {super();this.name = name;this.age = age;this.gender = gender;}public Person(int id, String name, int age, String gender) {super();this.id = id;this.name = name;this.age = age;this.gender = gender;}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 int getAge() {return age;}public void setAge(int age) {this.age = age;}public String getGender() {return gender;}public void setGender(String gender) {this.gender = gender;}@Overridepublic String toString() {return "Person [id=" + id + ", name=" + name + ", age=" + age + ", gender=" + gender + "]";}}

配置文件

PersonTest.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.Person;
import com.hala.util.HBUtil;public class PersonTest {private Session session=null;private Transaction ts=null;@BeforeEachpublic void before() {// 1,2步在HBUtil类中封装执行// 3.创建sessionsession = HBUtil.getSession();// 4.开启事务ts=session.beginTransaction();}@Testpublic void add() {Person person=new Person("hala",13,"male");session.save(person);}@AfterEachpublic void after() {//6.Hibernate不自动提交事务,需要手动ts.commit();//关闭会话session.close();//关闭会话工厂HBUtil.closeFactory();}}

注解一对多,多对一,多对多关系

多对多建议拆封为两个一对多,中间表另建实体类

这里有一个问题,两个表主键用的是同一个序列,下边是修改方法

Java 39---Hibernate框架(2)相关推荐

  1. (转)Hibernate框架基础——Java对象持久化概述

    http://blog.csdn.net/yerenyuan_pku/article/details/52732990 Java对象持久化概述 应用程序的分层体系结构 基于B/S的典型三层架构   说 ...

  2. Java web 三大框架异常学习总结

    struts2.1.8+hibernate2.5.6+spring3.0(ssh2三大框架)常见异常原因和解决方案 http://www.cnblogs.com/lanxuezaipiao/p/361 ...

  3. java常用日志框架日志门面及实现 SLF4J 、Jboss-logging 、JCL、Log4j、Logback、Log4j2、JUL,springboot集成 log4j、log4j2

    java常用日志框架日志门面SLF4J .Jboss-logging .JCL.Log4j及实现 Logback.Log4j2.JUL,springboot集成 log4j.log4j2 .logba ...

  4. Hibernate框架第二天

    ### Hibernate的持久化类 ### ---------- **什么是持久化类** 1. 持久化类:就是一个Java类(咱们编写的JavaBean),这个Java类与表建立了映射关系就可以成为 ...

  5. Java三大主流框架概述

    Struts.Hibernate和Spring是我们Java开发中的常用关键,他们分别针对不同的应用场景给出最合适的解决方案.但你是否知道,这些知名框架最初是怎样产生的? 我们知道,传统的Java W ...

  6. java ee核心框架实战 pdf_Java EE核心框架实战 高洪岩 中文PDF

    资源名称:Java EE核心框架实战 高洪岩 中文PDF 第1章 MyBatis 3操作数据库 第2章 MyBatis 3常用技能 第3章 Struts 2必备开发技能 第4章 Struts 2文件的 ...

  7. Java三大主流框架概述--(转载)

    Struts.Hibernate和Spring是我们Java开发中的常用关键,他们分别针对不同的应用场景给出最合适的解决方案.但你是否知道,这些知名框架最初是怎样产生的? 我们知道,传统的Java W ...

  8. java mysql框架_盘点 Java 数据库访问框架——究竟哪个更适合你

    本文将带您浏览和比较最受欢迎Java数据库访问框架(DAO层).假设您正在开发一个Java程序,有许多办法可以让您的应用连上数据库.下面会列举各数据库访问框架的适用场景,相信能够帮您选到适合项目的开发 ...

  9. 5个强大的Java分布式缓存框架推荐

    2019独角兽企业重金招聘Python工程师标准>>> 在开发中大型Java软件项目时,很多Java架构师都会遇到数据库读写瓶颈,如果你在系统架构时并没有将缓存策略考虑进去,或者并没 ...

  10. SSH框架第一天——hibernate框架

    什么是框架? 是软件的半成品,它已经完成了部分功能. 什么是hibernate? hibernate是一个开放源代码的对象关系映射(ORM)框架,它对JDBC进行了非常轻量级的对象封装,使得Java程 ...

最新文章

  1. Exchange Server 2016管理系列课件53.DAG管理之设置滞后数据库副本
  2. C语言能否写windows应用程序,C语言能写windows的窗口吗?
  3. ACM的fflush(stdin)的问题
  4. Feature Preprocessing on Kaggle
  5. 【C】@程序员,我们送给你一个成熟的Excel导入导出组件
  6. 私房钱就藏在老婆眼皮底下
  7. python作中国地图背景气泡图_exce表格中怎么制作中国地图背景数据气泡图
  8. 什么是云存储技术与云存储服务?
  9. Java编译出现不可映射字符
  10. 计算机函数两个表格找相同,wps筛选出两个表格中的重复项(countif 函数简单使用)【已解决】...
  11. ubuntu搜狗输入法切换快捷键fcitx设置
  12. GBASE 8s 用户标示与鉴别
  13. hadoop 8088端口网页无法打开
  14. OpenGL学习笔记九——光照3(实现三种光照类型:平行光,点光源,聚光灯)
  15. Win10任务栏假死问题解决方案
  16. requireJS,rjs,gulp简易实现
  17. 电脑可安装的超炫实用软件
  18. 你的项目该不该写单元测试?
  19. Python3网络爬虫--爬取有声小说(附源码)
  20. David想对asc码进行位运算

热门文章

  1. nagios 的安装
  2. 网络安全——文件上传
  3. 工作岗位必备技能总结
  4. SPH算法的理论和实践(2)
  5. 杀狗问题(帽子问题)
  6. y=asin(wx+φ)的对称中心_函数y=Asin(wx+φ)图像和性质
  7. algorithm用法
  8. 访问到页面的完整流程
  9. 【HTML5】调查问卷制作简约版
  10. php如何实现会员推荐奖励,分享微信公众号实现会员卡领取的功能