慕课网_《轻松愉快之玩转SpringData》第三,四章学习总结3

本文详细介绍SpringDataJPA的开发环境搭建、实体类创建、Repository接口使用、查询方法定义规则、Query注解使用及更新操作整合事务的实践。通过具体代码示例,展示如何在Spring框架下高效进行数据库操作。

3-1 开发环境搭建
Spring Data JPA快速起步
开发环境搭建
Spring Data JPA helloworld

在domain创建Employee.java

package com.imooc.domain;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

/**
 * 雇员:先开发实体类--->自动生成数据表
 */
@Entity
public class Employee {
    private Integer id;
    private String name;
    private Integer age;
    @GeneratedValue
    @Id
    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }
    @Column(length =20 )
    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }
}

@Id
@GeneratedValue
@Entity

根据之前的配置,完美运行SpringDataTest
在com.imooc下创建SpringDataTest
代码详情:

package com.imooc;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class SpringDataTest {
    /**
     * 实体类自动生成一张表
     */
    private ApplicationContext cxt =null ;


    @Before
    public void setup(){
        cxt = new ClassPathXmlApplicationContext("beansnew.xml");
        System.out.println("setup");
    }
    @After
    public void tearDown(){
        cxt = null ;
        System.out.println("tearDown");
    }
    @Test
    public void testEntityManagerFactory(){

    }
}

在beans-new.xml添加新的依赖(注解相关)

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

    </bean>

    <!--支持注解的事务-->
    <tx:annotation-driven transaction-manager="transactionManager"/>

    <!--配置spring data-->
    <jpa:repositories base-package="com.imooc" entity-manager-factory-ref="entityManagerFactory"/>
    <context:component-scan base-package="com.imooc"/>

beans-new.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:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:jpa="http://www.springframework.org/schema/data/jpa"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd
		http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <!--1 配置数据源-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="username" value="root"/>
        <property name="password" value="915099"/>
        <property name="url" value="jdbc:mysql:///spring_data?useSSL=false"/>
    </bean>

    <!--2 配置EntityManagerFactory-->
    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"/>
        </property>
        <property name="packagesToScan" value="com.imooc"/>

        <property name="jpaProperties">
            <props>
                <prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategy</prop>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.format_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">update</prop>
            </props>
        </property>

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

    </bean>

    <!--支持注解的事务-->
    <tx:annotation-driven transaction-manager="transactionManager"/>

    <!--配置spring data-->
    <jpa:repositories base-package="com.imooc" entity-manager-factory-ref="entityManagerFactory"/>
    <context:component-scan base-package="com.imooc"/>
</beans>

在com.imooc下创建package repository新建interface EmployeeRepository(下面是第四章完整的代码

package com.imooc.repository;

import com.imooc.domain.Employee;
import org.hibernate.sql.Select;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.Repository;
import org.springframework.data.repository.RepositoryDefinition;
import org.springframework.data.repository.query.Param;

import java.util.List;

@RepositoryDefinition(domainClass = Employee.class, idClass = Integer.class)
public interface EmployeeRepository {
    public Employee findByName(String name);
    
}

测试,在Test下com.imooc建立repository,在新建EmployeeRepositoryTest (第四章完整代码)

package com.imooc.repository;

import com.imooc.domain.Employee;
import com.mysql.fabric.xmlrpc.base.Fault;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.ArrayList;
import java.util.List;

public class EmployeeRepositoryTest {
    private ApplicationContext cxt =null ;
    private EmployeeRepository employeeRepository = null ;

    @Before
    public void setup(){
        cxt = new ClassPathXmlApplicationContext("beansnew.xml");
        employeeRepository= cxt.getBean(EmployeeRepository.class);
        System.out.println("setup");
    }
    @After
    public void tearDown(){
        cxt = null ;
        System.out.println("tearDown");
    }

    @Test
    public void TestFindByName() {
//        employeeRepository = (EmployeeRepository)cxt.getBean("employeeRepository");
        Employee employee = employeeRepository.findByName("RLiBin");

        if( employee == null){
            System.out.println("查询数据为空");
        }else{
            System.out.println("Id: " + employee.getId() +
                    "  name: " + employee.getName() +
                    "  age: " + employee.getAge());
        }
    }

   
}

Repository

Repository:Spring Data核心类 RepositoryDefinition:使用该注解进行配置 Repository
Query Specification:查询时,方法命名不能乱写 Query Annotation:使用该注解,可以实现原生SQL查询
Update/Delete/Transaction:更新、删除操作,支持事务

Repository Hierarchy

CrudRepository:内置了新增、更新、删除、查询方法PagingAndSortingRespository:分页和排序
JpaRepository JpaSpecificationExcutor

第四章 Spring Data 进阶

4-1关于Repository

Repository 接口详解

Repository接口是Spring Data的核心接口,不提供任何方法
public interface Repository<T, ID extends Serializable>{}
@RepositoryDefinition注解的使用

Repository类的定义

1)Repository是一个空接口,标记接口。没有包含方法声明的接口
2)如果我们定义的接口EmployeeRepository extends Repository,会被Spring管理。
如果我们自己的接口没有extends Repository,运行时会报错,没有这个Bean。

