Springboot2 jpa关联关系懒加载json序列化

实体类

student表: @manytoone的Many端
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import javax.persistence.*;
import java.util.Date;

@Entity
@Table(name = "students")
// @JsonIgnoreProperties是忽略Hibernate的延迟加载的一些属性"hibernateLazyInitializer", "handler", "fieldHandler",这些属性在实体类里没有所以要忽略掉,否则会报错
@JsonIgnoreProperties(value={"hibernateLazyInitializer","handler", "fieldHandler"})
public class Students {

    private Integer stuId;
    private String stuName;
    private Integer stuAge;
    private Integer stuSex;
    private Date stuBirth;
    private Collections collections;
    private Teacher teacher;

    @Id
    @Column(name = "stu_id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    public Integer getStuId() {
        return stuId;
    }

    public void setStuId(Integer stuId) {
        this.stuId = stuId;
    }

    @Column(name = "stu_name", length = 15)
    public String getStuName() {
        return stuName;
    }

    public void setStuName(String stuName) {
        this.stuName = stuName;
    }

    @Column(name = "stu_age", length = 3)
    public Integer getStuAge() {
        return stuAge;
    }

    public void setStuAge(Integer stuAge) {
        this.stuAge = stuAge;
    }

    @Column(name = "stu_sex", length = 1)
    public Integer getStuSex() {
        return stuSex;
    }

    public void setStuSex(Integer stuSex) {
        this.stuSex = stuSex;
    }

    @Column(name = "stu_birth")
    @Temporal(TemporalType.DATE)   // 时间格式
    public Date getStuBirth() {
        return stuBirth;
    }

    public void setStuBirth(Date stuBirth) {
        this.stuBirth = stuBirth;
    }

    @ManyToOne(fetch = FetchType.LAZY)  // 开启懒加载
    @JoinColumn(name = "coll_id")   // 关联另一张表的外键
    public Collections getCollections() {
        return collections;
    }

    public void setCollections(Collections collections) {
        this.collections = collections;
    }

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "teacher_id")
    public Teacher getTeacher() {
        return teacher;
    }

    public void setTeacher(Teacher teacher) {
        this.teacher = teacher;
    }

    @Override
    public String toString() {
        return "Students => [" +
                "stuId=" + stuId +
                ", stuName='" + stuName + '\'' +
                ", stuAge=" + stuAge +
                ", stuSex=" + stuSex +
                ", stuBirth=" + stuBirth +
                ", collections=" + collections +
                ", teacher=" + teacher +
                ']';
    }
}
Teacher表:@ManyToOne端的One端
@Entity
@Table(name = "teacher")
@JsonIgnoreProperties(value={"hibernateLazyInitializer","handler", "fieldHandler"})
public class Teacher {


    private Integer teacherId;

    private String teacherName;

    private Integer teacherSex;

    private Set students;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "teacher_id")
    public Integer getTeacherId() {
        return teacherId;
    }

    public void setTeacherId(Integer teacherId) {
        this.teacherId = teacherId;
    }

    @Column(name ="teacher_name", length = 15)
    public String getTeacherName() {
        return teacherName;
    }

    public void setTeacherName(String teacherName) {
        this.teacherName = teacherName;
    }

    @Column(name = "teacher_sex", length = 1)
    public Integer getTeacherSex() {
        return teacherSex;
    }

    public void setTeacherSex(Integer teacherSex) {
        this.teacherSex = teacherSex;
    }


    @JsonIgnore  // 在one端需要设置忽略这个属性
    @OneToMany(targetEntity = Students.class)  // targetEntity 必须写,值为Many端的表
    @JoinColumn(name = "teacher_id")
    public Set getStudents() {
        return students;
    }

    public void setStudents(Set students) {
        this.students = students;
    }

    @Override
    public String toString() {
        return "Teacher => [" +
                "teacherId=" + teacherId +
                ", teacherName='" + teacherName + '\'' +
                ", teacherSex=" + teacherSex +
                ']';
    }
}

Repository类

StudentsRepository表:
import com.springboot.crud.entity.Students;
import org.springframework.data.jpa.repository.JpaRepository;

public interface StudentsRepository extends JpaRepository<Students, Integer> {

}
TeacherRepository表:
import com.springboot.crud.entity.Teacher;
import org.springframework.data.jpa.repository.JpaRepository;

public interface TeacherRepository extends JpaRepository<Teacher, Integer> {
}

Service表:

StudentsService类和实现类:
// 接口类
import com.springboot.crud.entity.Students;
import org.springframework.data.domain.Page;

public interface StudentsService {

    // 普通分页
    Page getPage(Integer num, Integer size);

    // 通过主键删除
    void deleteById(Integer stu_id);

    Students findById(Integer stu_id);
}

// 实现类
import com.springboot.crud.entity.Students;
import com.springboot.crud.repository.StudentsRepository;
import com.springboot.crud.service.StudentsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class StudentsServiceImpl implements StudentsService {

    @Autowired
    private StudentsRepository studentsRepository;

    @Override
    @Transactional(readOnly = true)
    public Page getPage(Integer num, Integer size) {
        Pageable pageable =new PageRequest(num - 1,size);
        return studentsRepository.findAll(pageable);
    }

    @Override
    public void deleteById(Integer stu_id) {
        studentsRepository.deleteById(stu_id);
    }

    @Override
    public Students findById(Integer stu_id) {
        Students students = studentsRepository.getOne(stu_id);
        return students;
    }
}
TeacherService类和实现类:
// 接口类
import com.springboot.crud.entity.Teacher;

