簡単な説明:ユーザーとそれに対応する権利があります。それらの情報でデータベースを維持できるようにしたいと思います。
これは私が使用するソリューションです:
豆 :
...
@Entity
public class User implements Serializable {
...
@OneToMany(mappedBy = "idu", cascade = {CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH}, orphanRemoval = true)
private List<Userrights> userRightsList;
...
}
...
@Entity
public class Userrights implements Serializable {
...
@JoinColumn(name = "idu", referencedColumnName = "idu")
@ManyToOne
private User idu;
...
}
バネ :
@Component
public class UserBean implements IUser {
@Autowired
private MyPersistenceContext<User> pc;
...
@Transactional
@Override
public void update(User user) throws Exception {
pc.update(user, UPDATE_ERR);
}
...
}
@Component
public class MyPersistenceContext<T> {
@PersistenceContext
protected EntityManager EM;
...
public void insert(T object, String errMsg) {
EM.persist(object);
}
public void update(T object, String errMsg) {
EM.merge(object);
}
...
}
public void delete(T object, String errMsg) {
T forDeletion = null;
if (!EM.contains(object)) {
forDeletion = EM.merge(object);
}
if (forDeletion != null) {
EM.remove(forDeletion);
}
}
テスト :
@Test
public void testDb_InsertOrUpdateOfExistinguserRights() throws Exception {
User u = null;
try {
u = IAS.DS().user().getByUsername("kor1 username");
} catch (Exception e) {
}
List<Userrights> lur = new ArrayList<>();
boolean newUser = true;
if (u != null) {
newUser = false;
lur = IAS.DS().userRights().get(u);
} else {
u = new User("kor1", "kor1 prezime", "kor1 username", "kor1 pass");
}
if (lur.isEmpty()) {
lur.add(new Userrights(u, IAS.DS().roles().get(1)));
lur.add(new Userrights(u, IAS.DS().roles().get(2)));
lur.add(new Userrights(u, IAS.DS().roles().get(4)));
} else {
lur.clear();
lur.add(new Userrights(u, IAS.DS().roles().get(1)));
lur.add(new Userrights(u, IAS.DS().roles().get(5)));
}
u.setUserRightsList(lur);
if (!newUser) {
IAS.DS().user().update(u);
} else {
IAS.DS().user().insert(u);
}
}