在构造系统原型阶段,由于需求尚未确定,程序中的POJO会在开发过程中存在相当大的变动,于是在Hibernate3中引入了动态模型的概念。如此不需要事先实际定义POJO。
数据库DDL如下:
- CREATE TABLE user (
- id INT(11) NOT NULL auto_increment PRIMARY KEY,
- name VARCHAR(100) NOT NULL default '',
- age INT
- );
User.hbm.xml配置文件中设定entity-name属性(属性值为查找的唯一标示符,不可重复)。
- <?xml version="1.0" encoding="UTF-8"?>
- <!DOCTYPE hibernate-mapping PUBLIC
- "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
- "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
- <hibernate-mapping>
- <class entity-name="com.hb3.pack_06.model.DynamicUserModel" table="user">
-
- <id name="id" column="id" type="java.lang.Integer">
- <generator class="native"/>
- </id>
- <property name="name"
- column="name"
- type="java.lang.String"/>
-
- <property name="age"
- column="age"
- type="java.lang.Integer"/>
- </class>
-
- </hibernate-mapping>
修改hibernate.cfg.xml配置文件:
......
<mapping resource="com/hb3/pack_06/model/User.hbm.xml" />
......
测试代码如下:
- package com.hb3.pack_06;
- import java.util.HashMap;
- import java.util.Map;
- import org.hibernate.Session;
- import org.hibernate.SessionFactory;
- import org.hibernate.Transaction;
- import org.hibernate.cfg.Configuration;
- public class BusinessService {
- public static void main(String[] args) {
-
- Configuration config = new Configuration().configure();
- SessionFactory sessionFactory = config.buildSessionFactory();
- Session session = sessionFactory.openSession();
- Map<String, Object> userMap = new HashMap<String, Object>();
- userMap.put("name", "shenbin");
- userMap.put("age", new Integer(28));
-
- Transaction tx = session.beginTransaction();
- session.save("com.hb3.pack_06.model.DynamicUserModel", userMap);
- tx.commit();
-
- session.close();
- session = sessionFactory.openSession();
-
- userMap = (Map) session.load("com.hb3.pack_06.model.DynamicUserModel", new Integer(1));
- System.out.println(userMap.get("name"));
- System.out.println(userMap.get("age"));
-
- session.close();
- sessionFactory.close();
- }
- }
ExtJS教程-
Hibernate教程-
Struts2 教程-
Lucene教程