Spring Data JDBC 简单使用
Spring Data JDBC 简单使用
目录
因为想简化数据库查询函数的写法(相对 JbdcTemplate 而言),从而了解到 Spring Data JDBC (相对于 Spring Data JPA ,功能简单很多)。
1. 简单例子
代码1 User.java
代码2 UserRepository.java
2. 主键不设置 auto_increment
代码3 UserCallback.java
3. @MappedCollection
两张表要有相同内容的主键
4. 使用 JdbcTemplate 自定义操作
1. 定义 interface
2. 实现 interface ,Spring 搜索该 interface 的实现时,默认后缀为 Impl
3. 继承 interface ,相同函数「按继承的声明顺序」决定优先级
5. mappedCollection 测试
在文档中看到 Spring Data JDBC 支持 one-to-one relationship ,one-to-many relationship ,以为可以直接获取到外键关联表的数据,但经过简单测试后发现,貌似和 自己理解的有偏差。
经过测试后得到的结论:两张表要有相同内容的主键。
5.1. 数据库表
5.2. 表对应的 Java 对象
代码4 User.java
代码5 Role.java
5.3. 测试
用 CrudRepository.findById
,然后看执行的 SQL
5.3.1. 设置 user.account
为 @Id
1. @MappedCollection(idColumn = "id", keyColumn = "roleId")
2. @MappedCollection(idColumn = "id")
和 @MappedCollection(idColumn = "id", keyColumn = "roleId") 一样
3. @MappedCollection(idColumn = "roleId")
5.3.2. 设置 user.username
为 @Id
,并且 @MappedCollection(idColumn = "id")
5.3.3. 将 Role role
改为 Set<Role> role
会执行两次 SQL
两者传入的参数相同