Hibernate映射Map
一、POJO
package example.start.map;
import java.util.HashMap;
import java.util.Map;
public class Person
{
private int id;
private String name;
private int age;
private Map scores = new HashMap();
public Person()
{
}
public int getId()
{
return id;
}
public void setId(int id)
{
this.id = id;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
public Map getScores()
{
return scores;
}
public void setScores(Map scores)
{
this.scores = scores;
}
}
二、映射文件
<?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>
<class name="example.start.map.Person" table="person">
<id name="id" column="personid">
<generator class="identity"/>
</id>
<property name="name" type="string">
<column name="name"/>
</property>
<property name="age" type="integer">
<column name="age" />
</property>
<map name="scores" table="score">
<key column="personid" not-null="true"/>
<map-key column="xueke" type="string"/>
<element column="fenshu" type="double"/>
</map>
</class>
</hibernate-mapping>
三、测试类
package example.start.map;
import java.util.HashMap;
import java.util.Map;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.HibernateSessionFactory;
public class CreateAndStorePerson
{
public static void main(String[] args)
{
Session session = HibernateSessionFactory.getSession();
Transaction tx = session.beginTransaction();
Person yeeku = new Person();
yeeku.setAge(22);
yeeku.setName("哈哈map");
Map s = new HashMap();
double a = 100;
double b = 95.5;
s.put("数据结构",a);
s.put("操作系统",b);
yeeku.setScores(s);
session.save(yeeku);
tx.commit();
HibernateSessionFactory.closeSession();
}
}
需要使用<map-key column="xueke" type="string"/>来对应每一个key,使用map的时候是key -- value