3. Spring Boot SQL Databases

2018-10-22  本文已影响0人  LeeSpringFly

说明

<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.datasource.url=jdbc:mysql://localhost/test
spring.datasource.username=dbuser
spring.datasource.password=dbpass
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

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

上一篇下一篇

猜你喜欢

热点阅读