SpringBoot之JPA

SpringData之JPA

这里写图片描述

第一步:创建工程

使用IDEA的spring initializr创建工程,选中web、mysql、jdbc、jpa模块
这里写图片描述

第二步:配置

application.yml

spring:
  datasource:
    username: root
    password: Root!!2018
    url: jdbc:mysql://192.168.3.18/springboot_mybatis?autoReconnect=true&useSSL=false
    driver-class-name: com.mysql.jdbc.Driver

  jpa:
    hibernate:
#     更新或者创建数据表结构
      ddl-auto: update
#   控制台显示SQL
    show-sql: true

server:
  port: 8088

第三步:编码

User.java

// 使用JPA注解配置映射关系
@Entity // 告诉JPA这是一个实体类(和数据表映射的类)
@Table(name = "tb_user") // @Table来指定和哪个数据表对应;如果省略默认表名就是user;
public class User {

    @Id // 主键
    @GeneratedValue(strategy = GenerationType.IDENTITY) // 自增主键
    private Integer id;
    @Column(name = "username", length = 50)
    private String username;
    @Column // 省略配置属性则默认列名为属性名
    private Double balance;
    @Column
    private Date birthday;
    // 省略setter和getter
}

UserRepository.java

// 继承JpaRepository,完成数据库操作
public interface UserRepository extends JpaRepository<User, Integer> {

}

UserController.java

@RestController
public class UserController {

    @Autowired
    private UserRepository userRepository;

    @GetMapping("/user/{id}")
    public User getUserById(@PathVariable("id") Integer id){
        return userRepository.findById(id).get();
    }

    @PostMapping("/user")
    public int insertUser(User user){
        return userRepository.save(user).getId();
    }
}

猜你喜欢

转载自blog.csdn.net/Code_shadow/article/details/81254082