我正在使用Spring数据JPA,并正在建立我的第一个ManyToMany关系。我将第一个对象“用户”定义为:
import javax.persistence.*;
import java.util.Set;
@Entity
@Table(name = "SMX0_PAR_USER", schema = "SMX0_INPUT_DAY")
public class User {
@Id
private String userID;
private String username;
@ManyToMany
@JoinTable(
name = "SMX0_PAR_USER_ROLE",
schema = "SMX0_INPUT_DAY",
joinColumns = @JoinColumn(name = "USER_ID", referencedColumnName = "userID"),
inverseJoinColumns = @JoinColumn(name = "ROLE_ID", referencedColumnName = "roleID")
)
private Set<Role> roleSet;
protected User(){
}
public User(String userID, String username){
this.userID = userID;
this.username = username;
}
第二个对象“角色”定义为:
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import java.util.Set;
@Entity
@Table(name = "SMX0_PAR_ROLE", schema = "SMX0_INPUT_DAY")
public class Role {
@Id
private int roleID;
private String rolename;
@ManyToMany(mappedBy = "roleSet")
private Set<User> userSet;
protected Role(){
}
public Role(int roleID, String role){
this.roleID = roleID;
this.rolename = role;
}
尝试访问其中包含以下百里香代码的页面时:
<tr th:each="user : ${users}">
<td th:text="${user.getUserID()}">user ID</td>
<td th:text="${user.getUsername()}">username</td>
<td><span th:each="role : ${user.getRoleSet()}">
<span th:text="${role.getRolename()}">rolename</span>
</span></td>
</tr>
我得到例外:
org.thymeleaf.exceptions.TemplateInputException: An error happened during template parsing (template: "class path resource [templates//module/userManagement/index.html]")
…
Caused by: org.attoparser.ParseException: could not extract ResultSet
…
Caused by: org.hibernate.exception.SQLGrammarException: could not extract ResultSet
…
Caused by: java.sql.SQLSyntaxErrorException: ORA-00904: "ROLESET0_"."ROLE_ID": invalid identifier
这是怎么回事,当我将联接表名称显式设置为其他名称时,为什么会引用诸如“ ROLESET0_”之类的名称?我该如何强制使用已经给出的表名?
答案 0 :(得分:1)
ROLESET0_
是hibernate在其生成的查询中分配的别名。如果您设置spring.jpa.show-sql=true
以查看休眠产生的完整查询,可能会有所帮助。您还可以设置spring.jpa.properties.hibernate.format_sql=true
使其更具可读性。
答案 1 :(得分:0)
尝试为两个类中的所有字段添加注释@Column (name = "YourColumnName")
。
referencedColumnName
参数也应该是此外键列引用的列的名称。
public class User {
@Id
@Column(name = "YourColumnName")
private int roleID;
@Column(name = "YourColumnName")
private String rolename;
@ManyToMany
@JoinTable(
name = "SMX0_PAR_USER_ROLE",
schema = "SMX0_INPUT_DAY",
joinColumns = @JoinColumn(name = "USER_ID", referencedColumnName = "YourColumnName"),
inverseJoinColumns = @JoinColumn(name = "ROLE_ID", referencedColumnName ="YourColumnName"))
.....
}
public class Role {
@Id
@Column(name = "YourColumnName")
private int roleID;
@Column(name = "YourColumnName")
private String rolename;
.......
}