4-2 Repository子接口详解

Repository子接口详解

CrudRepository:继承Repository,实现了CRUD相关的方法
PagingAndSortingRepository:继承CrudRepository,实现了分页排序相关的方法
JpaRepository:继承PagingAndSortingRepositor,实现JPA规范相关的方法

添加注解能达到不用extends Repository的功能

@RepositoryDefinition(domainClass = Employee.class, idClass = Integer.class)

4-3 查询方法定义规则和使用

Repository中查询方法定义规则和使用
1.了解Spring Data中查询方法名称的定义规则
2.使用Spring 完成复杂查询方法名称的命名

Repository中查询定义规则和使用
在这里插入图片描述在这里插入图片描述
在数据库中创建数据
@RepositoryDefinition(domainClass = Employee.class, idClass = Integer.class)

在这里插入图片描述
查看一下数据库数据
use spring_data;
select *from employee;

在EmployeeRepository添加查询

package com.imooc.repository;

import com.imooc.domain.Employee;
import org.hibernate.sql.Select;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.Repository;
import org.springframework.data.repository.RepositoryDefinition;
import org.springframework.data.repository.query.Param;

import java.util.List;

@RepositoryDefinition(domainClass = Employee.class, idClass = Integer.class)
public interface EmployeeRepository {
    public Employee findByName(String name);
    //where name kike ?% and age <?
    public List<Employee> findByNameStartingWithAndAgeLessThan(String name, Integer age);

    //where name kike ?% and age <?
    public List<Employee> findByNameEndingWithAndAgeLessThan(String name, Integer age);

    //where name in (?,?...) or < ?
    public List<Employee> findByNameInOrAgeLessThan(List<String> name, Integer age);
    //where name in (?,?...) or <
    public List<Employee> findByNameInAndAgeLessThan(List<String> name, Integer age);

   

}

EmployeeRepositoryTest

package com.imooc.repository;

import com.imooc.domain.Employee;
import com.mysql.fabric.xmlrpc.base.Fault;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.ArrayList;
import java.util.List;

public class EmployeeRepositoryTest {
    private ApplicationContext cxt =null ;
    private EmployeeRepository employeeRepository = null ;

    @Before
    public void setup(){
        cxt = new ClassPathXmlApplicationContext("beansnew.xml");
        employeeRepository= cxt.getBean(EmployeeRepository.class);
        System.out.println("setup");
    }
    @After
    public void tearDown(){
        cxt = null ;
        System.out.println("tearDown");
    }

    @Test
    public void TestFindByName() {
//        employeeRepository = (EmployeeRepository)cxt.getBean("employeeRepository");
        Employee employee = employeeRepository.findByName("RLiBin");

        if( employee == null){
            System.out.println("查询数据为空");
        }else{
            System.out.println("Id: " + employee.getId() +
                    "  name: " + employee.getName() +
                    "  age: " + employee.getAge());
        }
    }

    @Test
    public void TestfindByNameStartingWithAndAgeLessThan(){
//        employeeRepository = (EmployeeRepository)cxt.getBean("employeeRepository");
        List<Employee> employees = employeeRepository.findByNameStartingWithAndAgeLessThan("test",22);
        if( employees != null  && employees.size() > 0){
            for (Employee employee : employees) {
                System.out.println("Id: " + employee.getId() +
                        "  name: " + employee.getName() +
                        "  age: " + employee.getAge());
            }
        }else{
            System.out.println("查询数据为空");
        }

    }

