我正在尝试为@MapKeyColumn
实现以下示例。 OnetoMany
和Company
之间存在Persons
关系。但是,当我尝试保留Person实例时遇到以下错误,因为那是关系的所有者:
Caused by: java.sql.SQLException: Field 'name_emp' 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)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:975)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1114)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1062)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeLargeUpdate(ClientPreparedStatement.java:1383)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdate(ClientPreparedStatement.java:1047)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:208)
... 20 more
人员实体
@Entity
public class Person {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
int id;
String name;
@ManyToOne(cascade=CascadeType.PERSIST)
//@JoinColumn(name="company_id")
Company company;
public Person()
{}
public Person(String name) {
super();
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Company getcompany() {
return company;
}
public void setcompany(Company c) {
this.company = c;
}
}
公司实体
@Entity
public class Company {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
int id;
String name;
@OneToMany(cascade=CascadeType.PERSIST,mappedBy="company")
@MapKeyColumn(name="name_emp")
Map<String,Person> persons= new HashMap<>();
public Company()
{}
public Company(String name) {
super();
this.name = name;
}
public Map<String,Person> getPersons() {
return persons;
}
public void setPersons(Map<String,Person> persons) {
this.persons = persons;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
MainTest
Person p1 = new Person("jack");
Company c= new Company("ABCORP");
p1.setcompany(c);
session.persist(p1);
答案 0 :(得分:0)
由于未在公司实例中设置关系,因此可能会出现问题。
您能否通过调用c.getPersons().add(p1.getName(), p1)
或将setcompany(...)
方法更改为
public void setcompany(Company c) {
c.getPersons().add(this.getName(), this)
this.company = c;
}