public interface TeacherService {

    Teacher getOne(Integer teacher_id);
}
// 实现类
import com.springboot.crud.entity.Teacher;
import com.springboot.crud.repository.TeacherRepository;
import com.springboot.crud.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class TeacherServiceImpl implements TeacherService {

    @Autowired
    private TeacherRepository teacherRepository;

    @Override
    public Teacher getOne(Integer teacher_id) {
        return teacherRepository.getOne(teacher_id);
    }
}

控制器类:

import com.springboot.crud.entity.Students;
import com.springboot.crud.service.StudentsService;
import com.springboot.crud.service.TeacherService;
import com.springboot.crud.util.Msg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Controller
@RequestMapping("/crud")
public class MainController {

    @Autowired
    private StudentsService studentsService;

    @Autowired
    private TeacherService teacherService;


    // 分页显示
    @RequestMapping("/index")
    public String loadPage(Model model, @RequestParam(value = "num", defaultValue = "1") Integer num, @RequestParam(value = "size", defaultValue = "4") Integer size){
        Page studentsPage = studentsService.getPage(num, size);
        model.addAttribute("pageInfo", studentsPage);
        return "index";
    }


    // json 分页显示
    @GetMapping("/page")
    @ResponseBody
    public Page getPage(@RequestParam(value = "num", defaultValue = "1") Integer num, @RequestParam(value = "size", defaultValue = "5") Integer size){
        return studentsService.getPage(num, size);
    }


    // 删除
    @DeleteMapping("/stu/{stu_id}")
    @ResponseBody
    public Msg delete_stu(@PathVariable("stu_id") Integer stu_id){
        studentsService.deleteById(stu_id);
        return Msg.success();
    }


    // 编辑 
    @GetMapping("/stu/{stu_id}")
    @ResponseBody
    public Msg edit_stu(@PathVariable("stu_id") Integer stu_id){
        Students students = studentsService.findById(stu_id);
        System.out.println("获取的类:" + students);
        return Msg.success().add("students", students);
    }


    // 获取
    @GetMapping("/teacher/{teacher_id}")
    @ResponseBody
    public Msg get_teacher(@PathVariable("teacher_id") Integer teacher_id){
        Set studentsList = teacherService.getOne(teacher_id).getStudents();
        List result = new ArrayList<>(studentsList);
        return Msg.success().add("studentsList", result);
    }
}

API json串显示:

http://localhost:3306/crud/stu/1
{
    "code": 100, 
    "msg": "处理成功!", 
    "extend": {
        "students": {
            "stuId": 3, 
            "stuName": "张军", 
            "stuAge": 12, 
            "stuSex": 1, 
            "stuBirth": "2018-01-01", 
            "collections": {
                "collId": 2, 
                "collName": "一年级2班"
            }, 
            "teacher": {
                "teacherId": 2, 
                "teacherName": "李老师", 
                "teacherSex": 1
            }
        }
    }
}
http://localhost:3306/crud/teacher/1
{
    "code": 100, 
    "msg": "处理成功!", 
    "extend": {
        "studentsList": [
            {
                "stuId": 6, 
                "stuName": "张小军", 
                "stuAge": 12, 
                "stuSex": 0, 
                "stuBirth": "2015-09-09", 
                "collections": {
                    "collId": 2, 
                    "collName": "一年级2班"
                }, 
                "teacher": {
                    "teacherId": 1, 
                    "teacherName": "张老师", 
                    "teacherSex": 1
                }
            }, 
            {
                "stuId": 26, 
                "stuName": "乐书", 
                "stuAge": 12, 
                "stuSex": 1, 
                "stuBirth": "2008-06-10", 
                "collections": {
                    "collId": 1, 
                    "collName": "一年级1班"
                }, 
                "teacher": {
                    "teacherId": 1, 
                    "teacherName": "张老师", 
                    "teacherSex": 1
                }
            }, 
            {
                "stuId": 22, 
                "stuName": "郭金金", 
                "stuAge": 10, 
                "stuSex": 1, 
                "stuBirth": "2018-08-23", 
                "collections": {
                    "collId": 3, 
                    "collName": "一年级3班"
                }, 
                "teacher": {
                    "teacherId": 1, 
                    "teacherName": "张老师", 
                    "teacherSex": 1
                }
            }, 
            {
                "stuId": 10, 
                "stuName": "李军", 
                "stuAge": 12, 
                "stuSex": 0, 
                "stuBirth": "2018-01-12", 
                "collections": {
                    "collId": 3, 
                    "collName": "一年级3班"
                }, 
                "teacher": {
                    "teacherId": 1, 
                    "teacherName": "张老师", 
                    "teacherSex": 1
                }
            }, 
            {
                "stuId": 18, 
                "stuName": "张丽丽", 
                "stuAge": 12, 
                "stuSex": 1, 
                "stuBirth": "2018-01-15", 
                "collections": {
                    "collId": 2, 
                    "collName": "一年级2班"
                }, 
                "teacher": {
                    "teacherId": 1, 
                    "teacherName": "张老师", 
                    "teacherSex": 1
                }
            }
        ]
    }
}

你可能感兴趣的:(java,SpringBoot,hibernate,SpringBoot2,技术点总结)