hibernate 和 jpa简介

  • 小引
  • 什么是ORM思想?
  • Hibernate概述
  • JPA概述
  • hibernate 和 jpa的关系
  • jpa的常用对象
  • JPA中的主键生成策略
  • JPA的入门案例
    • 配置文件(src下META-INF下persistence.xml 固定死的位置不能变)
    • 实体类
    • 测试Demo(DDL建表)
  • JPA的CRUD
    • 抽取工具类
    • 增删改查方法
  • JPA中的两种查询方式
  • Hibernate 的CRUD 练习
    • 配置文件
    • 抽取工具类
    • CURD

小引

长时间以来,人们解决持久层的方案,无论是jdbc、dbutils还是mybatis、jdbcTemplate,都无法跳出对SQL的高度关注,也就是说,大家始终要花费大量的时间去写简单的CRUD代码。因此,人们设想能不能通过某种方法,让我们不用再编写简单的CRUD语句而是直接建立某种对应关系实现表的操作,因此hibernate框架诞生了。

什么是ORM思想?

ORM(Object-Relational Mapping)
Object:java对象
Relational:关系型数据库
Mapping:映射(对应关系的映射)
ORM:通过操作实体类就能直接操作数据库,依据的是对应关系的建立

Hibernate概述

它是一个 开源的,轻量级的,基于ORM思想的企业级应用框架。通过实体类自动生成sql语句,实现程序员经过sql而操作数据库的可能。

JPA概述

JPA及java持久化API,是sun公司基于ORM思想提供的一套规范

hibernate 和 jpa的关系

jpa是一套接口和规范,hibernate是它其中一种的实现。

jpa的常用对象

Persistence
JPA的核心对象 主要负责创建 EntityManagerFactory

EntityManagerFactory
类似于SqlSessionFactory SqlSession IOC原理:工厂 + 反射 + 配置
此处使用工厂模式,一劳永逸 降低耦合

EntityManager
它是JPA中的持久化对象 封装所有的持久化方法,以及EntityTransaction

EntityTransaction
事务对象,目的是同化不同事物类型的差异,简便开发

JPA中的主键生成策略

IDENTITY
适用于数据库支持列的自增长情况 mysql db2(ibm)
SEQUENCE
适用于数据库支持序列的情况 Oracle db2
TABLE
用额外的一张表来维护你的主键
AUTO
默认就是Auto 默认使用Table

不完美:jpa提供的 主键生成策略 只限于 数值型

JPA的入门案例

配置文件(src下META-INF下persistence.xml 固定死的位置不能变)

<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xsi:schemaLocation="http://java.sun.com/xml/ns/persistence  http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"  version="2.0">  <!-- 持久化单元块 --><persistence-unit name="myJpa" transaction-type="RESOURCE_LOCAL"><!-- 数据库连接信息 使用hibernate提供的 在hibernate的源码包下project/etc/hibernate.properties--><properties><!-- 必须配置 --><property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/><property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/test"/><property name="hibernate.connection.username" value="root"/><property name="hibernate.connection.password" value="root"/><property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/><!-- 方言:数据库提供商对SQL的扩展 --><!-- 可选配置 --><property name="hibernate.show_sql" value="true"/><property name="hibernate.format_sql" value="true"/><!-- DDL语句生成策略update的含义:当程序运行会自动检测实体类和数据库的表结构是否有差异,一旦有会立即更新表结构使用场景:适合:开发阶段 不适合:线上阶段--><property name="hibernate.hbm2ddl.auto" value="update"/><!-- c3p0连接池信息 --><property name="hibernate.connection.provider_class" value="org.hibernate.connection.C3P0ConnectionProvider"/></properties></persistence-unit></persistence>

实体类


