我有以下模型结构:

@Entity
@Table(name = "MY_TEMPLATE")
public class MyTemplate {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "ID", nullable = false, updatable = false)
    private Long id;
    @OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
    @JoinColumn(name = "MY_TEMPLATE_ID")
    private List<MyObject> myobjects = new ArrayList<>();
    ...
}

@Entity
@Table(name = "MY_OBJECT")
public class MyObject implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "ID", nullable = false, updatable = false)
    private Long id;
}


MyDailyResource没有引用MyTemplate

我也有通常的CrudRepository

public interface MyTemplateRepository extends CrudRepository<MyTemplate, Long> {
}


当我执行时:

myTemplateRepo.save(myTemplate) // myTemplate在myObjects集合中有一个元素

我看到以下错误:

    insert
    into
        MY_TEMPLATE
        (LAST_MODIFIED, LAST_MODIFIED_BY, NAME)
    values
        (?, ?, ?)


    insert
    into
        MY_OBJECT
        (BAR, FOO)
    values
        (?, ?)

java.sql.SQLException: Field 'MY_TEMPLATE_ID' doesn't have a default value
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)


我不知道我该怎么做以及如何解决。

你能给我推荐点东西吗?

附言

看起来是因为我对数据库中的外键没有null约束。但我不喜欢消除这种约束

最佳答案

希望您的父表是MY_TEMPLATE,子表是MY_OBJECT

更新您的课程

@Entity
@Table(name = "MY_TEMPLATE")
public class MyTemplate {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "ID", nullable = false, updatable = false)
    private Long id;
    @OneToMany(mappedBy="myTemplate", cascade = CascadeType.ALL, orphanRemoval = true)
    private List<MyObject> myObjects = new ArrayList<>();
    ...
}

@Entity
@Table(name = "MY_OBJECT")
public class MyObject implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "ID", nullable = false, updatable = false)
    private Long id;
    @ManyToOne
    @JoinColumn(name = "MY_TEMPLATE_ID")
    private MyTemplate myTemplate;
}

关于java - java.sql.SQLException:字段foreign_key没有默认值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/52170726/

10-08 23:03