Java笔记:JDBC传统数据库访问和SpringData入门(3)

简介: Java笔记:JDBC传统数据库访问和SpringData入门

四、SpringData JPA 进阶

Responsitory类的定义

public interface Repository<T,ID extends Serializable>{
}

1)Responsitory是一个空接口,标记接口

没有包含方法的声明接口

2)我们定义的接口

public interface EmployeeRepository extends Repository<Employee, Integer>{
}

表示此接口纳入spring管理,需按一定规则定义方法


或者使用注解方式定义


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

public interface EmployeeRepository {


}


Repository继承体系


CrudRepository                    # 实现了CRUD相关方法

   - PagingAndSortingRepository  # 实现了分页排序方法

       - JpaRepository           # 实现了Jpa规范相关方法


JpaSpecificationExecutor

Repository查询方法定义规则和使用

package com.mouday.repository;
import com.mouday.domain.Employee;
import org.springframework.data.repository.RepositoryDefinition;
import java.util.List;
@RepositoryDefinition(domainClass = Employee.class, idClass = Integer.class)
public interface EmployeeRepository
{
    // where name = ?
    public Employee findByName(String name);
    // where name like ?% and age > ?
    List<Employee> findByNameStartingWithAndAgeGreaterThan(String name, Integer age);
    // where name like %? and age > ?
    List<Employee> findByNameEndingWithAndAgeGreaterThan(String name, Integer age);
}

测试

package com.mouday.repository;
import com.mouday.domain.Employee;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.List;
public class EmployeeRepositoryTest {
    ApplicationContext context = null;
    EmployeeRepository repository = null;
    @Before
    public void setup() {
        System.out.println("StudentDaoSpringJdbcImplTest.setup");
        context = new ClassPathXmlApplicationContext("beans-jpa.xml");
        repository = context.getBean(EmployeeRepository.class);
    }
    @After
    public void tearDown() {
        System.out.println("StudentDaoSpringJdbcImplTest.tearDown");
        context = null;
    }
    @Test
    public void testFindByName() {
        Employee employee = repository.findByName("刘备");
        System.out.println(employee);
    }
    @Test
    public void testFindByNameStartingWithAndAgeGreaterThan() {
        List<Employee> employees = repository.findByNameStartingWithAndAgeGreaterThan("刘", 10);
        System.out.println(employees);
    }
    @Test
    public void testFindByNameEndingWithAndAgeGreaterThan() {
        List<Employee> employees = repository.findByNameEndingWithAndAgeGreaterThan("羽", 10);
        System.out.println(employees);
    }
}

命名规则的弊端

  • 方法名比较长
  • 复杂查询很难实现

Query查询注解

1、在Respository方法中使用,不需要遵循查询方法命名规则

2、只需要将@Query定义在Respository中的方法之上即可

3、命名参数及索引参数的使用

4、本地查询

package com.mouday.repository;
import com.mouday.domain.Employee;
import org.springframework.data.jpa.repository.Query;
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
{
    // where name = ?
    public Employee findByName(String name);
    // where name like ?% and age > ?
    List<Employee> findByNameStartingWithAndAgeGreaterThan(String name, Integer age);
    // where name like %? and age > ?
    List<Employee> findByNameEndingWithAndAgeGreaterThan(String name, Integer age);
    // where name in (?...) and age > ?
    List<Employee> findByNameInAndAgeGreaterThan(List<String> names, Integer age);
    @Query("select o from Employee o where id = (select max(id) from Employee t1)")
    Employee getEmployeeByMaxId();
    @Query("select o from Employee o where o.name = ?1 and o.age =?2")
    Employee getEmployeeByName1(String name, Integer age);
    @Query("select o from Employee o where o.name = :name and o.age = :age")
    Employee getEmployeeByName2(@Param("name") String name, @Param("age") Integer age);
    @Query("select o from Employee o where o.name like %?1%")
    Employee getEmployeeByNameLike1(String name);
    @Query("select o from Employee o where o.name like %:name%")
    Employee getEmployeeByNameLike2(@Param("name") String name);
    // 开启原生查询
    @Query(nativeQuery=true, value = "select count(*) from employee")
    Integer getEmployeeCount();
}

