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

2021-01-24 10:13

阅读:716

标签:创建表   varchar   over   splay   pac   code   实现类   pos   保存   

Spring Data JPA--搭建环境

版本---maven  3.6.3

 5.2.5.RELEASE    Spring的版本
        5.4.10.Final   hibernate的版本
        1.7.302.12.11.1.215.1.6

导入依赖坐标

 dependencies>
        
        dependency>
            groupId>org.springframeworkgroupId>
            artifactId>spring-aopartifactId>
            version>${spring.version}version>
        dependency>

        dependency>
            groupId>org.aspectjgroupId>
            artifactId>aspectjweaverartifactId>
            version>1.9.5version>
        dependency>
        dependency>
            groupId>org.springframeworkgroupId>
            artifactId>spring-contextartifactId>
            version>${spring.version}version>
        dependency>

        dependency>
            groupId>org.springframeworkgroupId>
            artifactId>spring-context-supportartifactId>
            version>${spring.version}version>
        dependency>
        dependency>
            groupId>org.springframeworkgroupId>
            artifactId>spring-testartifactId>
            version>${spring.version}version>
        dependency>

        
        dependency>
            groupId>org.springframeworkgroupId>
            artifactId>spring-ormartifactId>
            version>${spring.version}version>
        dependency>
        dependency>
            groupId>org.springframeworkgroupId>
            artifactId>spring-beansartifactId>
            version>${spring.version}version>
        dependency>
        dependency>
            groupId>org.springframeworkgroupId>
            artifactId>spring-coreartifactId>
            version>${spring.version}version>
        dependency>

        
        dependency>
            groupId>org.hibernategroupId>
            artifactId>hibernate-entitymanagerartifactId>
            version>${hibernate.version}version>
        dependency>
        dependency>
            groupId>org.hibernategroupId>
            artifactId>hibernate-coreartifactId>
            version>${hibernate.version}version>
        dependency>
        dependency>
            groupId>org.hibernate.validatorgroupId>
            artifactId>hibernate-validatorartifactId>
            version>6.1.2.Finalversion>
            exclusions>
                exclusion>
                    artifactId>classmateartifactId>
                    groupId>com.fasterxmlgroupId>
                exclusion>
            exclusions>
        dependency>

        
        dependency>
            groupId>mysqlgroupId>
            artifactId>mysql-connector-javaartifactId>
            version>${mysql.version}version>
        dependency>
        dependency>
            groupId>com.alibabagroupId>
            artifactId>druidartifactId>
            version>${druid.version}version>
        dependency>
        
        dependency>
            groupId>org.springframework.datagroupId>
            artifactId>spring-data-jpaartifactId>
            version>2.2.6.RELEASEversion>
            exclusions>
                exclusion>
                    artifactId>slf4j-apiartifactId>
                    groupId>org.slf4jgroupId>
                exclusion>
            exclusions>
        dependency>
        dependency>
            groupId>org.springframeworkgroupId>
            artifactId>spring-testartifactId>
            version>${spring.version}version>
        dependency>

        
        dependency>
            groupId>javax.elgroupId>
            artifactId>javax.el-apiartifactId>
            version>3.0.0version>
        dependency>
        dependency>
            groupId>org.glassfishgroupId>
            artifactId>javax.elartifactId>
            version>3.0.0version>
        dependency>
        dependency>
            groupId>org.slf4jgroupId>
            artifactId>slf4j-apiartifactId>
            version>${slf4j.version}version>
        dependency>
        dependency>
            groupId>org.apache.logging.log4jgroupId>
            artifactId>log4j-apiartifactId>
            version>${log4j.version}version>
        dependency>
        dependency>
            groupId>junitgroupId>
            artifactId>junitartifactId>
            version>4.12version>
        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"/>
        
        property name="persistenceProvider">
            bean class="org.hibernate.jpa.HibernatePersistenceProvider"/>
        property>



        

        property name="jpaVendorAdapter">
            bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                
                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:repositories base-package="com.ytfs.dao"
                      transaction-manager-ref="transactionManager"
                      entity-manager-factory-ref="entityManagerFactory"/>

    
    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, JpaSpecificationExecutor {

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

    /**
     * 根据客户名称和客户id查询客户
     * jpql: from Customer where custName = ? and custId = ?
     * 

* 对于多个占位符参数 * 赋值的时候,默认的情况下,占位符的位置需要和方法参数中的位置保持一致 *

* 可以指定占位符参数的位置 * ? 索引的方式,指定此占位的取值来源

*/ @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 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 findByCustNameLike(String CustName); /** * 根据客户名称模糊查询,并且通过id精确查询 * @param name * @param Id * @return */ List findByCustNameLikeAndCustId(String name, Long Id); }
View Code

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

完成了Spring Data JPA的环境搭建,并且编写了符合Spring Data JPA 规范的Dao层接口之后,就可以使用定义好的Dao层接口进行客户的基本CRUD操作

技术图片技术图片
package com.ytfs.test;

import com.ytfs.dao.CustomerDao;
import com.ytfs.entity.Customer;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.List;

