02 Spring Data
准备工作
创建项目并添加数据库依赖
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>创建数据库
create database spring_data;
use spring_data;
create table student (
id int not null auto_increment,
name varchar(32) not null,
age int not null,
primary key(id)
);
insert into student (name, age) values ("张三", 22);创建实体类和访问接口
新增实体类 Student:
新增访问接口 StudentDAO:
传统方式访问数据库 JDBC
Connection
Statement
ResultSet
Test Case
配置文件 db.properties
配置文件 db.properties:
开发 JDBCUtil 工具类
工具类:获取 Connection,关闭 Connection、Statement、ResultSet。
实现访问接口
实现访问接口 StudentDAOImpl:
原始的通过 JDBC 访问数据库太复杂,模板代码太大太冗余。
Spring JdbcTemplate
引入依赖
配置文件 beans.xml
配置文件 beans.xml:
实现访问接口
实现访问接口 StudentDAOSpringJdbcImpl:
测试用例
Spring Data
引入依赖
配置文件 beans.xml
创建实体类和仓储
上面传统方式是先建数据表,这里是创建实体类后自动生成数据表,注意对比这里使用的是包装类型 Integer 而之前是基本类型 int。
创建 EmployeeRepository:
测试用例
Repository 查询方法定义规则
Repository 类的定义:
Repository 是一个空接口,也是标记接口,即没有任何方法声明的接口。继承这个接口后就会被纳入 spring 管理。
除了使用继承方式外,还可以使用注解:
Repository 子接口:
CrudRepository:继承 Repository,实现 CRUD 相关方法
PagingAndSortingRepository:继承 CrudRepository,实现分页排序相关方法
JpaRepository:继承 CrudRepository,实现 JPA 相关方法
Repository 查询方法定义规则:

示例:
对于按照方法命名规则来使用的话,有弊端:
方法名会比较长:约定大于配置
对于一些复杂的查询,很难实现
Query 注解
不需要遵循查询方法命名规则。
排序:
最后更新于
这有帮助吗?