测试

package com.mouday.repository;
import com.mouday.domain.Employee;
import org.junit.After;
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 {
    ApplicationContext context = null;
    EmployeeRepository repository = null;
    @Before
    public void setup() {
        System.out.println("StudentDaoSpringJdbcImplTest.setup");
        context = new ClassPathXmlApplicationContext("beans-jpa.xml");
        repository = context.getBean(EmployeeRepository.class);
    }
    @After
    public void tearDown() {
        System.out.println("StudentDaoSpringJdbcImplTest.tearDown");
        context = null;
    }
    @Test
    public void testFindByName() {
        Employee employee = repository.findByName("刘备");
        System.out.println(employee);
    }
    @Test
    public void testFindByNameStartingWithAndAgeGreaterThan() {
        List<Employee> employees = repository.findByNameStartingWithAndAgeGreaterThan("刘", 10);
        System.out.println(employees);
    }
    @Test
    public void testFindByNameEndingWithAndAgeGreaterThan() {
        List<Employee> employees = repository.findByNameEndingWithAndAgeGreaterThan("羽", 10);
        System.out.println(employees);
    }
    @Test
    public void testFindByNameInAndAgeGreaterThan() {
        List<String> names = new ArrayList<>();
        names.add("刘备");
        names.add("张飞");
        List<Employee> employees = repository.findByNameInAndAgeGreaterThan(names, 10);
        System.out.println(employees);
    }
    @Test
    public void testGetEmployeeByMaxId() {
        Employee employee = repository.getEmployeeByMaxId();
        System.out.println(employee);
    }
    @Test
    public void testGetEmployeeByName1() {
        Employee employee = repository.getEmployeeByName1("刘备", 40);
        System.out.println(employee);
    }
    @Test
    public void testGetEmployeeByName2() {
        Employee employee = repository.getEmployeeByName2("刘备", 40);
        System.out.println(employee);
    }
    @Test
    public void testGetEmployeeByNameLike1() {
        Employee employee = repository.getEmployeeByNameLike1("刘");
        System.out.println(employee);
    }
    @Test
    public void testGetEmployeeByNameLike2() {
        Employee employee = repository.getEmployeeByNameLike2("刘");
        System.out.println(employee);
    }
    @Test
    public void testGetEmployeeCount() {
        Integer total = repository.getEmployeeCount();
        System.out.println(total);
    }
}

事务在 Spring Data 中的应用:

  1. 事务一般是在 service 层,保证事务的完整性

2)注解的使用

@Query 查询

@Modifying 修改 更新和删除必用

@Transactional 事务 更新和删除必用

package com.mouday.repository;
import com.mouday.domain.Employee;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
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
{
    // 修改操作
    @Modifying
    @Query("update Employee o set o.name = :name where id = :id")
    void updateNameById(@Param("id") Integer id, @Param("name") String name);
}
package com.mouday.service;
import com.mouday.repository.EmployeeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Service;
import javax.transaction.Transactional;
@Service
public class EmployeeService {
    @Autowired
    private EmployeeRepository repository;
    @Transactional
    public void update(Integer id, String name){
        repository.updateNameById(id, name);
    }
}

测试

