Hibernate、Jpa与Spring data Jpa三者关系与整合

目录

      • 简介
      • Hibernate基础
        • hibernate查询的四种方式
      • Hibernate+JPA
      • Spring + Spring data jpa + hibernate

简介

Hibernate
Hibernate是一个开放源代码的对象关系映射框架,它对JDBC进行了非常轻量级的对象封装,它将POJO与数据库表建立映射关系,是一个全自动的orm框架,hibernate可以自动生成SQL语句,自动执行,使得Java程序员可以随心所欲的使用对象编程思维来操纵数据库。

JPA
JPA全称是Java Persistence API,即java持久化API,是sun公司推出的一套基于ORM的规范,内部由一系列的接口和抽象类构成。
JPA与Hibetnate的关系
JPA和Hibernate的关系就像JDBC和JDBC驱动的关系,JPA是规范,Hibernate除了作为ORM框架之外,它也是一种JPA实现。JPA怎么取代Hibernate呢?JDBC规范可以驱动底层数据库吗?答案是否定的,也就是说,如果使用JPA规范进行数据库操作,底层需要hibernate作为其实现类完成数据持久化工作。

Spring Data jpa
Spring Data JPA 让我们解脱了DAO层的操作,基本上所有CRUD都可以依赖于它来实现,在实际的工作工程中,推荐使用Spring Data JPA + ORM(如:hibernate)完成操作,这样在切换不同的ORM框架时提供了极大的方便,同时也使数据库层操作更加简单,方便解耦

Hibernate、JPA与Spring Data JPA之间的关系
JPA是一套规范,内部是有接口和抽象类组成的。hibernate是一套成熟的ORM框架,而且Hibernate实现了JPA规范,所以也可以称hibernate为JPA的一种实现方式,我们使用JPA的API编程,意味着站在更高的角度上看待问题(面向接口编程)Spring Data JPA是Spring提供的一套对JPA操作更加高级的封装,是在JPA规范下的专门用来进行数据持久化的解决方案。
以上就是对hibernate、JPA与Spring Data JPA三者之间的关系说明。

ORM 表示 Object-Relational Mapping (ORM)对象关系映射

Hibernate基础

maven依赖

<dependencies>
    <dependency>
      <groupId>junitgroupId>
      <artifactId>junitartifactId>
      <version>4.11version>
    dependency>

    <dependency>
      <groupId>org.hibernategroupId>
      <artifactId>hibernate-coreartifactId>
      <version>5.3.5.Finalversion>
    dependency>
    <dependency>
      <groupId>org.hibernategroupId>
      <artifactId>hibernate-c3p0artifactId>
      <version>5.3.5.Finalversion>
    dependency>

    <dependency>
      <groupId>org.projectlombokgroupId>
      <artifactId>lombokartifactId>
      <version>1.18.12version>
    dependency>
	
	
    <dependency>
      <groupId>mysqlgroupId>
      <artifactId>mysql-connector-javaartifactId>
      <version>8.0.19version>
    dependency>

	
    <dependency>
      <groupId>javax.xml.bindgroupId>
      <artifactId>jaxb-apiartifactId>
      <version>2.3.0version>
    dependency>
    <dependency>
      <groupId>com.sun.xml.bindgroupId>
      <artifactId>jaxb-implartifactId>
      <version>2.3.0version>
    dependency>
    <dependency>
      <groupId>com.sun.xml.bindgroupId>
      <artifactId>jaxb-coreartifactId>
      <version>2.3.0version>
    dependency>
    <dependency>
      <groupId>javax.activationgroupId>
      <artifactId>activationartifactId>
      <version>1.1.1version>
    dependency>

  dependencies>

创建配置文件hibernate.cfg.xml放在resources中



<hibernate-configuration>
    <session-factory>
        <property name="hibernate.dialect">org.hibernate.dialect.MySQL8Dialectproperty>
        <property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driverproperty>
        <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/ssm?useSSL=false&characterEncoding=UTF-8&serverTimezone=UTCproperty>
        <property name="hibernate.connection.username">rootproperty>
        <property name="hibernate.connection.password">passwordproperty>

        <property name="hibernate.connection.provider_class">org.hibernate.c3p0.internal.C3P0ConnectionProviderproperty>
        
        <property name="hibernate.show_sql">trueproperty>
        <property name="hibernate.format_sql">trueproperty>
        <property name="hibernate.hbm2ddl.auto">updateproperty>

        
        <property name="hibernate.current_session_context_class">threadproperty>
        
        
        <mapping resource="com/haoxuan/dao/User.hbm.xml" />
    session-factory>
