有四张表:
--Edu_Admin管理员表
--角色表
create table Edu_Role(
id int primary key identity(1,1) NOT NULL,
create_date datetime not null,
modify_date datetime not null,
name varchar(255) not null,
[description] varchar(255) default null,
is_system bit not null,
)
--角色权限表
create table Edu_RoleAuthority(
[role] int references Edu_Role(id) not null,
authorities varchar(255) not null,
)
--管理员角色表
create table Edu_AdminRole(
admins int references Edu_Admin(id) not null,
roles int references Edu_Role(id) not null,
)
当执行修改Edu_Admin时,打印的查询语句为:
select roles0_.admins as admins1_0_0_, roles0_.roles_id as roles_id2_1_0_, role1_.id as id1_29_1_, role1_.create_date as create_d2_29_1_, role1_.modify_date as modify_d3_29_1_, role1_.description as descript4_29_1_, role1_.is_system as is_syste5_29_1_, role1_.name as name6_29_1_ from Edu_AdminRole roles0_ inner join Edu_Role role1_ on roles0_.roles_id=role1_.id where roles0_.admins=? 信息:列名 'roles_id' 无效
原因是映射文件配置有误:
Admin.java中:
private Set<Role> roles = new HashSet<Role>(0);
@NotEmpty
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "Edu_AdminRole", joinColumns = @JoinColumn(name = "admins"), inverseJoinColumns = @JoinColumn(name="roles"))
public Set<Role> getRoles() {
return this.roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
Role.java:
@Entity
@Table(name = "Edu_Role")
public class Role extends BaseEntity {
private static final long serialVersionUID = 4810369605190930174L;
private String name;
private String description;
private Boolean isSystem;
private List<String> authorities = new ArrayList<String>();
private Set<Admin> admins = new HashSet<Admin>();
@Column(name = "name", nullable = false)
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
@Column(name = "description", nullable = false)
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
@Column(name = "is_system", nullable = false, updatable = false)
public Boolean getIsSystem() {
return this.isSystem;
}
public void setIsSystem(Boolean isSystem) {
this.isSystem = isSystem;
}
@ElementCollection
@CollectionTable(name = "Edu_RoleAuthority", joinColumns = @JoinColumn(name = "role"))
public List<String> getAuthorities() {
return this.authorities;
}
public void setAuthorities(List<String> authorities) {
this.authorities = authorities;
}
@ManyToMany(mappedBy = "roles", fetch = FetchType.LAZY)
public Set<Admin> getAdmins() {
return this.admins;
}
public void setAdmins(Set<Admin> admins) {
this.admins = admins;
}
}
只用Admin.java实体与Role.java实体即可,中间表不配置。默认若不配置Admin.java中的joinColumns与inverseJoinColums就会自动以为是实体对象明+主键字段名,但是数据库字段是Edu_AdminRole中是admins与roles。Role.java中的@CollectionTable中joinColumns同理
同案例文章:http://lanhuidong.iteye.com/blog/1735905