还是之前举的 城市 和 学校之间的例子
一座城市可以有多个学校
而每个学校都只能在一个城市
City.java
package com.ctguyxr.satokendemo.entity;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import lombok.Data;
import javax.persistence.*;
import java.util.List;
/**
* Created By Intellij IDEA
*
* @author Xinrui Yu
* @date 2021/11/28 20:59 星期日
*/
@Entity
@Data
@Table(name = "t_city")
public class City {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
@JsonManagedReference
@OneToMany(cascade = CascadeType.ALL)
@JoinColumn(name = "city_id")
private List<College> colleges;
}
College.java
package com.ctguyxr.satokendemo.entity;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import lombok.Data;
import javax.persistence.*;
import javax.persistence.criteria.CriteriaBuilder;
import java.util.List;
/**
* Created By Intellij IDEA
*
* @author Xinrui Yu
* @date 2021/11/28 21:00 星期日
*/
@Entity
@Data
@Table(name = "t_colleges")
public class College {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
@JsonBackReference
@ManyToOne(cascade = CascadeType.ALL)
private City city;
}
最后生成的表结构