hibernate 和 jpa简介

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 固定死的位置不能变)


<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">
          
           <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"/>
              
              <property name="hibernate.show_sql" value="true"/>
              <property name="hibernate.format_sql" value="true"/>
              
              <property name="hibernate.hbm2ddl.auto" value="update"/>
              
              <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;

/**
* 

Title: Customer

*

Description: 客户的实体类

* @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; } @Override public 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 {
	
	@Test
	public 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 {
	
	//增
	@Test
	public 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();
	}
	
	//查
	@Test
	public 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();
	}
	
	//改
	@Test
	public 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();
	}
	
	//删
	@Test
	public 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();
		}
	
	//查询全部
	@Test
	public void findAllTest() {
		EntityManager em = EntityManagerUtil.createEntityManager();
		EntityTransaction tx = em.getTransaction();
		tx.begin();
		//查询find方法
		Query query = em.createQuery("from Customer");// JPQL java persistence query language
		List<Customer> resultList = query.getResultList();
		for (Customer customer : resultList) {
			System.out.println(customer);
		}
		tx.commit();
		em.close();
	}
	
	//聚合函数
	@Test
	public 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 language
		List<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 练习

配置文件



<hibernate-configuration>
   
    <session-factory>
        
	     <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driverproperty>
	     <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/testproperty>
	     <property name="hibernate.connection.username">rootproperty>
	     <property name="hibernate.connection.password">adminproperty>
	     <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialectproperty>
        
	     <property name="hibernate.show_sql">trueproperty>
	     <property name="hibernate.format_sql">trueproperty>
	     <property name="hibernate.hbm2ddl.auto">updateproperty>
	     <property name="hibernate.connection.provider_class">org.hibernate.connection.C3P0ConnectionProviderproperty>
        
        <mapping class="com.itheima.domain.Customer"/>
    session-factory>
hibernate-configuration>	

抽取工具类

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

/**
* 

Title: HibernateUtil

*

Description: Hibernate的工具类

* @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;



/**
* 

Title: JpaTest

*

Description:Hibernate的crud操作

* @author zhaocq * @date 2018年9月18日 */
public class HibernateCRUDTest { /** *

Title: test

*

Description: 保存

*/
@Test public void test(){ Customer c = new Customer(); c.setCustName("hello Hibernate"); // 获取Session Session session = HibernateUtil.createSession(); Transaction tx = session.beginTransaction(); // 执行保存操作 session.save(c); // 提交事务 tx.commit(); // 关闭相关资源 session.close(); } /** *

Title: test1

*

Description: 根据ID查询

*/
@Test public void test1(){ // 获取Session Session session = HibernateUtil.createSession(); Transaction tx = session.beginTransaction(); // 执行保存操作 Customer c = session.get(Customer.class, 1); System.out.println(c); // 提交事务 tx.commit(); // 关闭相关资源 session.close(); } /** *

Title: test2

*

Description:更新

*/
@Test public void test2(){ // 获取Session Session session = HibernateUtil.createSession(); Transaction tx = session.beginTransaction(); // 执行保存操作 Customer c = session.get(Customer.class, 1); c.setCustName("javaee520"); session.update(c); // 提交事务 tx.commit(); // 关闭相关资源 session.close(); } /** *

Title: test3

*

Description: 删除

*/
@Test public void test3(){ Customer c = new Customer(); c.setCustId(2); // 获取Session Session session = HibernateUtil.createSession(); Transaction tx = session.beginTransaction(); // 执行保存操作 //Customer c = session.get(Customer.class, 1); session.delete(c); // 提交事务 tx.commit(); // 关闭相关资源 session.close(); } /** *

Title: test4

*

Description: 查询全部

*/
@Test public void test4(){ // 获取Session Session session = HibernateUtil.createSession(); Transaction tx = session.beginTransaction(); // 创建Query Query query = session.createQuery("from Customer");// HQL hibernate query language List<Customer> list = query.list(); for(Customer l:list){ System.out.println(l); } // 提交事务 tx.commit(); // 关闭相关资源 session.close(); } /** *

Title: test5

*

Description: 聚合函数的使用

*/
@Test public void test5(){ // 获取Session Session session = HibernateUtil.createSession(); Transaction tx = session.beginTransaction(); // 创建Query Query query = session.createQuery("select count(custId) from Customer");// JPQL java persistence query language Object uniqueResult = query.uniqueResult(); System.out.println(uniqueResult); // 提交事务 tx.commit(); // 关闭相关资源 session.close(); } }

你可能感兴趣的:(hibernate 和 jpa简介)