package com.itheima.domain;import java.io.Serializable;import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;/**
* <p>Title: Customer</p>
* <p>Description: 客户的实体类</p>
* @author zhaocq
* @date 2018年9月18日*/
@Entity
@Table(name="cst_customer")
public class Customer implements Serializable {@Id@Column(name="cust_id")@GeneratedValue(strategy=GenerationType.IDENTITY)private Integer custId;@Column(name="cust_name")private String  custName; @Column(name="cust_source")private String  custSource;@Column(name="cust_industry")private String  custIndustry;@Column(name="cust_level")private String custLevel;@Column(name="cust_address")private String  custAddress;@Column(name="cust_phone")private String  custPhone;public Integer getCustId() {return custId;}public void setCustId(Integer custId) {this.custId = custId;}public String getCustName() {return custName;}public void setCustName(String custName) {this.custName = custName;}public String getCustSource() {return custSource;}public void setCustSource(String custSource) {this.custSource = custSource;}public String getCustIndustry() {return custIndustry;}public void setCustIndustry(String custIndustry) {this.custIndustry = custIndustry;}public String getCustLevel() {return custLevel;}public void setCustLevel(String custLevel) {this.custLevel = custLevel;}public String getCustAddress() {return custAddress;}public void setCustAddress(String custAddress) {this.custAddress = custAddress;}public String getCustPhone() {return custPhone;}public void setCustPhone(String custPhone) {this.custPhone = custPhone;}@Overridepublic String toString() {return "Customer [custId=" + custId + ", custName=" + custName + ", custSource=" + custSource+ ", custIndustry=" + custIndustry + ", custLevel=" + custLevel + ", custAddress=" + custAddress+ ", custPhone=" + custPhone + "]";}
}

测试Demo(DDL建表)

