因此,我在两个实体 Medewerker 和 Taak 之间有多对多关系,这是我对这两个实体的代码:
@Entity
@Table(name = "T_MEDEWERKER")
public class Medewerker {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String naam;
private String functie;
@ManyToOne
@Cascade(org.hibernate.annotations.CascadeType.SAVE_UPDATE)
@JoinColumn(name = "festivalId", nullable = false)
private Festival festival;
@ManyToMany
@Cascade(org.hibernate.annotations.CascadeType.SAVE_UPDATE)
@JoinTable(name="T_MEDEWERKER_TAAK",
joinColumns = {@JoinColumn(name="medewerkerId")},
inverseJoinColumns = {@JoinColumn(name="taakId")})
private List<Taak> taken = new ArrayList<Taak>();
public Medewerker(){
}
public Medewerker(String naam, String functie) {
this.naam = naam;
this.functie = functie;
}
public void addTaak(Taak t) {
taken.add(t);
}
public void setFestival(Festival festival) {
this.festival = festival;
}
}
@Entity
@Table(name = "T_TAAK")
public class Taak {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String omschrijving;
@ManyToMany
@Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE})
@JoinTable(name="T_MEDEWERKER_TAAK",
joinColumns = {@JoinColumn(name="taakId")},
inverseJoinColumns = {@JoinColumn(name="medewerkerId")})
private List<Medewerker> medewerkers = new ArrayList<Medewerker>();
public Taak(){
}
public Taak(String omschrijving) {
this.omschrijving = omschrijving;
}
private void addMedewerker(Medewerker m){
medewerkers.add(m);
}
}
现在,我想让中间表(T_MEDEWERKER_TAAK)通过可连接的休眠自动生成。但是,我不断收到以下错误:21:49:08,157 WARN SqlExceptionHelper:145 - SQL 错误:1364,SQLState: HY000 21:49:08,158 错误 SqlExceptionHelper:147 - 字段 'taakId' 没有默认值
但是,taakid 字段确实有一个自动生成的值,所以我真的不明白我在这里做错了什么?另外,映射双方的多对多关系是否不好?因为老实说,我不知道将其放在一侧或将其放在两侧之间有什么区别.. Mysql 确实创建了复合表,但没有将任何数据放入其中。
如果需要,这是我的测试代码:
public class TestMedewerker {
public static void main(String[] args) {
Medewerker m = new Medewerker("Jos", "Cameraman");
m.setFestival(new Festival("Rock Wercher", 3, "Werchter", 75000));
m.addTaak(new Taak("Filmen"));
m.addTaak(new Taak("Geluidsman Spelen"));
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
Transaction tx = session.beginTransaction();
session.saveOrUpdate(m);
tx.commit();
}
}