hibernate-configuration>

实体类User.java

package com.haoxuan.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    private Integer id;
    private String name;
    private String password;
    private String tel;
}

创建映射文件User.hbm.xml



<hibernate-mapping>
    <class name="com.haoxuan.entity.User" table="user">
        <id name="id" column="id">
            <generator class="native">generator>
        id>
        <property name="name" column="username">property>
        <property name="password" column="password">property>
        <property name="tel" column="tel">property>
    class>
hibernate-mapping>

创建工具类HibernateUtil.java

package com.haoxuan.util;

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

public class HibernateUtil {
    static Configuration configuration = null;
    static SessionFactory sessionFactory = null;
    static {
        configuration = new Configuration();
        configuration.configure();

        sessionFactory = configuration.buildSessionFactory();
    }

    public static Session openSession()
    {
        return sessionFactory.openSession();
    }

    public static Session getCurrentSession()
    {
        Session session = sessionFactory.getCurrentSession();
        return session;
    }
}

hibernate查询的四种方式

1、主键查询
2、HQL查询
3、Criteria查询
4、本地sql查询

测试

public class HibernateTest {

    /*
    主键查询get、load
    区别:hibernate对于 load方法认为该数据在数据库中一定存在,可以放心的使用代理来延迟加载,
    如果在使用过程中发现了问题,只能抛异常;而对于get方法,hibernate一定要获取到真实
    的数据,否则返回null。
    */
    @Test
    public void hibernate1() {
        Session session = HibernateUtil.openSession();
        Transaction tx = session.beginTransaction();
        //get(实体类,主键);
        User user = session.get(User.class,1);
        System.out.println(user);

        tx.commit();
        session.close();
    }

    /*
    save()方法
    出现java.sql.SQLException: Field 'id' doesn't have a default value报错
    说明没有为主键设置自增
    */
    @Test
    public void hibernate2() {
    Session session = HibernateUtil.openSession();
    Transaction tx = session.beginTransaction();

    User user = new User(2,"name","word","13174851256");
    session.save(user);

    tx.commit();
    session.close();
    }

    /*
    使用hql,操作的对象为实体类
    1、查询全部字段,list封装的为对象的实体类
    2、只查询一个字段,默认情况下,list封装的是Object对象
    3、查询两个或两个以上字段,默认情况下,list封装的是Object[],长度与所查询的字段数一致。
    */
    @Test
    public void hibernate3() {
        Session session = HibernateUtil.openSession();
        Transaction tx = session.beginTransaction();

        String hql = "select u.name,u.tel from User u where u.id=1";
        Query query = session.createQuery(hql);
        List<Object[]> result = query.list();

        for (Object[] objs : result) {
            System.out.println("name:"+objs[0]);
            System.out.println("tel:"+objs[1]);
        }

    }

    /*
    使用原生sql
    */
    @Test
    public void hibernate4() {
        Session session = HibernateUtil.openSession();
        Transaction tx = session.beginTransaction();

        String sql = "select username,tel from user where id=1";
        Query query = session.createSQLQuery(sql);
        List<Object[]> result = query.list();

        for (Object[] objs : result) {
            System.out.println("name:"+objs[0]);
            System.out.println("tel:"+objs[1]);
        }
    }

    /*
    标准查询Criteria
    */
    @Test
    public void hibernate5() {
        Session session = HibernateUtil.openSession();
        Transaction tx = session.beginTransaction();

        Criteria criteria = session.createCriteria(User.class);
        criteria.add(Restrictions.eq("id",1));
        List<User> result = criteria.list();

        for (User user : result) {
            System.out.println(user);
        }
    }
}


Hibernate+JPA

