SpringBoot与JPA集成:
简介
JPA是Java Persistence API的简称,中文名Java持久层API,是JDK 5.0注解或XML描述对象-关系表的映射关系,并将运行期的实体对象持久化到数据库中。

准备


Maven
Maven的依赖关系

目录结构

1 2 3 4 5 6 7 8
| package com.hph.springboot.repository;
import com.hph.springboot.entity.User; import org.springframework.data.jpa.repository.JpaRepository;
public interface UserRepository extends JpaRepository<User,Integer> { }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43
| package com.hph.springboot.entity;
import javax.persistence.*;
@Entity @Table(name = "tbl_user") public class User {
@Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Integer id;
@Column(name = "last_name",length = 50) private String lastName; @Column private String email;
public Integer getId() { return id; }
public void setId(Integer id) { this.id = id; }
public String getLastName() { return lastName; }
public void setLastName(String lastName) { this.lastName = lastName; }
public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; } }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| package com.hph.springboot.controller;
import com.hph.springboot.entity.User; import com.hph.springboot.repository.UserRepository; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController;
@RestController public class UserController {
@Autowired UserRepository userRepository;
@GetMapping("/user/{id}") public User getUser(@PathVariable("id") Integer id){ User user = userRepository.findOne(id); return user; }
@GetMapping("/user") public User insertUser(User user){ User save = userRepository.save(user); return save; } }
|
1 2 3 4 5 6 7 8 9 10 11 12
| spring: datasource: url: jdbc:mysql://192.168.1.110/jpa username: root password: 123456 driver-class-name: com.mysql.jdbc.Driver jpa: hibernate: ddl-auto: update show-sql: true
|
运行

创建tbl_user表。

测试
数据准备

查询
