在構造系統原型階段,由於需求尚未確定,程序中的POJO會在開發過程中存在相當大的變動,於是在Hibernate3中引入了動態模型的概念。如此不需要事先實際定義POJO。
數據庫DDL如下:
1.CREATE TABLE user (
2. id INT(11) NOT NULL auto_increment PRIMARY KEY,
3. name VARCHAR(100) NOT NULL default '',
4. age INT
5.);
User.hbm.xml配置文件中設定entity-name屬性(屬性值為查找的唯一標示符,不可重復)。
1.<?xml version="1.0" encoding="UTF-8"?>
2. 3.<!DOCTYPE hibernate-mapping PUBLIC
4. "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
5. "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> 6. 7.<hibernate-mapping> 8. 9. <class entity-name="com.hb3.pack_06.model.DynamicUserModel" table="user"> 10.
11. <id name="id" column="id" type="java.lang.Integer">
12. <generator class="native"/>
13. </id> 14. 15. <property name="name"
16. column="name"
17. type="java.lang.String"/>
18.
19. <property name="age"
20. column="age"
21. type="java.lang.Integer"/>
22. </class> 23.
24.</hibernate-mapping>
修改hibernate.cfg.xml配置文件:
......
<mapping resource="com/hb3/pack_06/model/User.hbm.xml" />
......
測試代碼如下:
1.package com.hb3.pack_06;
2.
3.import java.util.HashMap;
4.import java.util.Map;
5. 6.import org.hibernate.Session;
7.import org.hibernate.SessionFactory;
8.import org.hibernate.Transaction;
9.import org.hibernate.cfg.Configuration;
10. 11.public class BusinessService {
12. 13. public static void main(String[] args) {
14.
15. Configuration config = new Configuration().configure();
16. SessionFactory sessionFactory = config.buildSessionFactory();
17. Session session = sessionFactory.openSession();
18. 19. Map<String, Object> userMap = new HashMap<String, Object>();
20. userMap.put("name", "shenbin");
21. userMap.put("age", new Integer(28));
22.
23. Transaction tx = session.beginTransaction();
24. session.save("com.hb3.pack_06.model.DynamicUserModel", userMap);
25. tx.commit();
26.
27. session.close();
28. session = sessionFactory.openSession();
29.
30. userMap = (Map) session.load("com.hb3.pack_06.model.DynamicUserModel", new Integer(1));
31. System.out.println(userMap.get("name"));
32. System.out.println(userMap.get("age"));
33.
34. session.close();
35. sessionFactory.close();
36. }
37.}