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, "曹操");
    }
}
相关文章
|
2月前
|
SQL 关系型数据库 数据库
Python SQLAlchemy模块:从入门到实战的数据库操作指南
免费提供Python+PyCharm编程环境,结合SQLAlchemy ORM框架详解数据库开发。涵盖连接配置、模型定义、CRUD操作、事务控制及Alembic迁移工具,以电商订单系统为例,深入讲解高并发场景下的性能优化与最佳实践,助你高效构建数据驱动应用。
378 7
|
2月前
|
SQL Java 数据库连接
除了JDBC,还有哪些常见的数据库访问技术?
除了JDBC,还有哪些常见的数据库访问技术?
284 2
|
2月前
|
Java 开发工具
【Azure Storage Account】Java Code访问Storage Account File Share的上传和下载代码示例
本文介绍如何使用Java通过azure-storage-file-share SDK实现Azure文件共享的上传下载。包含依赖引入、客户端创建及完整示例代码,助你快速集成Azure File Share功能。
379 5
|
7月前
|
负载均衡 算法 关系型数据库
大数据大厂之MySQL数据库课程设计:揭秘MySQL集群架构负载均衡核心算法:从理论到Java代码实战,让你的数据库性能飙升!
本文聚焦 MySQL 集群架构中的负载均衡算法,阐述其重要性。详细介绍轮询、加权轮询、最少连接、加权最少连接、随机、源地址哈希等常用算法,分析各自优缺点及适用场景。并提供 Java 语言代码实现示例,助力直观理解。文章结构清晰,语言通俗易懂,对理解和应用负载均衡算法具有实用价值和参考价值。
大数据大厂之MySQL数据库课程设计:揭秘MySQL集群架构负载均衡核心算法:从理论到Java代码实战,让你的数据库性能飙升!
|
4月前
|
存储 安全 Java
java: 无法访问org.springframework.ldap.core.LdapTemplate
java: 无法访问org.springframework.ldap.core.LdapTemplate
159 9
|
8月前
|
NoSQL Java API
在Java环境下如何进行Redis数据库的操作
总的来说,使用Jedis在Java环境下进行Redis数据库的操作,是一种简单而高效的方法。只需要几行代码,就可以实现复杂的数据操作。同时,Jedis的API设计得非常直观,即使是初学者,也可以快速上手。
372 94
|
6月前
|
缓存 Java 数据库
Java 访问修饰符使用方法与组件封装方法详细说明
本文详细介绍了Java中访问修饰符(`public`、`private`、`protected`、默认)的使用方法,并结合代码示例讲解了组件封装的核心思想与实现技巧。内容涵盖数据封装、继承扩展、模块化设计与接口隔离等关键技术点,帮助开发者提升代码的可维护性与安全性,适用于Java初学者及进阶开发者学习参考。
155 1
|
8月前
|
Java 关系型数据库 MySQL
Java汽车租赁系统源码(含数据库脚本)
Java汽车租赁系统源码(含数据库脚本)
207 4
|
9月前
|
前端开发 JavaScript Java
[Java计算机毕设]基于ssm的OA办公管理系统的设计与实现,附源码+数据库+论文+开题,包安装调试
OA办公管理系统是一款基于Java和SSM框架开发的B/S架构应用,适用于Windows系统。项目包含管理员、项目管理人员和普通用户三种角色,分别负责系统管理、请假审批、图书借阅等日常办公事务。系统使用Vue、HTML、JavaScript、CSS和LayUI构建前端,后端采用SSM框架,数据库为MySQL,共24张表。提供完整演示视频和详细文档截图,支持远程安装调试,确保顺利运行。
403 17
|
9月前
|
存储 算法 安全
Java对象创建和访问
Java对象创建过程包括类加载检查、内存分配(指针碰撞或空闲列表)、内存初始化、对象头设置及初始化方法执行。访问方式有句柄和直接指针两种,前者稳定但需额外定位,后者速度快。对象创建涉及并发安全、垃圾回收等机制。
134 0
Java对象创建和访问

热门文章

最新文章