public class HibernateFilterTest extends ... {
@Autowired
private TransactionTemplate transactionTemplate;
@Autowired
private SessionFactory sessionFactory;
@Test
public void testManyToManyFilterGet() {
final List<MyUserDBO> users = new ArrayList<>();
final List<MyRoleDBO> roles = new ArrayList<>();
this.doInTransaction(() -> {
roles.add(this.save(this.role("R1", false)));
roles.add(this.save(this.role("R2", false)));
users.add(this.save(this.user("A", true, roles.get(0), roles.get(1))));
});
this.doInTransaction(() -> {
final MyUserDBO dbUser = this.get(MyUserDBO.class, users.get(0).getId());
Assert.assertNotNull(dbUser);
Assert.assertThat(dbUser.getRoles(), Matchers.empty());
});
}
@Test
public void testManyToManyFilterGetAll() {
final List<MyUserDBO> users = new ArrayList<>();
final List<MyRoleDBO> roles = new ArrayList<>();
this.doInTransaction(() -> {
roles.add(this.save(this.role("R1", false)));
roles.add(this.save(this.role("R2", false)));
users.add(this.save(this.user("A", true, roles.get(0), roles.get(1))));
});
this.doInTransaction(() -> {
final List<MyUserDBO> dbUsers = this.getAll(MyUserDBO.class);
Assert.assertNotNull(dbUsers);
Assert.assertThat(dbUsers.size(), Matchers.is(1));
Assert.assertThat(dbUsers.get(0).getRoles(), Matchers.empty());
});
}
private void doInTransaction(final Runnable r) {
this.transactionTemplate.execute(new TransactionCallback<Object>() {
@Override
public Object doInTransaction(final TransactionStatus status) {
r.run();
return null;
}
});
}
private Session getSession() {
final Session session = this.sessionFactory.getCurrentSession();
session.enableFilter("activeUserFilter");
session.enableFilter("activeRoleFilter");
return session;
}
private <T extends AbstractMyDBO> T save(final T dbo) {
this.getSession().save(dbo);
return dbo;
}
@SuppressWarnings("unchecked")
private <T> T get(final Class<T> clazz, final Serializable id) {
return (T) this.getSession().get(clazz, id);
}
@SuppressWarnings("unchecked")
private <T> List<T> getAll(final Class<T> clazz) {
return this.getSession().createCriteria(clazz).setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY).list();
}
private MyUserDBO user(final String name, final boolean active, final MyRoleDBO... roles) {
final MyUserDBO user = new MyUserDBO();
user.setName(name);
user.setActive(active ? 1 : 0);
user.setRoles(new HashSet<>(Arrays.asList(roles)));
return user;
}
private MyRoleDBO role(final String name, final boolean active) {
final MyRoleDBO role = new MyRoleDBO();
role.setName(name);
role.setActive(active ? 1 : 0);
return role;
}
}