maven依赖

  <dependencies>
    <dependency>
      <groupId>junitgroupId>
      <artifactId>junitartifactId>
      <version>4.11version>
    dependency>
    
    <dependency>
      <groupId>org.hibernategroupId>
      <artifactId>hibernate-entitymanagerartifactId>
      <version>5.3.5.Finalversion>
    dependency>
    <dependency>
      <groupId>org.hibernategroupId>
      <artifactId>hibernate-c3p0artifactId>
      <version>5.3.5.Finalversion>
    dependency>

    <dependency>
      <groupId>org.projectlombokgroupId>
      <artifactId>lombokartifactId>
      <version>1.18.12version>
    dependency>

    <dependency>
      <groupId>mysqlgroupId>
      <artifactId>mysql-connector-javaartifactId>
      <version>8.0.19version>
    dependency>
    
  dependencies>

配置文件,放在resource文件夹中的META-INF中 persistent.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">
        
        <provider>org.hibernate.jpa.HibernatePersistenceProviderprovider>
        <properties>
            
            <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
            
            <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/ssm?characterEncoding=utf-8" />
            
            <property name="javax.persistence.jdbc.user" value="root" />
            
            <property name="javax.persistence.jdbc.password" value="password" />

            
            
            <property name="hibernate.show_sql" value="true" />
            <property name="hibernate.format_sql" value="true" />
            <property name="hibernate.hbm2ddl.auto" value="update" />
        properties>
    persistence-unit>
persistence>

工具类JpaUtil.java

package com.haoxuan.util;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

public class JpaUtil {
    private static EntityManagerFactory entityManagerFactory;
    static {
        entityManagerFactory = Persistence.createEntityManagerFactory("myJpa");
    }

    public static EntityManager getEntityManager() {
        return entityManagerFactory.createEntityManager();
    }
}

测试类

package com.haoxuan.test;

import com.haoxuan.entity.User;
import com.haoxuan.util.JpaUtil;
import org.junit.Test;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;

public class JpaTest {

    /*
    persist : 保存操作
    merge : 更新操作
    remove : 删除操作
    find(立即加载)/getReference(延迟加载) : 根据id查询
    */

    @Test
    public void jpaTest1(){
        EntityManager em = JpaUtil.getEntityManager();
        EntityTransaction tx = em.getTransaction();
        tx.begin();

        User user = em.find(User.class,1);
        System.out.println(user);
    }

}

Spring + Spring data jpa + hibernate

maven依赖

  <dependencies>
    <dependency>
      <groupId>junitgroupId>
      <artifactId>junitartifactId>
      <version>4.12version>
    dependency>

    
    <dependency>
      <groupId>org.springframework.datagroupId>
      <artifactId>spring-data-jpaartifactId>
      <version>2.3.0.RELEASEversion>
    dependency>
    <dependency>
      <groupId>org.springframework.datagroupId>
      <artifactId>spring-data-commonsartifactId>
      <version>2.3.0.RELEASEversion>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-coreartifactId>
      <version>5.2.6.RELEASEversion>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-contextartifactId>
      <version>5.2.6.RELEASEversion>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-beansartifactId>
      <version>5.2.6.RELEASEversion>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-jdbcartifactId>
      <version>5.2.6.RELEASEversion>
    dependency>
    <dependency>
      <groupId>org.springframeworkgroupId>
      <artifactId>spring-testartifactId>
      <version>5.2.6.RELEASEversion>
    dependency>
    
    <dependency>
      <groupId>org.hibernategroupId>
      <artifactId>hibernate-coreartifactId>
      <version>5.3.5.Finalversion>
    dependency>
    <dependency>
      <groupId>javax.xml.bindgroupId>
      <artifactId>jaxb-apiartifactId>
      <version>2.3.0version>
    dependency>
    <dependency>
      <groupId>com.sun.xml.bindgroupId>
      <artifactId>jaxb-implartifactId>
      <version>2.3.0version>
    dependency>
    <dependency>
      <groupId>com.sun.xml.bindgroupId>
      <artifactId>jaxb-coreartifactId>
      <version>2.3.0version>
    dependency>
    <dependency>
      <groupId>javax.activationgroupId>
      <artifactId>activationartifactId>
      <version>1.1.1version>
    dependency>


    <dependency>
      <groupId>org.projectlombokgroupId>
      <artifactId>lombokartifactId>
      <version>1.18.12version>
    dependency>

    
    <dependency>
      <groupId>com.alibabagroupId>
      <artifactId>druidartifactId>
      <version>1.1.21version>
    dependency>
    <dependency>
      <groupId>mysqlgroupId>
      <artifactId>mysql-connector-javaartifactId>
      <version>8.0.19version>
    dependency>

    
    <dependency>
      <groupId>log4jgroupId>
      <artifactId>log4jartifactId>
      <version>1.2.17version>
    dependency>
    <dependency>
      <groupId>org.slf4jgroupId>
      <artifactId>slf4j-apiartifactId>
      <version>2.0.0-alpha1version>
    dependency>
    <dependency>
      <groupId>org.slf4jgroupId>
      <artifactId>slf4j-log4j12artifactId>
      <version>2.0.0-alpha1version>
    dependency>

  dependencies>

