Come raggiungere & # 8220; non in & # 8221; utilizzando restrizioni e criteri in ibernazione?
-
10-07-2019 - |
Domanda
Ho un elenco di categorie. Ho bisogno di un elenco di categoria escludendo 2,3 righe. Possiamo raggiungere l'ibernazione usando Criteri e restrizioni?
Soluzione
La tua domanda non è chiara. Supponendo " Categoria " è un'entità radice e "2,3" sono id (o valori di alcune proprietà della categoria ") che puoi escluderli usando quanto segue:
Criteria criteria = ...; // obtain criteria from somewhere, like session.createCriteria()
criteria.add(
Restrictions.not(
// replace "id" below with property name, depending on what you're filtering against
Restrictions.in("id", new long[] {2, 3})
)
);
Lo stesso può essere fatto con DetachedCriteria
.
Altri suggerimenti
Session session=(Session) getEntityManager().getDelegate();
Criteria criteria=session.createCriteria(RoomMaster.class);
//restriction used or inner restriction ...
criteria.add(Restrictions.not(Restrictions.in("roomNumber",new String[] { "GA8", "GA7"})));
criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
List<RoomMaster> roomMasters=criteria.list();
Per i nuovi criteri dalla versione Hibernate 5.2:
CriteriaBuilder criteriaBuilder = getSession().getCriteriaBuilder();
CriteriaQuery<Comment> criteriaQuery = criteriaBuilder.createQuery(Comment.class);
List<Long> ids = new ArrayList<>();
ids.add(2L);
ids.add(3L);
Root<Comment> root = getRoot(criteriaQuery);
Path<Object> fieldId = root.get("id");
Predicate in = fieldId.in(ids);
Predicate predicate = criteriaBuilder.not(in);
criteriaQuery
.select(root)
.where(predicate);
List<Comment> list = getSession()
.createQuery(criteriaQuery)
.getResultList();
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow