我正在为一对多映射做一个概念验证但没有成功。我的架构如下:用户-----> UseRole
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name="UserRole")
public class UserRole {
private int userRoleId;
private String userRoleName;
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "UserRoleId", unique = true, nullable = false)
public int getUserRoleId() {
return userRoleId;
}
public void setUserRoleId(int userRoleId) {
this.userRoleId = userRoleId;
}
@Column(name = "UserRoleName", unique = true, nullable = false)
public String getUserRoleName() {
return userRoleName;
}
public void setUserRoleName(String userRoleName) {
this.userRoleName = userRoleName;
}
}
这里是User类的一部分
@Entity
@Table(name="Users")
public class User {
private int userId;
private String firstName;
private String lastName;
private String userName;
private String password;
private String phone;
private String email;
private UserRole userRole;
private List<Meeting> meetings;
private List<MeetingInvitation> meetingInvitationsSend;
private List<MeetingInvitation> meetingInvitationsReceived;
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "UserId", unique = true, nullable = false)
public int getUserId() {
return userId;
}
....
@ManyToOne(targetEntity=UserRole.class)
@JoinColumn (name="userRole")
public UserRole getUserRole() {
return userRole;
}
public void setUserRole(UserRole userRole) {
this.userRole = userRole;
}
}
我收到此错误 初始SessionFactory创建failed.org.hibernate.AnnotationException:@OneToOne或User.userRole上的@ManyToOne引用未知实体:UserRole
你可以看到我在用户角色类
中添加了@Entity注释答案 0 :(得分:5)
你可能只是忘了在你的hibernate配置文件中声明该类:
<mapping class="com.foo.bar.UserRole"/>
另请注意,targetEntity=UserRole.class
是不必要的,因为您的getter会返回UserRole
。 Hibernate将从getter的返回类型中推导出目标实体。