/**
 * @Classname SpringDataJpaTest
 * @Description TODO(springDataJpa的测试案例)
 * @Date 2020/4/29 21:58
 * @Created by ytfs
 */


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

    @Autowired
    private CustomerDao customerDao;

    /**
     * @description 查询全部
     * @author 雨听风说
     * @updateTime 2020/4/29 22:44
     */
    @Test
    public void testFindALl() {

        List list = this.customerDao.findAll();

        list.forEach(System.out::println);

    }

    /**
     * @description 根据id查询客户
     * @author 雨听风说
     * @updateTime 2020/4/29 22:49
     */
    @Test
    public void testFindById() {
        System.out.println(this.customerDao.findById(1L));
    }

    /**
     * @description 根据Id删除
     * @author 雨听风说
     * @updateTime 2020/4/29 22:53
     */
    @Test
    public void testDelete() {
        this.customerDao.deleteById(4l);
    }

    /**
     * @description 保存客户, save, 保存并且返回保存的对象
     * @author 雨听风说
     * @updateTime 2020/4/29 23:03
     */
    @Test
    public void testSave() {
        Customer customer = new Customer();
        customer.setCustName("雨听风说");
        this.customerDao.save(customer);
    }

    /**
     * @description 当保存方法执行的时候, 如果需要保存的对象有id, 那么将自动更新这个id的对象
     *              并且将该对象为设置的参数置为null
     * @author 雨听风说
     * @updateTime 2020/4/29 23:07
     */

    @Test
    public void testUpdate() {

        Customer customer = new Customer();

        customer.setCustId(5l);

        customer.setCustName("雨听风说修改");
        this.customerDao.save(customer);
    }
}
View Code

JPQL

1.1   方法命名规则查询

顾名思义,方法命名规则查询就是根据方法的名字,就能创建查询。只需要按照Spring Data JPA提供的方法命名规则定义方法的名称,就可以完成查询工作。Spring Data JPA在程序执行的时候会根据方法名称进行解析,并自动生成查询语句进行查询

 

按照Spring Data JPA 定义的规则,查询方法以findBy开头,涉及条件查询时,条件的属性用条件关键字连接,要注意的是:条件属性首字母需大写。框架在进行方法名解析时,会先把方法名多余的前缀截取掉,然后对剩下部分进行解析。

 

    //方法命名方式查询(根据客户名称查询客户)

    public Customer findByCustName(String custName);

 

 

具体的关键字,使用方法和生产成SQL如下表所示

 

         

Keyword

Sample

JPQL

   

And

findByLastnameAndFirstname

… where x.lastname = ?1 and x.firstname = ?2

   

Or

findByLastnameOrFirstname

… where x.lastname = ?1 or x.firstname = ?2

   

Is,Equals

findByFirstnameIs,

findByFirstnameEquals

… where x.firstname = ?1

   

Between

findByStartDateBetween

… where x.startDate between ?1 and ?2

   

LessThan

findByAgeLessThan

… where x.age

   

LessThanEqual

findByAgeLessThanEqual

… where x.age ⇐ ?1

   

GreaterThan

findByAgeGreaterThan

… where x.age > ?1

   

GreaterThanEqual

findByAgeGreaterThanEqual

… where x.age >= ?1

   

After

findByStartDateAfter

… where x.startDate > ?1

   

Before

findByStartDateBefore

… where x.startDate

   

IsNull

findByAgeIsNull

… where x.age is null

   

IsNotNull,NotNull

findByAge(Is)NotNull

… where x.age not null

   

Like

findByFirstnameLike

… where x.firstname like ?1

   

NotLike

findByFirstnameNotLike

… where x.firstname not like ?1

   

StartingWith

findByFirstnameStartingWith

… where x.firstname like ?1 (parameter bound with appended %)

   

EndingWith

findByFirstnameEndingWith

… where x.firstname like ?1 (parameter bound with prepended %)

   

Containing

findByFirstnameContaining

… where x.firstname like ?1 (parameter bound wrapped in %)

   

OrderBy

findByAgeOrderByLastnameDesc

… where x.age = ?1 order by x.lastname desc

   

Not

findByLastnameNot

… where x.lastname ?1

   

In

findByAgeIn(Collection ages)

… where x.age in ?1

   

NotIn

findByAgeNotIn(Collection age)

… where x.age not in ?1

   

TRUE

findByActiveTrue()

… where x.active = true

   

FALSE

findByActiveFalse()

… where x.active = false

   

IgnoreCase

findByFirstnameIgnoreCase

… where UPPER(x.firstame) = UPPER(?1)

   

 

创建JPQL的测试案例

技术图片技术图片
package com.ytfs.test;

import com.ytfs.dao.CustomerDao;
import com.ytfs.entity.Customer;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.transaction.Transactional;
import java.util.List;

/**
 * @Classname SpringDataJPAJpqlTest
 * @Description TODO(SpringDataJpaJpql测试)
 * @Date 2020/4/30 21:15
 * @Created by ytfs
 */

/**
 * jpql的查询方式
 * jpql : jpa query language  (jpq查询语言)
 * 特点:语法或关键字和sql语句类似
 *     查询的是类和类中的属性
 *     需要将JPQL语句配置到接口方法上
 * 1.特有的查询:需要在dao接口上配置方法
 * 2.在新添加的方法上,使用注解的形式配置jpql查询语句
 * 3.注解 : @Query
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class SpringDataJPAJpqlTest {

    @Autowired
    private CustomerDao customerDao;

    /**
     * @description 通过JPQL的方式查询所有的客户
     * @author 雨听风说
     * @updateTime 2020/4/30 21:48
     */
    @Test
    public void testFindAll() {

        List list = this.customerDa


评论


亲,登录后才可以留言!