1)application.yml 做出以下配置
spring:
datasource:
driverClassName: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/lpf?useSSL=false&allowPublicKeyRetrieval=true
username: root
password: root
jpa:
database-platform: org.hibernate.dialect.MySQL5Dialect
# 控制台显示SQL
show-sql: true
generate-ddl: true
hibernate:
# 更新或者创建数据表
ddl-auto: update
2)实体类关联数据库
package com.thoughtwork.springboot.entity;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data;
import javax.persistence.*;
/**
* 使用jpa注解配置映射关系
* @Entity 告诉jpa这是一个实体类,(和数据表映射的类)
* @Table(name = "tbl_user") 指定和哪个数据表对应,name如果省略,表名就是类名小写
*
* @GeneratedValue(strategy = GenerationType.IDENTITY) 主键自增
* @Column 和数据表对应的一个列,name列名,length长度,省略的话,默认列明就是属性名
*/
@Data
@Entity
@Table(name = "tbl_user")
@JsonIgnoreProperties({"hibernateLazyInitializer","handler"})
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(name = "username",length = 50)
private String name;
private String email;
}
3)继承JpaRepository
package com.thoughtwork.springboot.repository;
import com.thoughtwork.springboot.entity.User;
import org.springframework.data.jpa.repository.JpaRepository;
/**
* 继承 CrudRepository 有基本的crud功能
* 继承 PagingAndSortingRepository 有排序分页功能
* 继承 JpaRepository 以上两种都有
* JpaRepository<T,T> 第一个泛型,操作的实体类,第二个泛型,实体类的主键类型
*/
public interface UserRepository extends JpaRepository<User,Integer> {
}
4)CRUD
package com.thoughtwork.springboot.controller;
import com.thoughtwork.springboot.entity.User;
import com.thoughtwork.springboot.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
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;
// localhost:8080/user/1 查
@GetMapping("/user/{id}")
public User getUser(@PathVariable("id") Integer id) {
User user = userRepository.getOne(id);
return user;
}
// localhost:8080/user?name=lpf&email=pengfei.lv@thoughtworks.com 增改
@GetMapping("/user")
public User saveUser(User user) {
return userRepository.save(user);
}
// localhost:8080/user/4 删
@DeleteMapping("/user/{id}")
public void delete(@PathVariable("id") Integer id) {
userRepository.deleteById(id);
}
}