为什么我可以在关联表中多对多添加ID

时间:2019-05-09 14:46:32

标签: java spring spring-boot spring-mvc

我有一个问题,我有两个实体,我想创建一个关联表。

当前,我的关联表在数据库中创建。我得到一个带有两个外键的表。但是,当我将不存在的ID放在关联表中时,它会起作用。

我认为关联表中的主键和外键绑定无法正常工作,我找不到问题。

我喜欢这样:

脚本实体:

@Table(name = "script")
public class Script implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "nom")
    private String nom;

    @ManyToMany(fetch = FetchType.LAZY,
            cascade =
                    {
                            CascadeType.DETACH,
                            CascadeType.MERGE,
                            CascadeType.REFRESH,
                            CascadeType.PERSIST
                    },
            targetEntity = LibellePrerequis.class)
    @JoinTable(name = "script_libelleprerequis",
            inverseJoinColumns = @JoinColumn(name = "id_script",
                    nullable = false,
                    updatable = false),
            joinColumns = @JoinColumn(name = "id_libelleprerequis",
                    nullable = false,
                    updatable = false),
            foreignKey = @ForeignKey(ConstraintMode.CONSTRAINT),
            inverseForeignKey = @ForeignKey(ConstraintMode.CONSTRAINT))
    @JsonIgnore
    private List<LibellePrerequis> libelleprerequiss = new ArrayList<>();

和LibellePrerequis实体:

@Table(name = "libelleprerequis")
public class LibellePrerequis implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(name = "libelle_prerequis")
    private String libelle_prerequis;

    @ManyToOne
    private Produit produit;

    @ManyToOne
    private Typologie typologie;

    @ManyToMany(fetch = FetchType.LAZY,
            cascade =
                    {
                            CascadeType.DETACH,
                            CascadeType.MERGE,
                            CascadeType.REFRESH,
                            CascadeType.PERSIST
                    },
            targetEntity = Script.class)
    @JoinTable(name = "script_libelleprerequis",
            joinColumns = @JoinColumn(name = "id_script",
                    nullable = false,
                    updatable = false),
            inverseJoinColumns = @JoinColumn(name = "id_libelleprerequis",
                    nullable = false,
                    updatable = false),
            foreignKey = @ForeignKey(ConstraintMode.CONSTRAINT),
            inverseForeignKey = @ForeignKey(ConstraintMode.CONSTRAINT))
    @JsonIgnore
    private List<Script> scripts = new ArrayList<>();

0 个答案:

没有答案