JPA---Spring-data-JPA---Hibernate

Posted 雨听风说

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JPA---Spring-data-JPA---Hibernate相关的知识,希望对你有一定的参考价值。

Spring Data JPA--搭建环境

版本---maven  3.6.3

 <properties>
        <spring.version>5.2.5.RELEASE</spring.version>    Spring的版本
        <hibernate.version>5.4.10.Final</hibernate.version>   hibernate的版本
        <slf4j.version>1.7.30</slf4j.version>
        <log4j.version>2.12.1</log4j.version>
        <druid.version>1.1.21</druid.version>
        <mysql.version>5.1.6</mysql.version>

    </properties>

导入依赖坐标

 <dependencies>
        <!-- spring beg -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.5</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context-support</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- spring对orm框架的支持包-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>${spring.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!-- hibernate beg -->
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-entitymanager</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>${hibernate.version}</version>
        </dependency>
        <dependency>
            <groupId>org.hibernate.validator</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>6.1.2.Final</version>
            <exclusions>
                <exclusion>
                    <artifactId>classmate</artifactId>
                    <groupId>com.fasterxml</groupId>
                </exclusion>
            </exclusions>
        </dependency>

        <!-- hibernate end -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>${mysql.version}</version>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>${druid.version}</version>
        </dependency>
        <!-- spring data jpa 的坐标 -->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>2.2.6.RELEASE</version>
            <exclusions>
                <exclusion>
                    <artifactId>slf4j-api</artifactId>
                    <groupId>org.slf4j</groupId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>${spring.version}</version>
        </dependency>

        <!--  el beg 使用spring data jpa 必须引入 -->
        <dependency>
            <groupId>javax.el</groupId>
            <artifactId>javax.el-api</artifactId>
            <version>3.0.0</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish</groupId>
            <artifactId>javax.el</artifactId>
            <version>3.0.0</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-api</artifactId>
            <version>${log4j.version}</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>

    </dependencies>

创建配置文件

applicatioContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<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"
       xmlns:contxt="http://www.springframework.org/schema/context"
       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="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">

        <!-- 配置数据源 -->
        <property name="dataSource" ref="dataSource"/>
        
        <!-- 配置实体类包扫描 -->
        <property name="packagesToScan" value="com.ytfs.entity"/>
        <!-- 配置jpa提供方 -->
        <property name="persistenceProvider">
            <bean class="org.hibernate.jpa.HibernatePersistenceProvider"/>
        </property>



        <!-- 配置JPA提供方的适配器 -->

        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <!-- 是否显示sql语句 -->
                <property name="showSql" value="true"/>
                <!-- 数据库的类型 -->
                <property name="database" value="MYSQL"/>
                <!-- 数据库的方言 -->
                <property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect"/>
                <!-- 是否自动创建表 -->
                <property name="generateDdl" value="false"/>
            </bean>
        </property>
    </bean>

    <!-- 配置数据源 -->

    <contxt:property-placeholder location="classpath:jdbcConfig.properties"/>
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="username" value="${jdbc.username}"/>
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

    <!-- 配置事务管理器 -->
    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory"/>
    </bean>

    <!-- 整合jpa -->
    <jpa:repositories base-package="com.ytfs.dao"
                      transaction-manager-ref="transactionManager"
                      entity-manager-factory-ref="entityManagerFactory"/>

    <!-- 配置上spring包扫描器 -->
    <context:component-scan base-package="com.ytfs"/>

jdbcConfig.xml

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/jpa
jdbc.username=root
jdbc.password=root

创建实体类

package com.ytfs.entity;


import javax.persistence.*;
import java.io.Serializable;

/**
 * @Classname Customer
 * @Description TODO(客户实体类)
 * @Date 2020/4/29 21:34
 * @Created by ytfs
 */


@Entity
@Table(name = "cst_customer")
public class Customer implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "cust_id")
    private Long custId;
    /**
     * cust_id` bigint(32) NOT NULL AUTO_INCREMENT COMMENT \'客户编号(主键)\',
     * `cust_name` varchar(32) NOT NULL COMMENT \'客户名称(公司名称)\',
     * `cust_source` varchar(32) DEFAULT NULL COMMENT \'客户信息来源\',
     * `cust_industry` varchar(32) DEFAULT NULL COMMENT \'客户所属行业\',
     * `cust_level` varchar(32) DEFAULT NULL COMMENT \'客户级别\',
     * `cust_address` varchar(128) DEFAULT NULL COMMENT \'客户联系地址\',
     * `cust_phone` v
     */
    @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 Long getCustId() {
        return custId;
    }

    public void setCustId(Long 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 + \'\\\'\' +
                \'}\';
    }
}
View Code

创建dao接口

Spring Data JPA是spring提供的一款对于数据访问层(Dao层)的框架,使用Spring Data JPA,只需要按照框架的规范提供dao接口,不需要实现类就可以完成数据库的增删改查、分页查询等方法的定义,极大的简化了我们的开发过程。

 

