欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

springboot -- JPA简单运用

程序员文章站 2022-04-21 12:05:17
...

1、导入相关依赖

<dependency>
		<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-data-jpa</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-jdbc</artifactId>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>8.0.11</version>
			<scope>runtime</scope>
		</dependency>

2、配置文件(application.yml)

spring:
  datasource:
    url: jdbc:mysql://localhost:3306/abc?serverTimezone=UTC&useUnicode=true&characterEncoding=utf8&useSSL=false
    driver-class-name: com.mysql.cj.jdbc.Driver
    username: root
    password: admin
  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true
    

3、创建实体类

package com.example.bean;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="_user")
public class User {
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	private Integer id;
	
	private String lastName;

	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、创建实现JPA的接口

package com.example.dao;

import org.springframework.data.jpa.repository.JpaRepository;

import com.example.bean.User;

public interface UserResposity extends JpaRepository<User, Integer>{

}

5、调用测试

package com.example.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import com.example.bean.User;
import com.example.dao.UserResposity;

@RestController
public class UserController {
	@Autowired
	UserResposity userResposity;
	
	@GetMapping("/user/{id}")
	public User get(@PathVariable("id") int id){
		return userResposity.findOne(id);
	}
	
	@GetMapping("/user")
	public User add(User user){
		return userResposity.saveAndFlush(user);
	}
}

相关标签: springboot