springboot使用Spring Data JPA
新建SpringBoot项目
POM.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
<version>2.6.3</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.6.3</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>5.7.0</scope>
</dependency>
application.properties配置
spring.datasource.url=jdbc:mysql://localhost:3306/dbjpa?serverTimezone=UTC&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=root
#配置JPA
##使用Mysql5.7数据库,写MySQL5Dialect的话默认使用myisam引擎,MySQL5InnoDBDialect会使用innodb引擎
spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect
##update表示当实体类有任何变化时会更新Mysql数据库字段
##create和update都只能用在开发环境,线上环境一定要用none
spring.jpa.hibernate.ddl-auto=update
##打印sql
spring.jpa.show-sql=true
编写代码
@Entity说明这个class是实体类,并且使用默认的orm规则,即class名即数据库表中表名,class字段名即表中的字段名.
@Table来改变class名与数据库中表名的映射规则.
@Column来改变class中字段名与数据库中表的字段名的映射规则.
package com.autumn.model;
import javax.persistence.*;
@Entity
@Table(name = "student")
public class Student {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(nullable = false,name = "name")
private String name;
}
运行代码生成库表
在代码运行之前要先新建数据库
启动springboot项目,自动新建表
DAO接口
新建StudentDao数据库操作接口,继承CrudRepository接口。
import com.autumn.model.Student;
import org.springframework.data.repository.CrudRepository;
/**
* 继承spring data jpa的CrudRepository<类,类的主键类型>
**/
public interface StudentDao extends CrudRepository<Student,Long>{
}
Service类
service直接调用StudentDao的接口CrudRepository的方法。
import com.autumn.dao.StudentDao;
import com.autumn.exceptions.StudentEmptyNameException;
import com.autumn.exceptions.StudentNonExistException;
import com.autumn.model.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;
@Service
public class StudentService {
@Autowired
private StudentDao dao;
/*添加*/
public Student add(Student student){
if (student.getName().isEmpty()){
throw new StudentEmptyNameException("学生姓名为空!");
}
return dao.save(student);
}
/*修改*/
public Student update(Student student){
if (student.getId()==null || dao.existsById(student.getId())){
throw new StudentNonExistException("学生无ID");
}
return dao.save(student);
}
/*查询所有*/
public List<Student> getAllStudents(){
return (List<Student>) dao.findAll();
}
/*根据id获取详细信息*/
public Optional<Student> getStudentById(Long id){
return dao.findById(id);
}
}
Controller层
@RestController
@RequestMapping("api/student")
public class StudentController {
@Autowired
private StudentService service;
/*查询所有学生*/
@GetMapping
public List<Student> getAllStudents(){
return service.getAllStudents();
}
/*注册学生信息*/
@PostMapping
@RequestMapping("register")
public ResponseEntity<String> register(@RequestBody Student student){
try {
service.add(student);
return ResponseEntity.ok("注册学生信息" + student.toString());
}catch (StudentEmptyNameException e){
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage());
}
}
}
一对多业务添加
新增UniversityClass班级业务
model类
import com.fasterxml.jackson.annotation.JsonIgnore;
import javax.persistence.*;
import java.util.List;
@Entity
@Table(name = "university_class")
public class UniversityClass {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@Column(nullable = false)
Integer year;
@Column(nullable = false)
Integer number;
@OneToMany(mappedBy = "universityClass")
List<Student> students;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Integer getYear() {
return year;
}
public void setYear(Integer year) {
this.year = year;
}
public Integer getNumber() {
return number;
}
public void setNumber(Integer number) {
this.number = number;
}
//转换为json是忽略此字段,不然会无限递归
@JsonIgnore
public List<Student> getStudents() {
return students;
}
public void setStudents(List<Student> students) {
this.students = students;
}
@Override
public String toString() {
return "UniversityClass{" +
"id=" + id +
", year=" + year +
", number=" + number +
'}';
}
}
Dao层
package com.autumn.dao;
import com.autumn.model.UniversityClass;
import org.springframework.data.repository.CrudRepository;
public interface UniversityClassDao extends CrudRepository<UniversityClass,Long>{
}
Service层
package com.autumn.service;
import com.autumn.dao.UniversityClassDao;
import com.autumn.exceptions.InvalidUniversityClassException;
import com.autumn.model.UniversityClass;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Calendar;
import java.util.List;
@Service
public class UniversityClassService {
@Autowired
UniversityClassDao dao;
/*查询所有*/
public List<UniversityClass> getAll() {
return (List<UniversityClass>) dao.findAll();
}
/*添加*/
public UniversityClass add(UniversityClass universityClass){
int currentYear = Calendar.getInstance().get(Calendar.YEAR);
if(universityClass.getYear()<currentYear){
throw new InvalidUniversityClassException("Cannot add class in the past!");
}
if(universityClass.getYear()>currentYear){
throw new InvalidUniversityClassException("Cannot add class in the future!");
}
return dao.save(universityClass);
}
}
Controller层
package com.autumn.controller;
import com.autumn.exceptions.InvalidUniversityClassException;
import com.autumn.model.UniversityClass;
import com.autumn.service.UniversityClassService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("api/class")
public class UniversityClassController {
@Autowired
private UniversityClassService service;
/*查询所有*/
@GetMapping
public List<UniversityClass> getAllStudents(){
return service.getAll();
}
/*添加*/
@PostMapping
@RequestMapping("add")
public ResponseEntity<String> add(@RequestBody UniversityClass universityClass){
try {
UniversityClass savedUniversityClass = service.add(universityClass);
return ResponseEntity.ok("添加班级信息: " + savedUniversityClass.toString());
}catch (InvalidUniversityClassException e){
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage());
}
}
}
修改Student业务类
在Student的model类中添加字段
@ManyToOne
@JoinColumn(name = "university_class_id")
private UniversityClass universityClass;
在Student的service层中添加
@Autowired
private UniversityClassDao universityClassDao;
/**
* 给学生分配班级
* */
public Student assignClass(Long studentId,Long classId){
if (!dao.existsById(studentId)){
throw new StudentNonExistException("Cannot find student Id"+studentId);
}
if(!universityClassDao.existsById(classId)){
throw new StudentNonExistException("Cannot find calss Id"+studentId);
}
Student student = getStudentById(studentId).get();
UniversityClass universityClass = universityClassDao.findById(classId).get();
student.setUniversityClass(universityClass);
return dao.save(student);
}
在Student的Controller层中添加
/**
* 给学生分配班级
* @param studentId
* @param classId
* @return
*/
@PostMapping(path = "assignclass/{sid}/{cid}")
public ResponseEntity<String> assignClass2(@PathVariable("sid") Long studentId,@PathVariable("cid") Long classId){
try{
Student updatedstudent = service.assignClass(studentId, classId);
return ResponseEntity.ok("Assigned class. "+updatedstudent.toString());
}catch (StudentNonExistException e){
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage());
}catch(InvalidUniversityClassException e){
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(e.getMessage());
}
}
给学生分配班级
查询所有学生
如果这篇文章对你有用,可以关注本人微信公众号获取更多ヽ(^ω^)ノ ~
![微信公众号二维码](https://images.cnblogs.com/cnblogs_com/aeolian/1679458/o_wechat_gzh_qrcode.jpg)