    @Test
    public void TestfindByNameEndingWithAndAgeLessThan(){
//        employeeRepository = (EmployeeRepository)cxt.getBean("employeeRepository");
        List<Employee> employees = employeeRepository.findByNameEndingWithAndAgeLessThan("6",22);
        if( employees != null  && employees.size() > 0){
            for (Employee employee : employees) {
                System.out.println("Id: " + employee.getId() +
                        "  name: " + employee.getName() +
                        "  age: " + employee.getAge());
            }
        }else{
            System.out.println("查询数据为空");
        }

    }

    @Test
    public void TestfindByNameInOrAgeLessThan(){
//        employeeRepository = (EmployeeRepository)cxt.getBean("employeeRepository");
        List<String> names = new ArrayList<String>();
        names.add("test1");
        names.add("test2");
        names.add("test3");
        List<Employee> employees = employeeRepository.findByNameInOrAgeLessThan(names,22);
        if( employees != null  && employees.size() > 0){
            for (Employee employee : employees) {
                System.out.println("Id: " + employee.getId() +
                        "  name: " + employee.getName() +
                        "  age: " + employee.getAge());
            }
        }else{
            System.out.println("查询数据为空");
        }

    }
    @Test
    public void TestfindByNameInAndAgeLessThan(){
//        employeeRepository = (EmployeeRepository)cxt.getBean("employeeRepository");
        List<String> names = new ArrayList<String>();
        names.add("test1");
        names.add("test2");
        names.add("test3");
        List<Employee> employees = employeeRepository.findByNameInAndAgeLessThan(names,22);
        if( employees != null  && employees.size() > 0){
            for (Employee employee : employees) {
                System.out.println("Id: " + employee.getId() +
                        "  name: " + employee.getName() +
                        "  age: " + employee.getAge());
            }
        }else{
            System.out.println("查询数据为空");
        }
    }
}

对于按照方法命名规则来使用的话,有弊端:
1)方法名比较长:约定大于配置
2)对于一些复杂的查询,是很难实现。

4-4Query注解使用

在Respository方法中使用,不需要遵循查询方法命令规则
只需要将@Query定义在Respository中的方法之上即可
命名参数及索引参数的使用
本地查询

代码演示:

EmployeeRepository

package com.imooc.repository;

import com.imooc.domain.Employee;
import org.hibernate.sql.Select;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.Repository;
import org.springframework.data.repository.RepositoryDefinition;
import org.springframework.data.repository.query.Param;

import java.util.List;

@RepositoryDefinition(domainClass = Employee.class, idClass = Integer.class)
public interface EmployeeRepository {
    public Employee findByName(String name);
    //where name kike ?% and age <?
    public List<Employee> findByNameStartingWithAndAgeLessThan(String name, Integer age);

    //where name kike ?% and age <?
    public List<Employee> findByNameEndingWithAndAgeLessThan(String name, Integer age);

    //where name in (?,?...) or < ?
    public List<Employee> findByNameInOrAgeLessThan(List<String> name, Integer age);
    //where name in (?,?...) or <
    public List<Employee> findByNameInAndAgeLessThan(List<String> name, Integer age);

    /**
     * 自定义查询SQL
     */
    @Query("select o from Employee o where id= (select max (id) from Employee t1)")
    public Employee getEmployeeByMaxId();

    /**
     *使用占位符进行参数绑定
     */

    @Query ("select o from Employee o where o.name=?1 and o.age = ?2 ")
    public List<Employee> queryParamsl(String name , Integer age);

    /**
     *使用命名参数进行参数绑定
     */
    @Query ("select o from Employee o where o.name= :name and o.age =:age ")
    public List<Employee> queryParamsl2(@Param("name") String name , @Param("age") Integer age);

    /**
     *自定义查询SQL,like,占位符进行参数绑定
     */
    @Query ("select o from Employee o where o.name like %?1%")
    public List<Employee> queryLike1( String name);