在Spring Data JPA中,对于定义符合规范的Dao层接口,我们只需要遵循以下几点就可以了:

 

1.创建一个Dao层接口,并实现JpaRepositoryJpaSpecificationExecutor

    2.提供相应的泛型

package com.ytfs.dao;

import com.alibaba.druid.sql.visitor.functions.If;
import com.ytfs.entity.Customer;
import org.hibernate.mapping.Value;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;

import java.lang.invoke.VarHandle;
import java.security.spec.NamedParameterSpec;
import java.util.List;


/**
 * @Classname CustomerDao
 * @Description TODO(客户的数据库访问层)
 * @Date 2020/4/29 21:46
 * @Created by ytfs
 * JpaRepository<实体类类型,主键类型>:用来完成基本CRUD操作
 * JpaSpecificationExecutor<实体类类型>:用于复杂查询(分页等查询操作)
 */


public interface CustomerDao extends JpaRepository<Customer, Long>, JpaSpecificationExecutor<Customer> {

    /**
     * JPQL的方式查询全部客户
     *
     * @return
     */
    @Query(value = "from Customer")
    List<Customer> findAllByJPQL();

    /**
     * 根据客户名称和客户id查询客户
     * jpql: from Customer where custName = ? and custId = ?
     * <p>
     * 对于多个占位符参数
     * 赋值的时候,默认的情况下,占位符的位置需要和方法参数中的位置保持一致
     * <p>
     * 可以指定占位符参数的位置
     * ? 索引的方式,指定此占位的取值来源
     */
    @Query("from Customer where custName = ?2 and custId = ?1")
    Customer findCustomerById(Long custId, String custName);



    /**
     * 使用jpql完成更新操作
     *      案例 : 根据id更新,客户的名称
     *          更新4号客户的名称,将名称改为“黑马程序员”
     *
     *  sql  :update cst_customer set cust_name = ? where cust_id = ?
     *  jpql : update Customer set custName = ? where custId = ?
     *
     *  @Query : 代表的是进行查询
     *      * 声明此方法是用来进行更新操作
     *  @Modifying
     *      * 当前执行的是一个更新操作
     *
     */
    @Query("update Customer  set custName = ?1 where custId = ?2")
    @Modifying
    void updateCustomerById(String custName,Long Id);


    /**
     * 使用sql的形式查询:
     *     查询全部的客户
     *  sql : select * from cst_customer;
     *  Query : 配置sql查询
     *      value : sql语句
     *      nativeQuery : 查询方式
     *          true : sql查询
     *          false:jpql查询 默认值
     *
     */
    @Query(value = "select  * from cst_customer", nativeQuery = true)
    List<Customer> findAllBySql();


    /**
     * 使用sql的形式查询:
     *     条件查询
     *  sql : select * from cst_customer where cust_name like ?;
     *  Query : 配置sql查询
     *      value : sql语句
     *      nativeQuery : 查询方式
     *          true : sql查询
     *          false:jpql查询 默认值
     *
     */
    @Query(value = "select * from cst_customer where cust_name like ?1", nativeQuery = true)
    Customer FindCustomerByLikeCustName(String custName);
    
    
    /**
     * @author 雨听风说
     * @param 
     * @updateTime 2020/4/30 23:45
     * 方法名的约定:
     *      findBy : 查询
     *            对象中的属性名(首字母大写) : 查询的条件
     *            CustName
     *            * 默认情况 : 使用 等于的方式查询
     *                  特殊的查询方式
     *
     *  findByCustName   --   根据客户名称查询
     *
     *  再springdataJpa的运行阶段
     *          会根据方法名称进行解析  findBy    from  xxx(实体类)
     *                                      属性名称      where  custName =
     *
     *      1.findBy  + 属性名称 (根据属性名称进行完成匹配的查询=)
     *      2.findBy  + 属性名称 + “查询方式(Like | isnull)”
     *          findByCustNameLike
     *      3.多条件查询
     *          findBy + 属性名 + “查询方式”   + “多条件的连接符(and|or)”  + 属性名 + “查询方式”
     */


    /**
     * 根据名称精准查询客户
     * @param CustName
     * @return
     */
    Customer findByCustName(String CustName);


    /**
     * 根据客户名称进行模糊查询
     * @param CustName
     * @return
     */
    List<Customer> findByCustNameLike(String CustName);


    /**
     * 根据客户名称模糊查询,并且通过id精确查询
     * @param name
     * @param Id
     * @return
     */
    List<Customer> findByCustNameLikeAndCustId(String name, Long Id);

}
View Code

创建spring-data-jpa的测试案例

完成了Spring D

以上是关于JPA---Spring-data-JPA---Hibernate的主要内容,如果未能解决你的问题,请参考以下文章