Spring-Data-JDBC
对比mybatis与mybatis-plus,spring-data-jdbc更适合在领域驱动设计(DDD)的架构下实现持久化存储。
使用教程
- 建表
CREATE TABLE `person` (
`id` bigint(255) NOT NULL,
`name` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
- 导入maven依赖
<dependencies>
<!-- Spring-Data-JDBC-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jdbc</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
</dependencies>
- 在domain层创建
entity
、repository
两个package
- 编写实体类(实体类 != POJO),一个实体类必有一个
@Id
注解的聚合标识(类似于于主键,但是是从DDD的角度理解)
@Builder
@NoArgsConstructor
@Data
public class Person {
public Person(long id, String name) {
this.id = id;
this.name = name;
}
@Id
long id;
String name;
}
- 编写 EntityRepository接口 继承
PagingAndSortingRepository<Person,Long>
public interface PeopleRepository extends PagingAndSortingRepository<Person,Long> {
List<Person> findByName(String name);
}
- 编写Test类进行测试
@SpringBootTest
class PeopleRepositoryTest {
@Autowired
PeopleRepository peopleRepository;
@Test
public void test() {
Person person = new Person();
person.setId(1);
person.setName("小明");
Person savePerson = peopleRepository.save(person);
assertThat(savePerson.getId()).isNotNull();
savePerson.setName("xiaoping");
peopleRepository.save(savePerson);
Optional<Person> reloaded = peopleRepository.findById(savePerson.getId());
List<Person> list = peopleRepository.findByName("xiaoping");
list.forEach(
(e)-> System.out.println(e.getName())
);
assertThat(reloaded).isNotEmpty();
System.out.println(reloaded.get().getName());
}
}
总结。刚入门学习,spring-data-jdbc非常的简洁且功能强大,使用方便,拥有ORM与JDBC的优点,是DDD架构下非常实用的持久层框架,浅尝使用,希望国内不在只是mybatis的唯一。
这里附上官方文档地址: