Hibernate version: 3
Hi Guys,
i need help with creating a criteria statement. I have the following classes (not my real project, simplyfied example):
Entity
Code:
import java.util.Map;
public class Person {
private long id;
private String name;
private Map test;
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 getTest() {
return test;
}
public void setTest(Map test) {
this.test = test;
}
}
Mapping File
Code:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="de.test">
<class name="Person" table="personen">
<id name="id">
<generator class="native" />
</id>
<property name="name" />
<map name="test" table="test">
<key column="id" />
<index column="test_name" type="string" />
<element column="test_value" type="string" />
</map>
</class>
</hibernate-mapping>
Test
Code:
package de.test;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Expression;
import org.hibernate.criterion.Restrictions;
public class Runner {
/**
* @param args
*/
public static void main(String[] args) {
SessionFactory sessionFactory = new Configuration().configure(
"hibernate.cfg.mapping.xml").buildSessionFactory();
Session session = sessionFactory.getCurrentSession();
Transaction transaction = session.beginTransaction();
Person p = new Person();
p.setName("Fred");
Map<String, String> map = new HashMap<String, String>();
map.put("testKey", "testValue");
p.setTest(map);
session.save(p);
Criteria crit = session.createCriteria(Person.class);
crit.setMaxResults(50);
crit.add(Expression.eq("name", "Fred"));
// TODO Key from test has to be testKey and Value has to be testValue
List<Person> personen = crit.list();
transaction.commit();
for (Person person : personen) {
System.out.println(person.getName());
System.out.println(person.getTest().get("testKey"));
}
sessionFactory.close();
}
}
The entity Person has a HashMap. I want to create a Select-Statement using the Criteria-API (SQL in Criteria is Ok too) with checking a given key and a given value.
Pseudo code:
Give me Person with name Fred and a Hashmap with the value-key-combinaton testKey, valueKey
Can i do this? and how can i do this?
Thx for your help!