我有两个类,它们之间有两个关系。
用户类:
@Entity
@Table(name="User")
public class User implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="Id")
private long id;
@OneToMany(cascade = CascadeType.ALL, fetch=FetchType.EAGER, mappedBy="admin")
private Set<Group> ownedGroup;
@ManyToMany(cascade = CascadeType.ALL, fetch=FetchType.EAGER, mappedBy="members")
private Set<Group> memberGroups;
//.......
}
群组类:
@Entity
@Table(name="Group")
public class Group implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="Id")
private long id;
@NotNull
@ManyToOne(cascade=CascadeType.ALL, fetch=FetchType.EAGER)
@JoinColumn(name="Admin", referencedColumnName="Id")
private User admin;
@ManyToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER)
@JoinTable(name = "Group_User",
joinColumns = @JoinColumn(name = "Group"),
inverseJoinColumns = @JoinColumn(name = "User"))
private Set<User> members;
//....
}
当我想启动应用程序时,我遇到了这个例外:
org.hibernate.AnnotationException: Use of @OneToMany or @ManyToMany targeting an unmapped class: com.myproject.model.User.memberGroups[com.querydsl.core.group.Group]
我看到了其他类似的帖子,但显然他们没有使用javax.persistence.Entity
,这是导致此错误的根本原因。知道如何解决这个问题吗?
答案 0 :(得分:1)
群组是保留关键字。使用反引号来转义保留的关键字。查看this回答。
@Table(name = "`Group`")
不幸的是,您的@ManyToMany
映射不正确。
像这样更新您的Group
实体:
@Entity
@Table(name="`Group`") // Change your table name
public class Group implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="Id")
private long id;
@NotNull
@ManyToOne(cascade=CascadeType.ALL, fetch=FetchType.EAGER)
@JoinColumn(name="Admin", referencedColumnName="Id")
private User admin;
@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinTable(
name = "Group_User",
joinColumns = @JoinColumn(name = "group_id", referencedColumnName = "id"), //Give a column name 'group_id' and map it to Group primary key id
inverseJoinColumns = @JoinColumn(name = "user_id", referencedColumnName = "id") //Give a column name 'user_id' and map it to User primary key id.
)
private Set<User> members;
...
}