1.创建SpringBoot工程,引入依赖如下:
<dependencies>
<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>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.8</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
2.创建application.yml,配置相关属性:
spring:
datasource:
url: jdbc:mysql://localhost:3306/jpa?useUnicode=true&characterEncoding=utf-8&useSSL=false
username: root
password: ******
driver-class-name: com.mysql.jdbc.Driver
jpa:
hibernate:
ddl-auto: update #更新或者创建数据表
show-sql: true #控制体显示sql语句
3.创建实体类User
package com.chenpeng.springboot.entity;
import lombok.Data;
import javax.persistence.*;
@Data//生成get和set方法
@Entity//告诉JPA这是一个实体类(和数据报映射的类)
@Table(name = "t_user")//@Table来指定和哪个数据表对应,如果省略默认表名就是类名小写
public class User {
@Id//这是一个主键
@GeneratedValue(strategy = GenerationType.IDENTITY)//自增主键
private Integer id;
@Column(name = "name", length = 10)
private String name;
@Column//省略默认类名就是属性名
private String age;
}
4.创建UserRepository接口
package com.chenpeng.springboot.repository;
import com.chenpeng.springboot.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
//继承JpaRepository来完成对数据库的操作
public interface UserRepository extends JpaRepository<User, Integer> {
}
5.创建UserController
package com.chenpeng.springboot.controller;
import com.chenpeng.springboot.entity.User;
import com.chenpeng.springboot.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.RestController;
@RestController
public class UserController {
@Autowired
UserRepository userRepository;
@GetMapping("/user/{id}")
public User getUserById(@PathVariable("id") Integer id){
//springboot版本2.0以后,废除了原来的findOne(id)方法,查询对象使用findById(id).get()
User user = userRepository.findById(id).get();
return user;
}
@GetMapping("/user")
public User insertUser(User user){
User save = userRepository.save(user);
return save;
}
}