package com.mouday.service;
import com.mouday.repository.EmployeeRepository;
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 {
    ApplicationContext context = null;
    EmployeeService service = null;
    @Before
    public void setup() {
        System.out.println("StudentDaoSpringJdbcImplTest.setup");
        context = new ClassPathXmlApplicationContext("beans-jpa.xml");
        service = context.getBean(EmployeeService.class);
    }
    @After
    public void tearDown() {
        System.out.println("StudentDaoSpringJdbcImplTest.tearDown");
        context = null;
    }
    @Test
    public void testUpdate(){
        service.update(1, "曹操");
    }
}
相关文章
|
6月前
|
SQL 关系型数据库 数据库
Python SQLAlchemy模块:从入门到实战的数据库操作指南
免费提供Python+PyCharm编程环境,结合SQLAlchemy ORM框架详解数据库开发。涵盖连接配置、模型定义、CRUD操作、事务控制及Alembic迁移工具,以电商订单系统为例,深入讲解高并发场景下的性能优化与最佳实践,助你高效构建数据驱动应用。
733 7
|
6月前
|
SQL Java 数据库连接
除了JDBC,还有哪些常见的数据库访问技术?
除了JDBC,还有哪些常见的数据库访问技术?
531 2
|
SQL Java 中间件
【YashanDB知识库】yasdb jdbc驱动集成BeetISQL中间件,业务(java)报autoAssignKey failure异常
在BeetISQL 2.13.8版本中,客户使用batch insert向yashandb表插入数据并尝试获取自动生成的sequence id时,出现类型转换异常。原因是beetlsql在prepareStatement时未指定返回列,导致yashan JDBC驱动返回rowid(字符串),与Java Bean中的数字类型tid不匹配。此问题影响业务流程,使无法正确获取sequence id。解决方法包括:1) 在batchInsert时不返回自动生成的sequence id;2) 升级至BeetISQL 3,其已修正该问题。
【YashanDB知识库】yasdb jdbc驱动集成BeetISQL中间件,业务(java)报autoAssignKey failure异常
|
存储 Java 开发者
【潜意识Java】深入详细理解分析Java中的toString()方法重写完整笔记总结,超级详细。
本文详细介绍了 Java 中 `toString()` 方法的重写技巧及其重要
845 10
【潜意识Java】深入详细理解分析Java中的toString()方法重写完整笔记总结,超级详细。
|
SQL druid Oracle
【YashanDB知识库】yasdb jdbc驱动集成druid连接池,业务(java)日志中有token IDENTIFIER start异常
客户Java日志中出现异常,影响Druid的merge SQL功能(将SQL字面量替换为绑定变量以统计性能),但不影响正常业务流程。原因是Druid在merge SQL时传入null作为dbType,导致无法解析递归查询中的`start`关键字。
|
Java 数据库连接 数据库
springboot java.lang.ClassNotFoundException: dm.jdbc.driver.DmDriver应该如何解决
通过上述步骤,可以有效解决Spring Boot项目中遇到的 `java.lang.ClassNotFoundException: dm.jdbc.driver.DmDriver`问题。确保在项目中正确添加达梦数据库的JDBC驱动依赖,并在配置文件中正确配置数据源信息,是解决此问题的关键。通过这些方法,可以确保Spring Boot项目能够正确连接达梦数据库并正常运行。
2559 31
|
SQL Java 关系型数据库
使用 JDBC 实现 Java 数据库操作
JDBC(Java Database Connectivity)是 Java 提供的数据库访问技术,允许通过 SQL 语句与数据库交互。本文详细介绍了 JDBC 的使用方法,包括环境准备、编程步骤和完整示例。
1165 7
|
SQL Java 数据库连接
【潜意识Java】Java中JDBC过时方法的替代方案以及JDBC为什么过时详细分析
本文介绍了JDBC中一些常见过时方法及其替代方案。
418 5
|
前端开发 JavaScript Java
Java构建工具-maven的复习笔记【适用于复习】
这篇文档由「潜意识Java」创作,主要介绍Maven的相关知识。内容涵盖Maven的基本概念、作用、项目导入步骤、依赖管理(包括依赖配置、代码示例、总结)、依赖传递、依赖范围以及依赖的生命周期等七个方面。作者擅长前端开发,秉持“得之坦然,失之淡然”的座右铭。期待您的点赞、关注和收藏,这将是作者持续创作的动力! [个人主页](https://blog.csdn.net/weixin_73355603?spm=1000.2115.3001.5343)
419 3