3. Spring Boot SQL Databases

说明

  • 嵌入式数据库

    使用内存中的嵌入式数据库开发应用程序通常很方便。显然,内存数据库不提供持久存储。您需要在应用程序启动时填充数据库,并在应用程序结束时准备丢弃数据。

  • Spring Boot 会自动配置H2,HSQL,Derby 数据库,只需要将依赖添加到 POM 文件中,本例采用H2


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


    org.hsqldb
    h2
    runtime

  • Spring Boot 会自动配置 DataSource 链接池,只需要在项目配置文件(application.properties)设置一些属性,如下
spring.datasource.url=jdbc:mysql://localhost/test
spring.datasource.username=dbuser
spring.datasource.password=dbpass
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
  • Spring Boot 默认采用 Hibernate 作为 JPA 实现

Spring Data JPA Repositories

src/
 +- main/
     +- java/
         +- com/
             +- lee/
                 +- springbootdemo/
                     +- pojo/
                         +- City.java
                     +- repository/
                         +- CityRepository.java
                     +- controller/
                         +- CityRestController.java
                     +- SpringBootDemoApplication.java
     +- resources/
         +- 

City.java

@Entity
public class City implements Serializable {

    @Id
    @GeneratedValue
    private Long id;

    @Column(nullable = false)
    private String name;

    @Column(nullable = false)
    private String state;

    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 String getState() { return state; }
    public void setState(String state) { this.state = state; }
}

CityRepository.java

public interface CityRepository extends JpaRepository {}

CityRestController.java

@RestController
@RequestMapping("/city")
public class CityRestController {

    @Autowired
    private CityRepository cityRepository;

    @GetMapping("/{name}/{state}")
    public City city(@PathVariable String name, @PathVariable String state) {
        City city = new City();
        city.setName(name);
        city.setState(state);

        return cityRepository.save(city);
    }
}

运行应用程序,输入url,如下


3. Spring Boot SQL Databases_第1张图片
SpringBootJpa.png

参考

  1. Spring Boot Data 官方文档

上一篇:2. Spring Boot 编写 Controller
下一篇:4. Spring Boot Caching Redis

你可能感兴趣的:(3. Spring Boot SQL Databases)