SpringData-JDBC学习笔记

Spring-Data-JDBC

对比mybatis与mybatis-plus,spring-data-jdbc更适合在领域驱动设计(DDD)的架构下实现持久化存储。

使用教程

  1. 建表
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;
  1. 导入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>
  1. 在domain层创建 entityrepository两个package
  2. 编写实体类(实体类 != 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;
}
  1. 编写 EntityRepository接口 继承 PagingAndSortingRepository<Person,Long>
public interface PeopleRepository  extends PagingAndSortingRepository<Person,Long> {
    List<Person> findByName(String name);
}
  1. 编写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的唯一。
这里附上官方文档地址:

官方文档地址

外网一个Spring-Data-JDBC写得非常好的博客


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值