美文网首页
3. Spring Boot SQL Databases

3. Spring Boot SQL Databases

作者: LeeSpringFly | 来源:发表于2018-10-22 15:05 被阅读0次

说明

  • 嵌入式数据库

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

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

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
    <groupId>org.hsqldb</groupId>
    <artifactId>h2</artifactId>
    <scope>runtime</scope>
</dependency>
  • 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/
         +- <other resource>

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<City, Long> {}

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,如下


SpringBootJpa.png

参考

  1. Spring Boot Data 官方文档

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

相关文章

网友评论

      本文标题:3. Spring Boot SQL Databases

      本文链接:https://www.haomeiwen.com/subject/bjdgzftx.html