我对 Ebean 有疑问。我有通常的对象 PsecUser、PsecRoles 和 PsecPermission。一个用户可以有很多权限或角色,一个角色可以有很多权限。这里的代码(摘录):
@Entity
public class PsecPermission {
@Id
@GeneratedValue
private Long id;
@Column(unique=true, nullable=false)
private String name;
@Column(nullable=false)
private String type = PsecBasicPermission.class.getName();
@Column(nullable=false)
private String target;
@Column(nullable=false)
private String actions;
}
@Entity
public class PsecRole {
@Id
@GeneratedValue
private Long id;
@Column(unique=true, nullable=false)
private String name;
@Temporal(TemporalType.TIMESTAMP)
private Date lastUpdate;
@ManyToMany(fetch=FetchType.EAGER)
private List<PsecPermission> psecPermissions;
private boolean defaultRole = false;
}
我写了以下帮助方法:
public PsecRole createOrUpdateRole(String name, boolean defaultRole, String... permissions) {
PsecRole result = server.find(PsecRole.class).
where().eq("name", name).findUnique();
if (result == null) {
result = new PsecRole();
result.setName(name);
}
final List<PsecPermission> permissionObjects = server.find(PsecPermission.class).
where().in("name", (Object[])permissions).findList();
result.setPsecPermissions(permissionObjects);
result.setDefaultRole(defaultRole);
final Set <ConstraintViolation <PsecRole>> errors =
Validation.getValidator().validate(result);
if (errors.isEmpty()) {
server.save(result);
server.saveManyToManyAssociations(result, "psecPermissions");
} else {
log.error("Can't save role: " + name +"!");
for (ConstraintViolation <PsecRole> constraintViolation : errors) {
log.error(" " + constraintViolation);
}
}
return result;
}
并尝试以下测试:
@Test
public void testCreateOrUpdateRole() {
String[] permNames = {"Test1", "Test2", "Test3"};
List <PsecPermission> permissions = new ArrayList <PsecPermission>();
for (int i = 0; i < permNames.length; i++) {
helper.createOrUpdatePermission(permNames[i], "target"+ i, "actions" +i);
PsecPermission perm = server.find(PsecPermission.class).where().eq("name", permNames[i]).findUnique();
assertThat(perm.getTarget()).isEqualTo("target" + i);
assertThat(perm.getActions()).isEqualTo("actions" + i);
permissions.add(perm);
}
PsecRole orgRole = helper.createOrUpdateRole(ROLE, false, permNames);
testRole(permNames, orgRole);
PsecRole role = server.find(PsecRole.class).where().eq("name", ROLE).findUnique();
testRole(permNames, role);
}
private void testRole(String[] permNames, PsecRole role) {
assertThat(role).isNotNull();
assertThat(role.getName()).isEqualTo(ROLE);
assertThat(role.isDefaultRole()).isEqualTo(false);
assertThat(role.getPermissions()).hasSize(permNames.length);
}
如果它检查读取角色的权限数量,则会失败。始终为0。我查看了数据库,发现psec_role_psec_permission 始终为空。
知道代码有什么问题吗?
您可以从https://github.com/opensource21/ebean-samples/downloads获得一个纯 Ebean 示例,它使用来自 ebean 的 eclipse-plugin。