springboot入门_数据库访问_jpa
本文记录使用jpa访问数据库。
创建spring boot项目,并在pom文件中添加相应的依赖包。
1 <dependency> 2 <groupId>org.springframework.boot</groupId> 3 <artifactId>spring-boot-starter-data-jpa</artifactId> 4 </dependency> 5 <dependency> 6 <groupId>org.springframework.boot</groupId> 7 <artifactId>spring-boot-starter-web</artifactId> 8 </dependency> 9 10 <dependency> 11 <groupId>mysql</groupId> 12 <artifactId>mysql-connector-java</artifactId> 13 <scope>runtime</scope> 14 </dependency>
在resources路径下创建yml文件,并配置数据库连接信息,JPA默认使用hibernate做的实现,所以也需要配置hibernate个别参数项,yml文件如下:
1 spring: 2 datasource: 3 url: jdbc:mysql://localhost:3306/test 4 username: root 5 password: 123456 6 jpa: 7 show-sql: true 8 hibernate: 9 ddl-auto: update 10 database: mysql
创建实体类,与数据库表做映射
1 @Entity 2 @Table(name="t_city") 3 public class City { 4 5 @Id 6 @GeneratedValue(strategy = GenerationType.AUTO) 7 private Integer id; 8 @Column(name = "city_code", length = 50) 9 private String cityCode; 10 @Column(name = "city_name", length = 50) 11 private String cityName; 12 //省略get和set方法 13 }
创建dao接口,并继承JpaRepository
1 @Repository 2 public interface CityRepository extends JpaRepository<City, Long> { 3 4 /** 5 * 查询所有 6 * @return 7 */ 8 List<City> findAll(); 9 10 /** 11 * 根据ID查询 12 * @param id 13 * @return 14 */ 15 @Query("from City where id = :id") 16 City findById(@Param("id") Integer id); 17 18 @Transactional 19 @Query("update City set city_name=?1 where city_code = ?2") 20 @Modifying 21 int update(String name, String code); 22 23 }
创建一个service
1 @Service 2 public class CityService { 3 4 @Autowired 5 private CityRepository cityRepository; 6 7 public int add(City city){ 8 Object obj = cityRepository.save(city); 9 System.out.println(obj.toString()); 10 return 1; 11 } 12 13 public void delete(long id){ 14 cityRepository.deleteById(id); 15 } 16 17 public void update(String name, String code){ 18 cityRepository.update(name, code); 19 } 20 21 public List<City> findAllCity(){ 22 return cityRepository.findAll(); 23 } 24 25 public City findById(Integer id){ 26 return cityRepository.findById(id); 27 } 28 29 }
创建controller,提供api方法测试
@RestController @RequestMapping("data/jpa/city") public class CityController { @Autowired private CityService cityService; @PutMapping public String add(@RequestBody City city){ System.out.println(city.toString()); cityService.add(city); return "success"; } @DeleteMapping(value="/{id}") public String delete(@PathVariable String id){ cityService.delete(Long.valueOf(id)); return "success"; } @PostMapping public String update(@RequestBody City city){ cityService.update(city.getCityName(), city.getCityCode()); return "success"; } @GetMapping("/{id}") public City findById(@PathVariable("id") int id){ City city = cityService.findById(id); return city; } @GetMapping("/list") public List<City> findAllCity(){ List<City> cityList = cityService.findAllCity(); return cityList; } }
对于一般的增删改查方法,我们也可在再dao中继承CrudRepository来实现对应的方法。一般在开发中,我们的业务也会用到分页排序等功能,这JPA也做了支持,我们可以通过继承PagingAndSortingRepository来实现。