Springboot 整合jpa的使用

2019-08-01 10:55:26 浏览数 (1)

1 先配置文件

代码语言:javascript复制
spring:
  datasource:
    url: jdbc:mysql://192.168.3.193/jpa
    username: root
    password: shiye
    driver-class-name: com.mysql.jdbc.Driver
  jpa:
    hibernate:
      ddl-auto: update  # 更新或者穿件数据库表
    show-sql: true  #打印sql

2 创建实体对象

代码语言:javascript复制
package com.shi.data.model;

import javax.persistence.*;

//使用JPA注解配置映射关系
@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(name = "email",length = 50)
    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;
    }
}

3 编写dao文件 直接继承JpaRepository

代码语言:javascript复制
package com.shi.data.respository;

import com.shi.data.model.User;
import org.springframework.data.jpa.repository.JpaRepository;

//继承 JpaRepository 来完成基本的 crud操作
public interface UserRespository  extends JpaRepository<User,Integer>{



}

4 编写controller来调用该对像

代码语言:javascript复制
package com.shi.data.controller;

import com.shi.data.model.User;
import com.shi.data.respository.UserRespository;
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 JpaController {

    @Autowired
    UserRespository userRespository;

    //根据id查询单个用户
    @GetMapping("/user/{id}")
    public User getUser(@PathVariable("id") Integer id){
        User one = userRespository.findOne(id);
        return one;
    }

    //添加用户
    @GetMapping("/user")
    public User saveUser(User user){
        User one = userRespository.save(user);
        return one;
    }

}

0 人点赞