1.项目结构 2.配置yml文件
spring: datasource: url: jdbc:mysql://localhost:3306/jpa username: root password: shan007 driver-class-name: com.mysql.jdbc.Driver jpa: hibernate: # 更新或者创建数据表结构 ddl-auto: update # 控制台显示SQL show-sql: true3.编写实体类
package com.example.myspringboot07jpa.entity; import javax.persistence.*; //使用JPA注解配置映射关系 @Entity //告诉JPA这是一个实体类(和数据表映射的类) @Table(name = "tbl_user") //@Table来指定和哪个数据表对应;如果省略默认表名就是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; } }4.创建UserRepository接口,来继承JpaRepository接口。
package com.example.myspringboot07jpa.repository; import com.example.myspringboot07jpa.entity.User; import org.springframework.data.jpa.repository.JpaRepository; //继承JpaRepository来完成对数据库的操作 public interface UserRepository extends JpaRepository<User,Integer> { }5.创建controller层,编写UserController
package com.example.myspringboot07jpa.controller; import com.example.myspringboot07jpa.entity.User; import com.example.myspringboot07jpa.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.ResponseBody; import org.springframework.web.bind.annotation.RestController; @ResponseBody @RestController public class UserController { @Autowired UserRepository userRepository; @GetMapping("/user/{id}") public User getUser(@PathVariable("id") Integer id){ User user = userRepository.findById(id).orElse(null); // User user = userRepository.findOne(id); return user; } @GetMapping("/user") public User insertUser(User user){ User save = userRepository.save(user); return save; } }插入数据
查询数据