创建spring配置文件applicationContext.xml


<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:task="http://www.springframework.org/schema/task"
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
		http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
		http://www.springframework.org/schema/data/jpa 
		http://www.springframework.org/schema/data/jpa/spring-jpa.xsd">
	
	
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
		<property name="driverClass" value="com.mysql.jdbc.Driver" />
		<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/jpa?characterEncoding=utf-8" />
		<property name="user" value="root" />
		<property name="password" value="password" />
	bean>
	
	
	<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
		<property name="dataSource" ref="dataSource" />
		<property name="packagesToScan" value="com.ithubei.entity" />
		<property name="persistenceProvider">
			<bean class="org.hibernate.jpa.HibernatePersistenceProvider" />
		property>
		
        <property name="jpaProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialectprop>
                <prop key="hibernate.show_sql">trueprop>
                <prop key="hibernate.format_sql">trueprop>
                <prop key="hibernate.hbm2ddl.auto">updateprop>
            props>
        property>
		
		<property name="jpaVendorAdapter">
			<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
				<property name="generateDdl" value="false" />
				<property name="database" value="MYSQL" />
				<property name="databasePlatform" value="org.hibernate.dialect.MySQL8Dialect" />
			bean>
		property>
		<property name="jpaDialect">
			<bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" />
		property>
	bean>
    
	
	
	
	<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
		<property name="entityManagerFactory" ref="entityManagerFactory" />
	bean>
	
	
	<jpa:repositories base-package="com.ithubei.dao"
		transaction-manager-ref="transactionManager"
		entity-manager-factory-ref="entityManagerFactory">jpa:repositories>
		
	
	<tx:advice id="txAdvice" transaction-manager="transactionManager">
		<tx:attributes>
			<tx:method name="save*" propagation="REQUIRED"/>
			<tx:method name="insert*" propagation="REQUIRED"/>
			<tx:method name="update*" propagation="REQUIRED"/>
			<tx:method name="delete*" propagation="REQUIRED"/>
			<tx:method name="get*" read-only="true"/>
			<tx:method name="find*" read-only="true"/>
			<tx:method name="*" propagation="REQUIRED"/>
		tx:attributes>
	tx:advice>
	
	
	<aop:config>
		<aop:pointcut id="pointcut" expression="execution(* com.ithubei.service.*.*(..))" />
		<aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut" />
	aop:config>
	
	<context:component-scan base-package="com.ithubei">context:component-scan>
		
	
	
beans>

实体类User.java

@Data
@AllArgsConstructor
@NoArgsConstructor
@Entity
@Table(name = "user")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Integer id;

    @Column(name = "username")
    private String name;

    @Column(name = "password")
    private String password;

    @Column(name = "tel")
    private String tel;
}

UserDao.java

package com.haoxuan.dao;

import com.haoxuan.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;

import java.util.Optional;

@Repository
public interface UserDao extends JpaRepository<User,Integer> {
    public Optional<User> findById(Integer id);
}

测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class SpringJpaTest {

    @Autowired
    UserDao userDao;

    @Test
    public void test1() {
        Optional<User> user = userDao.findById(1);
        if (user.isPresent()) {
            System.out.println(user.get());
        } else {
            System.out.println("Not find!");
        }
    }
}

你可能感兴趣的:(Java,Spring)