【Spring Data Access】 Spring jdbc Embedded Database

本文介绍如何使用Spring的xml配置文件设置内嵌数据库,包括H2、HSQL和Derby等,并通过具体示例展示schema.sql和data.sql的使用,以及如何通过JdbcTemplate查询数据。

Spring jdbc Embedded Database

内置的数据库对测试很有用,spring默认提供了H2, HSQL, Derby等类型的数据支撑,

下面介绍基于xml的配置方式,配置如下:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:jdbc="http://www.springframework.org/schema/jdbc" xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd">

    <jdbc:embedded-database id="dataSource" generate-name="true" type="HSQL"/>

    <!--
        The ignore-failures option can be set to
         NONE (the default), DROPS (ignore failed drops), or ALL (ignore all failures).

     Each statement should be separated by ; or a new line if the ;
      character is not present at all in the script.
       You can control that globally or script by script, as the following example shows:
     -->
    <jdbc:initialize-database data-source="dataSource" enabled="true" ignore-failures="DROPS" separator=";">
        <!-- The script locations can also be patterns with wildcards in the usual
         Ant style used for resources in Spring (for example, classpath*:/com/foo/**/sql/*-data.sql).
         If you use a pattern, the scripts are run in the lexical order of their URL or filename.
        -->
        <jdbc:script location="classpath:schema.sql" separator=";"/>
        <jdbc:script location="classpath:data.sql"/>
    </jdbc:initialize-database>
</beans>

结合具体的例子来感受一下:

1 schema.sql

create table user(
id INTEGER GENERATED BY DEFAULT AS IDENTITY(START WITH 100, INCREMENT BY 1) PRIMARY KEY,
name varchar(20),
age int);

2 data.sql

insert into user(name, age) values('alice', 20),('bob', 18);

3 User.java

public class User {
    private Long id;
    private String name;
    private int age;

    public User() {
    }

    public User(Long id, String name) {
        this.id = id;
        this.name = name;
    }

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

4 EmbeddedDatabaseSample.java

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;

import javax.sql.DataSource;

/**
 * @author jiangjian
 */
public class EmbeddedDatabaseSample {
    public static void main(String[] args) {
        ApplicationContext ac = new ClassPathXmlApplicationContext("classpath:dataaccess/jdbc/step14_embedded_database/spring.xml");
        JdbcTemplate jdbcTemplate = new JdbcTemplate(ac.getBean(DataSource.class));
        jdbcTemplate.query("select * from user", (rs, rowNum) -> {
            User user = new User();
            user.setId(rs.getLong("id"));
            user.setName(rs.getString("name"));
            user.setAge(rs.getInt("age"));
            return user;
        }).forEach(System.out::println);
    }
}

结果如下:
在这里插入图片描述

### Spring Data JPA Getting Started Guide To begin using Spring Data JPA, it is essential to understand its core concepts and setup process. Below is a comprehensive overview of starting with Spring Data JPA. #### Setting Up Your Project Ensure your project includes the necessary dependencies for Spring Data JPA. This can be achieved by adding the appropriate Maven or Gradle dependency. For example, in Maven: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> ``` This dependency pulls in all required libraries for working with Spring Data JPA[^5]. #### Defining Entity Classes Entity classes represent database tables. These must be annotated with `@Entity` from the Java Persistence API (JPA). Each entity should also define fields corresponding to table columns along with getter and setter methods. Here's an illustrative example: ```java import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; @Entity public class Person { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String name; private int age; // Getters and Setters } ``` The above code defines a simple `Person` entity mapped to a relational database table[^3]. #### Creating Repository Interfaces Spring Data JPA simplifies data access through repository interfaces. A typical repository extends either `CrudRepository` or `JpaRepository`. The framework automatically generates implementations based on method signatures defined within these interfaces. Here’s an example of defining a custom repository for the `Person` entity: ```java import org.springframework.data.jpa.repository.JpaRepository; public interface PersonRepository extends JpaRepository<Person, Long> { List<Person> findByName(String name); } ``` In this case, the `findByName` query method will search entities matching the provided name parameter without requiring explicit SQL queries[^3]. Additionally, when creating repositories like `PersonRepository`, ensure they are correctly linked to their respective domain objects as described earlier[^2]. #### Configuring Database Connection Configure the application properties file (`application.properties`) to establish connections between your app and databases such as MySQL, PostgreSQL etc., specifying details including driver class names, URLs, usernames, passwords among others. Example configuration snippet below demonstrates connecting to H2 embedded DB during development phase only: ```properties spring.datasource.url=jdbc:h2:mem:testdb spring.datasource.driverClassName=org.h2.Driver spring.datasource.username=sa spring.datasource.password=password spring.jpa.database-platform=org.hibernate.dialect.H2Dialect ``` With everything configured properly according to official guides mentioned previously [^1], you're now ready to leverage powerful features offered via Spring Data JPA! --- 问题
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值