我有以下模型结构:
@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约束。但我不希望删除该约束
答案 0 :(得分:0)
希望您的父表是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;
}