    /**
     *自定义查询SQL,like,命名参数进行参数绑定
     */
    @Query ("select o from Employee o where o.name like %:name%")
    public List<Employee> queryLike2( @Param("name") String name);
         /**
     *使用原生态SQL查询
     */
    @Query(nativeQuery = true, value = "select count(1) from employee")
    public long getCount();
  
}

EmployeeRepositoryTest

package com.imooc.repository;

import com.imooc.domain.Employee;
import com.mysql.fabric.xmlrpc.base.Fault;
import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.ArrayList;
import java.util.List;

public class EmployeeRepositoryTest {
    private ApplicationContext cxt =null ;
    private EmployeeRepository employeeRepository = null ;

    @Before
    public void setup(){
        cxt = new ClassPathXmlApplicationContext("beansnew.xml");
        employeeRepository= cxt.getBean(EmployeeRepository.class);
        System.out.println("setup");
    }
    @After
    public void tearDown(){
        cxt = null ;
        System.out.println("tearDown");
    }

    @Test
    public void TestFindByName() {
//        employeeRepository = (EmployeeRepository)cxt.getBean("employeeRepository");
        Employee employee = employeeRepository.findByName("RLiBin");

        if( employee == null){
            System.out.println("查询数据为空");
        }else{
            System.out.println("Id: " + employee.getId() +
                    "  name: " + employee.getName() +
                    "  age: " + employee.getAge());
        }
    }

    @Test
    public void TestfindByNameStartingWithAndAgeLessThan(){
//        employeeRepository = (EmployeeRepository)cxt.getBean("employeeRepository");
        List<Employee> employees = employeeRepository.findByNameStartingWithAndAgeLessThan("test",22);
        if( employees != null  && employees.size() > 0){
            for (Employee employee : employees) {
                System.out.println("Id: " + employee.getId() +
                        "  name: " + employee.getName() +
                        "  age: " + employee.getAge());
            }
        }else{
            System.out.println("查询数据为空");
        }

    }

    @Test
    public void TestfindByNameEndingWithAndAgeLessThan(){
//        employeeRepository = (EmployeeRepository)cxt.getBean("employeeRepository");
        List<Employee> employees = employeeRepository.findByNameEndingWithAndAgeLessThan("6",22);
        if( employees != null  && employees.size() > 0){
            for (Employee employee : employees) {
                System.out.println("Id: " + employee.getId() +
                        "  name: " + employee.getName() +
                        "  age: " + employee.getAge());
            }
        }else{
            System.out.println("查询数据为空");
        }

    }

    @Test
    public void TestfindByNameInOrAgeLessThan(){
//        employeeRepository = (EmployeeRepository)cxt.getBean("employeeRepository");
        List<String> names = new ArrayList<String>();
        names.add("test1");
        names.add("test2");
        names.add("test3");
        List<Employee> employees = employeeRepository.findByNameInOrAgeLessThan(names,22);
        if( employees != null  && employees.size() > 0){
            for (Employee employee : employees) {
                System.out.println("Id: " + employee.getId() +
                        "  name: " + employee.getName() +
                        "  age: " + employee.getAge());
            }
        }else{
            System.out.println("查询数据为空");
        }

    }
    @Test
    public void TestfindByNameInAndAgeLessThan(){
//        employeeRepository = (EmployeeRepository)cxt.getBean("employeeRepository");
        List<String> names = new ArrayList<String>();
        names.add("test1");
        names.add("test2");
        names.add("test3");
        List<Employee> employees = employeeRepository.findByNameInAndAgeLessThan(names,22);
        if( employees != null  && employees.size() > 0){
            for (Employee employee : employees) {
                System.out.println("Id: " + employee.getId() +
                        "  name: " + employee.getName() +
                        "  age: " + employee.getAge());
            }
        }else{
            System.out.println("查询数据为空");
        }

    }

    @Test
    public void TestgetEmployeeByMaxId(){
//        employeeRepository = (EmployeeRepository)cxt.getBean("employeeRepository");

        Employee employee = employeeRepository.getEmployeeByMaxId();
        if( employee == null){
            System.out.println("查询数据为空");
        }else{
            System.out.println("Id: " + employee.getId() +
                    "  name: " + employee.getName() +
                    "  age: " + employee.getAge());
        }

    }

