在我的Users.entity中使用多个@OneToMany条目时,Hibernate崩溃,我不明白为什么。
我有一个用于用户的表(主键userID)和其他各种表,这些表通过数据库中的外键集(在每个依赖表中设置了InnoDB集和外键)来引用主键userID。
这里有一个包含三个表的示例:
表用户:
CREATE TABLE `users` (`userID` int(11) NOT NULL) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `users` ADD PRIMARY KEY (`userID`);
表:vacationrequests
CREATE TABLE `vacationrequests` (`requestID` int(11) NOT NULL,`userID` int(4) NOT NULL,) ENGINE=InnoDB DEFAULT CHARSET=latin1;
ALTER TABLE `vacationrequests` ADD CONSTRAINT `userID` FOREIGN KEY (`userID`) REFERENCES `users` (`userID`) ON UPDATE CASCADE; COMMIT;
表格月末:
CREATE TABLE `monthend` (`monthendID` int(11) NOT NULL,`userID` int(4) NOT NULL,) ENGINE=InnoDB DEFAULT CHARSET=latin1;
实体用户:
@Entity
@Table(name="users")
public class Users {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="userID")
private int userID;
... .... (other variables)
@OneToMany(fetch = FetchType.LAZY, mappedBy="monthend")
private Set<Monthend> monthend;
@OneToMany(fetch = FetchType.LAZY, mappedBy="vacationrequests")
private Set<Vacationrequests> vacationrequests;
public Users() {
}
实体休假请求:
@Entity
@Table(name="vacationrequests")
public class Vacationrequests {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="requestID")
private int requestID;
... .... (other variables)
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="userID", nullable = false)
private Users users;
public Vacationrequests() {
}
实体蒙亨德:
@Entity
@Table(name="monthend")
public class Monthend {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="monthendID")
private int monthendID;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="userID", nullable = false)
private Users users;
@Column(name="clientID")
private int clientID;
@Column(name="month")
private int month;
@Column(name="year")
private int year;
@Column(name="monthend")
private int monthend;
public Monthend() {
}
工作查询:
List<Object> listJoinUsersMonthend = session.createQuery("from Monthend m inner join m.users as users where m.clientID = :clientID AND m.year = :year AND users.loginclass = 0 AND users.isactive = 1 AND m.monthend = 0 AND m.month < :month order by users.userID asc")
.setInteger("clientID", user.getClientID())
.setInteger("year", year)
.setInteger("month", month)
.getResultList();
我要集成的第二个查询:
List<Object> listJoinVacationrequestsUsers = session.createQuery("from Vacationrequests v inner join v.users as users where v.clientID = :clientID AND v.approved=0 AND v.vacationtype=1 AND YEAR(v.startdate) = :year" )
.setInteger("clientID", user.getClientID())
.setInteger("year", year)
.getResultList();
只有一个查询和Users.entity中的一个条目,一切都可以正常工作。一旦添加两个条目,休眠就会崩溃,并且没有错误消息。不可能在一个实体中执行两个@OneToMany语句吗?
答案 0 :(得分:1)
问题似乎出在Users实体中关联的映射上。 您应该更改关联的 mappedBy 属性,以指定引用关联实体中当前实体的字段名称(在本例中为 users ),如下所示:
@OneToMany(fetch = FetchType.LAZY, mappedBy = "users")
private Set<Monthend> monthend;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "users")
private Set<Vacationrequests> vacationrequests;