springboot用jpa来访问数据库

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_36984017/article/details/83420980

一、首先创建一个springboot项目,并选择好web、JPA、Mysql、JDBC相关依赖

二、在配置文件中配置好连接数据库的相关配置

spring:
  datasource:
  	//这里的jpa是连接哪个数据库
    url: jdbc:mysql://127.0.0.1:3306/jpa?useUnicode=true&characterEncoding=utf-8&useSSL=false
    username: root
    password: daibin

三、建一个实体类用于映射数据库表

package com.jpa.entity;

import javax.persistence.*;

//告诉容器是表映射
@Entity
//表名
@Table(name="user_dai")
public class User {
    //主键
    @Id
    //自增主键
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;

	//表字段映射
    @Column
    private String name;

    public User(int id, String name) {
        this.id = id;
        this.name = name;
    }

    public User() {

    }
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

四、建一个类似与mapper的dao接口层

package com.jpa.dao;

import com.jpa.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;

//User是你自建的表映射实体类,Integer是表主键字段的类型,一般是Integer
public interface UserInter extends JpaRepository<User,Integer> {
}

五、controller中操作

package com.jpa.controller;

import com.jpa.dao.UserInter;
import com.jpa.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class He {
    @Autowired
    private UserInter userInter;
    
    @RequestMapping("/ii")
    public Object ii(){
    	//查找数据库id为1的行
        return userInter.findById(1);
    }

    @RequestMapping("/pp")
    public Object pp(User user){
    	//localhost:127.0.0.1:8080/pp?user=你好     (数据库会插入一条你好数据,因为id自增,可以不传)
        return userInter.save(user);
    }

}

用jpa操作数据库就这么简单

猜你喜欢

转载自blog.csdn.net/qq_36984017/article/details/83420980