    @Test
    public void TestqueryParamsl(){
//        employeeRepository = (EmployeeRepository)cxt.getBean("employeeRepository");
        List<Employee> employees = employeeRepository.queryParamsl("RLiBin",23);
        if( employees != null  && employees.size() > 0){
            for (Employee employee : employees) {
                System.out.println("Id: " + employee.getId() +
                        "  name: " + employee.getName() +
                        "  age: " + employee.getAge());
            }
        }else{
            System.out.println("查询数据为空");
        }
    }

    @Test
    public void TestqueryParamsl2() {
//        employeeRepository = (EmployeeRepository)cxt.getBean("employeeRepository");
        List<Employee> employees = employeeRepository.queryParamsl2("RLiBin", 23);
        if (employees != null && employees.size() > 0) {
            for (Employee employee : employees) {
                System.out.println("Id: " + employee.getId() +
                            "  name: " + employee.getName() +
                            "  age: " + employee.getAge());
            }
        } else {
                System.out.println("查询数据为空");
        }
    }


    @Test
    public void TestqueryLike1() {
//        employeeRepository = (EmployeeRepository)cxt.getBean("employeeRepository");
        List<Employee> employees = employeeRepository.queryLike1("test");
        if (employees != null && employees.size() > 0) {
            for (Employee employee : employees) {
                System.out.println("Id: " + employee.getId() +
                        "  name: " + employee.getName() +
                        "  age: " + employee.getAge());
            }
        } else {
            System.out.println("查询数据为空");
        }
    }


    @Test
    public void TestqueryLike2() {
//        employeeRepository = (EmployeeRepository)cxt.getBean("employeeRepository");
        List<Employee> employees = employeeRepository.queryLike2("test1");
        if (employees != null && employees.size() > 0) {
            for (Employee employee : employees) {
                System.out.println("Id: " + employee.getId() +
                        "  name: " + employee.getName() +
                        "  age: " + employee.getAge());
            }
        } else {
            System.out.println("查询数据为空");
        }
    }
    @Test
    public void TestgetCount() {
//        employeeRepository = (EmployeeRepository)cxt.getBean("employeeRepository");
        int count = (int) employeeRepository.getCount();
        System.out.println("count: "+count);
    }
}

4-5 更新操作整合事务使用

更新及删除操作整合事务的使用

  1. @Modifying注解使用

  2. @Modifying结合@Query("update Employee o set o.age= :age where o.id= :id ")注解执行更新操作

  3. @Transaction在Spring Data中的使用
    在EmployeeRepository添加新的查询
    根据id更新年龄

    @Modifying
    @Query("update Employee o set o.age= :age where o.id= :id ")
    public void update(@Param(“id”) Integer id, @Param(“age”) Integer age);

在EmployeeRepositoryTest加入测试

@Test
public void TestUpdate(){
employeeRepository.update(5,30);
}

报错:

Caused by:

javax.persistence.TransactionRequiredException: Executing an update/delete query

缺少事务
事务一般专门新建一个包 service,多次调用DAO,新建一个类EmployeeService

package com.imooc.service;

import com.imooc.repository.EmployeeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;

@Service  
public class EmployeeService {

    @Autowired
    private EmployeeRepository employeeRepository;
    @Transactional
    public void update(Integer id, Integer age){
        employeeRepository.update(id, age);

    }
}

在对应的位置创建service包,EmployeeServiceTest类

package com.imooc.Service;

import com.imooc.repository.EmployeeRepository;
import com.imooc.service.EmployeeService;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class EmployeeServiceTest {
    private ApplicationContext cxt =null ;
    private EmployeeService employeeService = null ;

    @Before
    public void setup(){
        cxt = new ClassPathXmlApplicationContext("beansnew.xml");
        employeeService = cxt.getBean(EmployeeService.class);
        System.out.println("setup");
    }
    @After
    public void tearDown(){
        cxt = null ;
        System.out.println("tearDown");

    }

    @Test
    public void Testupdate (){
//        employeeRepository = (EmployeeRepository)cxt.getBean("employeeRepository");
        employeeService.update(5,30);

    }
}

事务在Spring data中使用
1.事务一般是在service层
2.@Query @Modifying @Transactional的综合使用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值