【笔记】springboot使用Spring-data-jpa
发布日期:2021-05-15 23:14:42 浏览次数:11 分类:精选文章

本文共 4271 字,大约阅读时间需要 14 分钟。

Spring Data JPA 开发指南

1. 依赖管理

Spring Data JPA 是 Spring Boot 开发中核心数据访问模块之一,其依赖于 Hibernate ORM框架。通过整合 Hibernate 后,开发者可以利用面向对象的特性,将domain对象变换为数据库表结构。以下是 Spring Data JPA 的基本依赖配置:

org.springframework.boot
spring-boot-starter-data-jpa

2. 数据库配置

在应用程序启动之前,需要配置数据库连接信息。对于嵌套式数据库,则无需特殊配置。以下是使用MySQL的配置示例:

spring.datasource.url=jdbc:mysql://localhost:3306/data1spring.datasource.username=rootspring.datasource.password=rootspring.datasource.driver-class-name=com.mysql.jdbc.Driver

注意:spring.jpa.properties.hibernate.hbm2ddl.auto 这一配置决定了数据库表结构的生命周期。如果选用 create 模式,启动时会删除已有表并重新创建,这可能导致数据丢失。因此,默认使用 create-drop 模式:

spring.jpa.properties.hibernate.hbm2ddl.auto=create-drop

这意味着数据 mev Kaplan 的每次加载都会根据 domain 类动态创建表结构,但在 session factory 提交后会自动删除表。这是常用配置方式。

3. 实体定义

创建一个简要的 User 实体类(实体类),包含主键 id、姓名 name 和年龄 age 属性。结合Hibernate的自动映射机制,将此domain对象映射到数据库表中:

@Entitypublic class User {    @Id    @GeneratedValue(strategy = GenerationType.IDENTITY)    private Long id;    @Column(nullable = false)    private String name;    @Column(nullable = false)    private Integer age;    // ... 省略 setter 和 getter 方法}

4. 数据访问接口

在 Spring Data JPA 中,为实体定义接口以实现数据访问。例如,定义一个 UserRepository 接口:

public interface UserRepository extends JpaRepository
{ User findByName(String name); User findByNameAndAge(String name, Integer age); @Query("from User u where u.name=:name") User findUser(@Param("name") String name);}

JpaRepository 提供了基础的 CRUD 操作,同时通过自定义方法实现定制查询。

5. 单元测试

创建单元测试来验证数据访问接口是否正确:

@RunWith(SpringJUnit4ClassRunner.class)@SpringApplicationConfiguration(Application.class)public class ApplicationTests {    @Autowired    private UserRepository userRepository;    @Test    public void test() throws Exception {        // 创建多条记录        userRepository.save(new User("AAA", 10));        userRepository.save(new User("BBB", 20));        // ... 类似操作        // 验证查询结果        assertEquals(10, userRepository.findAll().size());    }}

6. 多数据源配置

在复杂应用场景中,可能需要处理多个数据源。可以使用独立的数据源进行读写分离:

@Configurationpublic class DataSourceConfig {    @Bean(name = "primaryDataSource")    @Qualifier("primaryDataSource")    @ConfigurationProperties(prefix = "spring.datasource.primary")    public DataSource primaryDataSource() {        return DataSourceBuilder.create().build();    }    @Bean(name = "secondaryDataSource")    @Qualifier("secondaryDataSource")    @ConfigurationProperties(prefix = "spring.datasource.secondary")    public DataSource secondaryDataSource() {        return DataSourceBuilder.create().build();    }}

对应的 application.properties 配置:

spring.datasource.primary.url=jdbc:mysql://localhost:3306/test1spring.datasource.primary.username=rootspring.datasource.primary.password=rootspring.datasource.primary.driver-class-name=com.mysql.jdbc.Driverspring.datasource.secondary.url=jdbc:mysql://localhost:3306/test2spring.datasource.secondary.username=rootspring.datasource.secondary.password=rootspring.datasource.secondary.driver-class-name=com.mysql.jdbc.Driver

7. JdbcTemplate 支持

对于配合使用 Spring Data JPA 的场景,可以配置 JdbcTemplate 进行特定数据库操作:

@Bean(name = "primaryJdbcTemplate")public JdbcTemplate primaryJdbcTemplate(@Qualifier("primaryDataSource") DataSource dataSource) {    return new JdbcTemplate(dataSource);}@Bean(name = "secondaryJdbcTemplate")public JdbcTemplate secondaryJdbcTemplate(@Qualifier("secondaryDataSource") DataSource dataSource) {    return new JdbcTemplate(dataSource);}

8. 测试示例

通过测试验证数据库操作:

@RunWith(SpringJUnit4ClassRunner.class)@SpringApplicationConfiguration(Application.class)public class ApplicationTests {    @Autowired    @Qualifier("primaryJdbcTemplate")     private JdbcTemplate jdbcTemplate1;    @Autowired    @Qualifier("secondaryJdbcTemplate")    private JdbcTemplate jdbcTemplate2;    @Before    public void setUp() {        jdbcTemplate1.update("DELETE FROM USER");        jdbcTemplate2.update("DELETE FROM USER");    }    @Test    public void test() throws Exception {        // 向第一个数据源插入数据        jdbcTemplate1.update("insert into user(id, name, age) values(?, ?, ?)", 1, "AAA", 20);        // 验证数据是否成功        assertEquals("2", jdbcTemplate1.queryForObject("select count(1) from user", String.class));    }}

以上内容涵盖了 Spring Data JPA 的核心配置和使用方法,包括依赖管理、数据库配置、实体定义、数据访问接口、单元测试、多数据源支持及 JdbcTemplate 配置。希望以上内容能为开发提供有价值的参考。

上一篇:【笔记】c++中opencv的使用
下一篇:【pytorch】pytorch自定义训练vgg16和测试数据集 微调resnet18全连接层

发表评论

最新留言

表示我来过!
[***.240.166.169]2025年04月16日 15时24分55秒