package com.itheima.test;import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;import org.junit.Test;import domain.Customer;public class JpaTest {@Testpublic void test() {//创建entityManagerFactory工厂EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("myJpa");//获得EntityManager对象EntityManager em = entityManagerFactory.createEntityManager();//获取事物对象EntityTransaction tx = em.getTransaction();//开启事物tx.begin();Customer customer = new Customer();customer.setCustName("hello jpa");//保存操作em.persist(customer);//提交事物tx.commit();//关闭资源em.close();entityManagerFactory.close();}
}

JPA的CRUD

抽取工具类

package utils;import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;public class EntityManagerUtil {private static EntityManagerFactory entityManagerFactory;static {entityManagerFactory=Persistence.createEntityManagerFactory("myJpa");}public EntityManager createEntityManager() {return entityManagerFactory.createEntityManager();}
}

增删改查方法

package com.itheima.test;import java.util.List;import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;import org.junit.Test;import domain.Customer;
import utils.EntityManagerUtil;public class JpaCRUDTest {//增@Testpublic void addTest() {Customer customer = new Customer();customer.setCustName("hello jpa3");customer.setCustPhone("110");EntityManager em = EntityManagerUtil.createEntityManager();EntityTransaction tx = em.getTransaction();tx.begin();//增加persist方法em.persist(customer);tx.commit();em.close();}//查@Testpublic void findTest() {EntityManager em = EntityManagerUtil.createEntityManager();EntityTransaction tx = em.getTransaction();tx.begin();//查询find方法Customer c = em.find(Customer.class, 1);System.out.println(c);tx.commit();em.close();}//改@Testpublic void updateTest() {EntityManager em = EntityManagerUtil.createEntityManager();EntityTransaction tx = em.getTransaction();tx.begin();//先查询Customer c = em.find(Customer.class, 1);//在用merge修改c.setCustName("改名字了");em.merge(c);System.out.println(c);tx.commit();em.close();}//删@Testpublic void delTest() {EntityManager em = EntityManagerUtil.createEntityManager();EntityTransaction tx = em.getTransaction();tx.begin();//先查询Customer c = em.find(Customer.class, 1);//在用remove删除em.remove(c);tx.commit();em.close();}//查询全部@Testpublic void findAllTest() {EntityManager em = EntityManagerUtil.createEntityManager();EntityTransaction tx = em.getTransaction();tx.begin();//查询find方法Query query = em.createQuery("from Customer");// JPQL java persistence query languageList<Customer> resultList = query.getResultList();for (Customer customer : resultList) {System.out.println(customer);}tx.commit();em.close();}//聚合函数@Testpublic void test() {EntityManager em = EntityManagerUtil.createEntityManager();EntityTransaction tx = em.getTransaction();tx.begin();//查询find方法Query query = em.createQuery("select count(custId) from Customer");// JPQL java persistence query languageList<Customer> resultList = query.getResultList();System.out.println(resultList.get(0));tx.commit();em.close();}
}

JPA中的两种查询方式

Find和 getReference 的区别:
1. 加载时机不一样,find是立即加载,getReference是
延迟加载。
2. 返回的对象不一样,find返回的就是实体对象,
getReference返回的是代理对象。

Hibernate 的CRUD 练习

配置文件

<?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><!-- 必须配置 --><property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property><property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property><property name="hibernate.connection.username">root</property><property name="hibernate.connection.password">admin</property><property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property><!-- 可选配置 --><property name="hibernate.show_sql">true</property><property name="hibernate.format_sql">true</property><property name="hibernate.hbm2ddl.auto">update</property><property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property><!-- 实体类的位置 --><mapping class="com.itheima.domain.Customer"/></session-factory>
</hibernate-configuration>

抽取工具类

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;/**
* <p>Title: HibernateUtil</p>
* <p>Description: Hibernate的工具类</p>
* @author zhaocq
* @date 2018年9月18日*/
public class HibernateUtil {//   private static EntityManagerFactory factory;private static SessionFactory factory;static{// 创建工厂
//       factory = Persistence.createEntityManagerFactory("myJpa");// 创建Configuration对象Configuration configuration = new Configuration();configuration.configure();factory = configuration.buildSessionFactory();}public static Session createSession(){return factory.openSession();}
}

CURD

package com.itheima.test;import java.util.List;import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;import domain.Customer;
import utils.HibernateUtil;/**
* <p>Title: JpaTest</p>
* <p>Description:Hibernate的crud操作</p>
* @author zhaocq
* @date 2018年9月18日*/
public class HibernateCRUDTest {/*** <p>Title: test</p>  * <p>Description: 保存</p>*/@Testpublic void test(){Customer c = new Customer();c.setCustName("hello Hibernate");// 获取SessionSession session = HibernateUtil.createSession();Transaction tx = session.beginTransaction();// 执行保存操作session.save(c);// 提交事务tx.commit();// 关闭相关资源session.close();}/*** <p>Title: test1</p>  * <p>Description: 根据ID查询</p>*/@Testpublic void test1(){// 获取SessionSession session = HibernateUtil.createSession();Transaction tx = session.beginTransaction();// 执行保存操作Customer c = session.get(Customer.class, 1);System.out.println(c);// 提交事务tx.commit();// 关闭相关资源session.close();}/*** <p>Title: test2</p>  * <p>Description:更新 </p>*/@Testpublic void test2(){// 获取SessionSession session = HibernateUtil.createSession();Transaction tx = session.beginTransaction();// 执行保存操作Customer c = session.get(Customer.class, 1);c.setCustName("javaee520");session.update(c);// 提交事务tx.commit();// 关闭相关资源session.close();}/*** <p>Title: test3</p>  * <p>Description: 删除</p>*/@Testpublic void test3(){Customer c = new Customer();c.setCustId(2);// 获取SessionSession session = HibernateUtil.createSession();Transaction tx = session.beginTransaction();// 执行保存操作//Customer c = session.get(Customer.class, 1);session.delete(c);// 提交事务tx.commit();// 关闭相关资源session.close();}/*** <p>Title: test4</p>  * <p>Description: 查询全部</p>*/@Testpublic void test4(){// 获取SessionSession session = HibernateUtil.createSession();Transaction tx = session.beginTransaction();// 创建Query Query query = session.createQuery("from Customer");// HQL hibernate query languageList<Customer> list = query.list();for(Customer l:list){System.out.println(l);}// 提交事务tx.commit();// 关闭相关资源session.close();}/*** <p>Title: test5</p>  * <p>Description: 聚合函数的使用</p>*/@Testpublic void test5(){// 获取SessionSession session = HibernateUtil.createSession();Transaction tx = session.beginTransaction();// 创建Query Query query = session.createQuery("select count(custId) from Customer");// JPQL java persistence query languageObject uniqueResult = query.uniqueResult();System.out.println(uniqueResult);  // 提交事务tx.commit();// 关闭相关资源session.close();}}

hibernate 和 jpa简介相关推荐

  1. Spring Boot 之Spring data JPA简介

    文章目录 添加依赖 添加entity bean 创建 Dao Spring Data Configuration 测试 Spring Boot 之Spring data JPA简介 JPA的全称是Ja ...

  2. Spring 2 和 JPA 简介

    Spring 2 和 JPA 简介 用 Eclipse 和 DB2 Express-C 研究 Spring 2 框架和 Java 持久性 API 第 1 页,共 16 页 对本教程的评价 帮助我们改进 ...

  3. iBATIS、Hibernate和JPA:哪一款最适合你

    iBATIS.Hibernate和JPA:哪一款最适合你 http://article.yeeyan.org/view/213582/180283 在本文中我们介绍并比较两种最流行的开源持久框架:iB ...

  4. ibernate、EJB3和JPA简介

    Hibernate.EJB3和JPA简介 在用Hibernate开始第一个项目之前,应该考虑EJB3.0标准和它的子规范Java Persistence.让我们回顾历史看看这个新标准是如何产生的. 许 ...

  5. SpringDataJPA 系列之 JPA 简介

    1.1 了解 ORM 1.1.1 概述   对象-关系映射(Object/Relation Mapping,简称 ORM),是随着面向对象的软件开发方法发展而产生的.面向对象的开发方法是当今企业级应用 ...

  6. 数据持久化框架为什么放弃Hibernate、JPA、Mybatis,最终选择JDBCTemplate!

    点击上方"方志朋",选择"设为星标" 回复"666"获取新整理的面试文章 因为项目需要选择数据持久化框架,看了一下主要几个流行的和不流行的框 ...

  7. Hibernate、JPA、Spring Data JPA,傻傻分不清

    国庆假期接近尾声,明天最后一天了,要开始收收心啦- 今天讲讲一个初学者(或许一些老手)可能没去搞懂的几个概念:Hibernate.JPA.Spring Data JPA 之间的关联. 嘿嘿,前段时间有 ...

  8. SpringData Jpa、Hibernate、Jpa 三者之间的关系

    JPA规范与ORM框架之间的关系是怎样的呢? JPA规范本质上就是一种ORM规范,注意不是ORM框架--因为JPA并未提供ORM实现,它只是制订了一些规范,提供了一些编程的API接口,但具体实现则由服 ...

  9. jooq实体 和mysql_几个数据持久化框架Hibernate、JPA、Mybatis、JOOQ的比较

    因为项目需要选择数据持久化框架,看了一下主要几个流行的和不流行的框架,对于复杂业务系统,最终的结论是,JOOQ是总体上最好的,可惜不是完全免费,最终选择JDBC Template. Hibernate ...

最新文章

  1. 代码生成器前戏 之 数据库元数据
  2. CCF CSP201709-1打酱油
  3. React入门看这篇就够了
  4. oracle awr 等待事件,3.db file scattered read等待事件
  5. 一个完整的 Web 请求到底发生了什么
  6. Android零基础入门第20节:CheckBox和RadioButton使用大全
  7. wifi两种工作模式
  8. atitit.javascript js 上传文件的本地预览
  9. Solaris 简单命令
  10. lopatkin俄大神精简中文系统Windows 8.1 Pro 19599 x86-x64 ZH-CN SM
  11. 从SVN上拉取代码到本地进行开发
  12. ruby 安装bundler的方法
  13. 单细胞测序——基本知识
  14. SOM神经网络、LVQ神经网络、CPN神经网络与Python实现
  15. 关于大学生如何进行编码规范的火拼
  16. TestNG - 运行失败的test
  17. 微信公众h5页面如何在pc端调试
  18. Vuex仿饿了么购物车功能
  19. Java的集合有什么?
  20. MomentJs 常用api

热门文章

  1. 联通宽带显示dns服务器黄色,怎么查看联通宽带dns是否被劫持
  2. 中公通信计算机招聘,2021新疆国企考试:电网招聘_复习锦囊计算机类-通信原理...
  3. 打印流PrintStream和配置流Propeties
  4. c语言输入r1 r2垫片的面积,C语言基础入门设计
  5. ubuntu卸载永中office2012青年版
  6. centos6升级OpenSSH
  7. java实现加减乘除以及等式判断
  8. 初识Linux下C语言编程
  9. python快速格式化json
  10. bp神经网络是用来干嘛的,bp神经网络的应用领域