Multiple Criteria avec l'annotation ElementCollection
Bonjour à tous,
J'ai créé une classe Foo comme ceci.
De ce fait, je me retrouve avec 2 tables foo et foo_attributes.
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
|
@Entity
@Table
public class Foo {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private long id;
@Column
private String name;
@ElementCollection
@MapKeyColumn(name="attr_key")
@Column(name="attr_val")
@CollectionTable(name="foo_attributes", joinColumns=@JoinColumn(name="foo_id")
private Map<String, String> attributes = new HashMap<String, String>();
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Map<String, String> getAttributes() {
return attributes;
}
public void setAttributes(Map<String, String> attributes) {
this.attributes = attributes;
}
public void setAttribute(String k, String v) {
this.attributes.put(k, v);
}
public String getAttribute(String k) {
return this.attributes.get(k);
}
} |
Lorsque j'ajoute, supprime ou modifie, je n'ai pas de soucis. Exemple de code :
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
|
Foo foo1 = new Foo();
foo1.setName("test 2");
foo1.setAttribute("key1", "val1");
foo1.setAttribute("key2", "val2");
Foo foo2 = new Foo();
foo2.setName("test 2");
foo2.setAttribute("key1", "val1");
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
session.saveOrUpdate(foo1);
session.saveOrUpdate(foo2);
tx.commit();
} catch (Exception e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}
HibernateUtil.closeQuietly(session); |
par contre lorsque je veux exploiter les Criteria, je rencontre le soucis suivant. J'arrive bien à trouver mes Foo qui posséde un couple clef/valeur spécifique.
Voici mon code pour la récupération d'une liste qui possède un certains couple clef/valeur :
Code:
1 2 3 4 5 6 7 8 9 10 11 12 13
|
public List<Foo> findFooByAttribute(String key, String value) {
Session session = HibernateUtil.getSessionFactory().openSession();
Criteria criteria = session.createCriteria(Foo.class);
criteria.createCriteria("attributes").add(Restrictions.and(
Restrictions.eq("indices", key),
Restrictions.eq("elements", value)
)
);
List result = criteria.list();
HibernateUtil.closeQuietly(session);
return result
} |
Par contre, comment faire pour sélectionner tous les Foo qui possédent (AND) plusieurs couple de clefs/valeurs ?
Code:
1 2 3 4 5 6 7 8 9 10 11
|
public List<Foo> findFooByAttribute(Map<String, String> attributes) {
Session session = HibernateUtil.getSessionFactory().openSession();
Criteria criteria = session.createCriteria(Foo.class);
// Critère de recherche ??????
List result = criteria.list();
HibernateUtil.closeQuietly(session);
return result
} |
Une idée ?
En vous remerciant