`
yaerfeng1989
  • 浏览: 223980 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

用Hibernate实现领域对象的自定义字段

阅读更多

原创整理不易,转载请注明出处:用Hibernate实现领域对象的自定义字段

代码下载地址:http://www.zuidaima.com/share/1724475837090816.htm

导言

在开发企业级业务应用(企业规模)时,客户往往要求在不修改系统源代码的情况下对应用对象模型的扩展性提供支持。利用可扩展域模型可以实现新功能的开发,而不需要额外的精力和成本

  1. 应用的使用周期将被延长; 
  2. 外部因素改变时,系统工作流也可以随之被修改;
  3. 已经被部署的应用可以被“设定”,使其符合企业的特定情况。

完成以上功能需求最简单、最具成本效益的方法应该是在应用中实现支持自定义字段的可扩展业务实体。

 

什么是“自定义字段”?

什么是自定义字段?最终用户如何从中受益呢?自定义字段是一种对象属性,它不是由系统开发人员在开发阶段创建的,而是在系统实际使用中由系统用户在不改变任何源代码的情况下添加到对象中的。

可能会需要哪些功能呢?

让我们举一个CRM(客户关系管理系统)应用的例子来领会一下。 假设我们有一个客户“Client”对象。理论上讲,这个对象可以有任意多的各种属性:几个email地址、若干电话号码和地址等。某公司的销售部门可能会使用其中一个属性,但其它公司却会完全忽略它。将最终用户可能会用到的(也可能不会用到的)所有属性都加入到对象当中,这是很浪费并很不合理的。

既然这样,允许系统用户(或者管理员)来创建他们公司的销售经理们需要的属性,也许是更好的做法。例如,如果有需要,管理员可以创建“工作电话”或者“家庭地址”等属性。 此外,这些属性还可以用到数据过滤和查询中去。

简要说明

在实施Enterra CRM项目时,客户提出了在应用中支持自定义字段的目标,“系统管理员不需要重启系统就可以创建或删除自定义字段”。

系统后端开发使用了Hibernate 3.0框架,这个因素(技术约束)是考虑实现这个需求的关键。

实现

在这一章里面我们将介绍采用Hibernate框架实现的关键环节。

环境

例子的开发环境如下所示: 

  1. JDK 1.5;
  2. Hibernate 3.2.0框架;
  3. MySQL 4.1。

限制

简单起见,我们不使用Hibernate EntityManager(译注一)和Hibernate Annotations(译注二)。持久化对象的映射关系将基于xml映射文件。此外,值得一提的是,由于演示用例是基于xml映射文件管理映射,所以使用Hibernate Annotations的话,它将不能正常运行。

功能定义

我们必须实现一种机制——允许实时地创建/删除自定义字段而不重启应用,向其中添加值并保证值能保存到应用的数据库中。此外我们还必须保证自定义字段能用于查询。

解决方案

域模型

首先,我们需要一个进行试验的业务实体类。假设是Contact类,它有两个持久化字段:id和name。

但是,除了这些持久不变的字段外,这个类还应该有一些存储自定义字段值的数据结构。Map也许是针对于此的理想数据结构。

为所有支持自定义字段的业务实体创建一个基类——CustomizableEntity,它包含处理自定义字段的Map类型属性customProperties:

 

01 package com.enterra.customfieldsdemo.domain;
02  
03  import java.util.Map;
04  import java.util.HashMap;
05  
06  public abstract class CustomizableEntity {
07  
08 private Map customProperties;
09  
10 public Map getCustomProperties() {
11  if (customProperties==null)
12  customProperties=new HashMap();
13  return customProperties;
14 }
15 public void setCustomProperties(Map customProperties) {
16  this.customProperties=customProperties;
17 }
18  
19 public Object getValueOfCustomField(String name) {
20  return getCustomProperties().get(name);
21 }
22  
23 public void setValueOfCustomField(String name, Object value) {
24  getCustomProperties().put(name, value);
25 }
26  
27 }

清单1-基类CustomizableEntity

Contact类继承上面的基类:

01 package com.enterra.customfieldsdemo.domain;
02  
03  import com.enterra.customfieldsdemo.domain.CustomizableEntity;
04  
05  public class Contact extends CustomizableEntity {
06  
07 private int id;
08 private String name;
09  
10 public int getId() {
11  return id;
12 }
13  
14 public void setId(int id) {
15  this.id=id;
16 }
17  
18 public String getName() {
19  return name;
20 }
21  
22 public void setName(String name) {
23  this.name=name;
24 }
25  
26 }

清单2-继承自CustomizableEntity的Contact类

别忘了这个类的映射文件:

01 <?xml version="1.0"encoding="UTF-8"?>
02  
03  <! DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN"
05  
06  <hibernate-mapping auto-import="true" default-access="property" default-cascade="none" default-lazy="true">
07  
08  <class abstract="false" name="com.enterra.customfieldsdemo.domain.Contact" table="tbl_contact">
09  
10  <id column="fld_id" name="id">
11  <generator class="native"/>
12  </id>
13  
14  <property name="name" column="fld_name" type="string"/>
15  <dynamic-component insert="true" name="customProperties" optimistic-lock="true" unique="false" update="true">
16  </dynamic-component>
17  </class>

清单3-Contact类的映射

注意id和name属性都是当作普通的属性来处理,但对于customProperties,我们使用了 (动态组件)标签。Hibernate 3.2.0GA文档里面关于dynamic-component的要点如下:


<dynamic-component>映射的语义与<component>是一样的。该映射的优点是仅仅通过编辑映射文件,就能在部署时确定bean的现行属性。使用DOM解析器,映射文件的运行时操作也是可行的。甚至,你可以通过Configuration对象,来访问(和修改)Hibernate的配置时元模型。

基于Hibernate文档中的这段规则,我们来建立前面要求的功能机制。

HibernateUtil和hibernate.cfg.xml

定义了应用中的域模型之后,我们需要创建Hibernate框架运转的必要条件。为此我们必须创建一个配置文件hibernate.cfg.xml和一个处理Hibernate核心功能的类。

01 <?xml version='1.0'encoding='utf-8'?>
02  
03  <! DOCTYPE hibernate-configuration
04  
05  PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN"
06  
08  
09  <hibernate-configuration>
10  
11  <session-factory>
12  
13  <property name="show_sql">true </property>
14  <property name="dialect">
15 org.hibernate.dialect.MySQLDialect </property>
16  <property name="cglib.use_reflection_optimizer">true </property>
17  <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver </property>
18  <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/custom_fields_test </property>
19  <property name="hibernate.connection.username">root </property>
20  <property name="hibernate.connection.password"></property>
21  <property name="hibernate.c3p0.max_size"> </property>
22  <property name="hibernate.c3p0.min_size"> </property>
23  <property name="hibernate.c3p0.timeout"> </property>
24  <property name="hibernate.c3p0.max_statements"> </property>
25  <property name="hibernate.c3p0.idle_test_period"> </property>
26  <property name="hibernate.c3p0.acquire_increment"> </property>
27  <property name="hibernate.jdbc.batch_size"> </property>
28  <property name="hibernate.hbm2ddl.auto"> update </property>
29  </session-factory>
30  </hibernate-configuration>

清单4-Hibernate配置文件

hibernate.cfg.xml文件没有什么需要特别关注的,除了下面这句:

1 <property name="hibernate.hbm2ddl.auto"> update </property>

清单5-使用auto-update(自动更新)

后面我们将详细解释其目的,并更多地讲解没有它我们怎样实现。HibernateUtil类有好几种实现方式。由于Hibernate配置文件内容的不同,我们的实现与已知的那些将有一点儿不同。

 

01 package com.enterra.customfieldsdemo;
02  
03  import org.hibernate. * ;
04  import org.hibernate.mapping.PersistentClass;
05  import org.hibernate.tool.hbm2ddl.SchemaUpdate;
06  import org.hibernate.cfg.Configuration;
07  import com.enterra.customfieldsdemo.domain.Contact;
08  
09  public class HibernateUtil {
10  
11 private static HibernateUtil instance;
12 private Configuration configuration;
13 private SessionFactory sessionFactory;
14 private Session session;
15  
16 public synchronized static HibernateUtil getInstance() {
17  if (instance==null) {
18  instance=new HibernateUtil();
19  }
20  return instance;
21 }
22  
23 private synchronized SessionFactory getSessionFactory() {
24  if (sessionFactory==null) {
25  sessionFactory=getConfiguration().buildSessionFactory();
26  }
27  return sessionFactory;
28 }
29  
30 public synchronized Session getCurrentSession() {
31  if (session==null) {
32  session=getSessionFactory().openSession();
33  session.setFlushMode(FlushMode.COMMIT);
34  System.out.println("session opened.");
35  }
36  return session;
37 }
38  
39 private synchronized Configuration getConfiguration() {
40  if (configuration==null) {
41  System.out.print("configuring Hibernate ");
42  try {
43  configuration=new Configuration().configure();
44  configuration.addClass(Contact.class);
45  System.out.println("ok");
46  catch (HibernateException e) {
47  System.out.println("failure");
48  e.printStackTrace();
49  }
50  }
51  return configuration;
52 }
53 public void reset() {
54  Session session=getCurrentSession();
55  if (session !=null) {
56  session.flush();
57  if (session.isOpen()) {
58  System.out.print("closing session ");
59  session.close();
60  System.out.println("ok");
61  }
62  }
63  SessionFactory sf=getSessionFactory();
64  if (sf !=null) {
65  System.out.print("closing session factory ");
66  sf.close();
67  System.out.println("ok");
68  }
69  this.configuration=null;
70  this.sessionFactory=null;
71  this.session=null;
72 }
73  
74 public PersistentClass getClassMapping(Class entityClass){
75  return getConfiguration().getClassMapping(entityClass.getName());
76 }
77 }

清单6-HibernateUtils类

除了平常的getCurrentSession()和getConfiguration()方法(这些方法对基于Hibernate的应用的常规操作是很必要的)之外,我们还需要实现像reset()和getClassMapping(Class entityClass)这样的方法。在getConfiguration()方法中,我们配置Hibernate、并将类Contact添加到配置中去。

reset()方法关闭所有Hibernate使用的资源、清除所有的设置:

 

01 public void reset() {
02  Session session=getCurrentSession();
03  if (session !=null) {
04  session.flush();
05  if (session.isOpen()) {
06  System.out.print("closing session ");
07  session.close();
08  System.out.println("ok");
09  }
10  }
11  SessionFactory sf=getSessionFactory();
12  if (sf !=null) {
13  System.out.print("closing session factory ");
14  sf.close();
15  System.out.println("ok");
16  }
17  this.configuration=null;
18  this.sessionFactory=null;
19  this.session= null;
20 }

清单7-reset()方法

getClassMapping(Class entityClass)方法返回PersistentClass对象,该对象包含相关实体映射的全部信息。特别地,对PersistentClass对象的处理允许在运行时修改实体类的属性设置。

1 public PersistentClass getClassMapping(Class entityClass) {
2  return getConfiguration().getClassMapping(entityClass.getName());
3 }

清单8-getClassMapping(Class entityClass)方法

处理映射

一旦我们有了可用的业务实体类(Contact)和与Hibernate交互的主类,我们就能开始工作了。我们能创建、保存Contact类的实例。甚至可以在Map对象customProperties里面放置一些数据,但是需要注意的是存储在Map对象customProperties里面的数据并不会被保存到数据库里。

为了保存数据,我们需要让这个机制能在类里面创建自定义字段,并且要让Hibernate知道该如何处理它们。

为了实现对类映射的处理,我们需要创建一些接口。叫它CustomizableEntityManager吧。名字应该表现出该接口管理业务实体及其内容、属性的意图:

01 package com.enterra.customfieldsdemo;
02  
03  import org.hibernate.mapping.Component;
04  
05  public interface CustomizableEntityManager {
06  public static String CUSTOM_COMPONENT_NAME= "customProperties";
07  
08  void addCustomField(String name);
09  
10  void removeCustomField(String name);
11  
12  Component getCustomProperties();
13  
14  Class getEntityClass();
15 }

清单9-CustomizableEntityManager接口

接口中重要的方法是void addCustomField(String name)和void removeCustomField(String name)。它们将分别在相应类的映射里创建、删除我们的自定义字段。

下面是实现该接口的情况:

01 package com.enterra.customfieldsdemo;
02  
03  import org.hibernate.cfg.Configuration;
04  import org.hibernate.mapping. * ;
05  import java.util.Iterator;
06  
07  public class CustomizableEntityManagerImpl implements CustomizableEntityManager {
08  private Component customProperties;
09  private Class entityClass;
10  
11  public CustomizableEntityManagerImpl(Class entityClass) {
12  this.entityClass=entityClass;
13  }
14  
15  public Class getEntityClass() {
16  return entityClass;
17  }
18  
19  public Component getCustomProperties() {
20  if (customProperties==null) {
21  Property property=getPersistentClass().getProperty(CUSTOM_COMPONENT_NAME);
22  customProperties=(Component) property.getValue();
23  }
24  return customProperties;
25  }
26  
27  public void addCustomField(String name) {
28  SimpleValue simpleValue=new SimpleValue();
29  simpleValue.addColumn(new Column("fld_" + name));
30  simpleValue.setTypeName(String.class.getName());
31  
32  PersistentClass persistentClass=getPersistentClass();
33  simpleValue.setTable(persistentClass.getTable());
34  
35  Property property=new Property();
36  property.setName(name);
37  property.setValue(simpleValue);
38  getCustomProperties().addProperty(property);
39  
40  updateMapping();
41  }
42  
43  public void removeCustomField(String name) {
44  Iterator propertyIterator=customProperties.getPropertyIterator();
45  
46  while (propertyIterator.hasNext()) {
47  Property property=(Property) propertyIterator.next();
48  if (property.getName().equals(name)) {
49  propertyIterator.remove();
50  updateMapping();
51  return;
52  }
53  }
54  }
55  
56  private synchronized void updateMapping() {
57  MappingManager.updateClassMapping(this);
58  HibernateUtil.getInstance().reset();
59  // updateDBSchema();
60  }
61  
62  private PersistentClass getPersistentClass() {
63  return HibernateUtil.getInstance().getClassMapping(this.entityClass);
64  }
65 }

清单10-接口CustomizableEntityManager的实现

首先需要指出的是,在构造CustomizableEntityManager时,我们要指定管理器操作的业务实体类。该业务实体类作为参数传递给CustomizableEntityManager的构造函数:

1 private Class entityClass;
2  
3  public CustomizableEntityManagerImpl(Class entityClass) {
4  this.entityClass=entityClass;
5 }
6  
7  public Class getEntityClass() {
8  return entityClass;
9 }

清单11-CustomizableEntityManagerImpl构造函数

现在我们应该对void addCustomField(String name)方法的实现更感兴趣:

01 public void addCustomField(String name) {
02  SimpleValue simpleValue=new SimpleValue();
03  simpleValue.addColumn(new Column("fld_" + name));
04  simpleValue.setTypeName(String.class.getName());
05  
06  PersistentClass persistentClass=getPersistentClass();
07  simpleValue.setTable(persistentClass.getTable());
08  
09  Property property= new Property();
10  property.setName(name);
11  property.setValue(simpleValue);
12  getCustomProperties().addProperty(property);
13  
14  updateMapping();
15 }

清单12-创建自定义字段

正如我们从实现中看到的一样,Hibernate在处理持久化对象的属性及其在数据库中的表示方面提供了更多的选择。下面分步讲解该方法的要素:

1)创建一个SimpleValue类对象,它指明了自定义字段的值如何被存储到字段和表所在的数据库中:

1 SimpleValuesimpleValue= new SimpleValue();
2 simpleValue.addColumn( new Column( " fld_ " + name));
3 simpleValue.setTypeName(String. class .getName());
4  
5 PersistentClass persistentClass= getPersistentClass();
6 simpleValue.setTable(persistentClass.getTable());

清单13-表创建新列

2)给持久化对象创建一个属性(property),并将动态组件添加进去,注意,这是我们为了这个目的已经计划好的:

1 Propertyproperty= new Property()
2 property.setName(name)
3 property.setValue(simpleValue)
4 getCustomProperties().addProperty(property)

清单14-创建对象属性

3)最后应该让应用修改xml文件,并更新Hibernate配置。这个可以由updateMapping()方法来完成;

阐明上面代码中另外两个get方法的用途还是很有必要的。第一个方法是getCustomProperties():

1 public Component getCustomProperties() {
2  if (customProperties==null) {
3  Property property=getPersistentClass().getProperty(CUSTOM_COMPONENT_NAME);
4  customProperties=(Component) property.getValue();
5  }
6  return customProperties;
7 }

清单15-获取组件CustomProperties

该方法找到并返回与业务实体映射中标签相对应的组件(Component)对象。

第二个方法是updateMapping():

1 private synchronized void updateMapping() {
2  MappingManager.updateClassMapping(this);
3  HibernateUtil.getInstance().reset();
4  // updateDBSchema();
5 }

清单16-updateMapping()方法

该方法负责存储更新后的持久化类映射,并且更新Hibernate的配置状态,以进一步使改变生效。

顺便,我们回过头来看看Hibernate配置中的语句: 

1 <property name="hibernate.hbm2ddl.auto"> update </property>

如果缺少该配置,我们就必须使用Hibernate工具类来执行数据库schema的更新。然而使用该设置让我们避免了那么做。

保存映射

运行时对映射的修改不会将自身保存到相应的xml映射文件中,为了使变化在应用下次的执行中活化,我们需要手动将变化保存到对应的映射文件中去。

我们使用MappingManager类来完成这件工作,该类的主要目的是将指定的业务实体的映射保存到其xml映射文件中去:

01 package com.enterra.customfieldsdemo;
02  
03  import com.enterra.customfieldsdemo.domain.CustomizableEntity;
04  import org.hibernate.Session;
05  import org.hibernate.mapping.Column;
06  import org.hibernate.mapping.Property;
07  import org.hibernate.type.Type;
08  import org.w3c.dom.Document;
09  import org.w3c.dom.Element;
10  import org.w3c.dom.Node;
11  import org.w3c.dom.NodeList;
12  import java.util.Iterator;
13  
14  public class MappingManager );
15  XMLUtil.removeChildren(node);
16  
17  Iterator propertyIterator=entityManager.getCustomProperties().getPropertyIterator();
18  while (propertyIterator.hasNext()) {
19  Property property=(Property) propertyIterator.next();
20  Element element=createPropertyElement(document, property);
21  node.appendChild(element);
22  }
23  
24  XMLUtil.saveDocument(document, file);
25  catch (Exception e) {
26  e.printStackTrace();
27  }
28  }
29  
30  private static Element createPropertyElement(Document document, Property property) {
31  Element element=document.createElement("property");
32  Type type=property.getType();
33  
34  element.setAttribute("name", property.getName());
35  element.setAttribute("column", ((Column) property.getColumnIterator().next()).getName());
36  element.setAttribute("type", type.getReturnedClass().getName());
37  element.setAttribute("not-null", String.valueOf(false));
38  
39  return element;
40  }
41 }

清单17-更新持久化类映射的工具类

该类一一执行了下面的操作:

  1. 对于指定的业务实体,定义其xml映射的位置,并加载到DOM Document对象中,以供进一步操作;
  2. 查找到Document对象中的 元素。我们将在这里存储自定义字段和我们所做的内容变化;
  3. 将该元素内嵌套的所有元素都删除;
  4. 对于负责自定义字段存储的组件所包含的任意持久化属性,我们都创建一个特定的document元素,并根据相应的属性为元素定义属性;
  5. 保存这个新建的映射文件。

虽然我们这里用了XMLUtil类(正如从代码中看到的一样)来处理XML,但是一般而言,可以换成任何一种方式来实现,不过XMLUtil已经足以加载并保存xml文件。

我们的实现如下面的清单所示:

01 import org.w3c.dom.Node;
02  import org.w3c.dom.NodeList;
03  import org.w3c.dom.Document;
04  import org.xml.sax.SAXException;
05  import javax.xml.parsers.ParserConfigurationException;
06  import javax.xml.parsers.DocumentBuilderFactory;
07  import javax.xml.parsers.DocumentBuilder;
08  import javax.xml.transform.TransformerException;
09  import javax.xml.transform.TransformerFactory;
10  import javax.xml.transform.Transformer;
11  import javax.xml.transform.OutputKeys;
12  import javax.xml.transform.stream.StreamResult;
13  import javax.xml.transform.dom.DOMSource;
14  import java.io.IOException;
15  import java.io.FileOutputStream;
16  
17  public class XMLUtil ; i--)
18  node.removeChild(childNodes.item(i));
19  }
20  
21  public static Document loadDocument(String file)
22  throws ParserConfigurationException, SAXException, IOException {
23  
24  DocumentBuilderFactory factory=DocumentBuilderFactory.newInstance();
25  DocumentBuilder builder=factory.newDocumentBuilder();
26  return builder.parse(file);
27  }
28  
29  public static void saveDocument(Document dom, String file)
30  throws TransformerException, IOException {
31  
32  TransformerFactory tf=TransformerFactory.newInstance();
33  Transformer transformer=tf.newTransformer();
34  
35  transformer.setOutputProperty(OutputKeys.DOCTYPE_PUBLIC, dom.getDoctype().getPublicId());
36  transformer.setOutputProperty(OutputKeys.DOCTYPE_SYSTEM, dom.getDoctype().getSystemId());
37  
38  DOMSource source=new DOMSource(dom);
39  StreamResult result=new StreamResult();
40  
41  FileOutputStream outputStream=new FileOutputStream(file);
42  result.setOutputStream(outputStream);
43  transformer.transform(source, result);
44  
45  outputStream.flush();
46  outputStream.close();
47  }
48 }

清单18-XML处理工具类

 

测试

我们有了所有必需的运行代码, 现在可以编写测试代码来看看一切到底是怎样工作的。第一个测试创建自定义字段“email”,创建并保存Contact类的实例,并给它定义“email”属性。

首先让我们看一下数据库表tbl_contact,它包括两个字段:fld_id和fld_name。代码如下:

01 package com.enterra.customfieldsdemo.test;
02  
03  import com.enterra.customfieldsdemo.HibernateUtil;
04  import com.enterra.customfieldsdemo.CustomizableEntityManager;
05  import com.enterra.customfieldsdemo.CustomizableEntityManagerImpl;
06  import com.enterra.customfieldsdemo.domain.Contact;
07  import org.hibernate.Session;
08  import org.hibernate.Transaction;
09  import java.io.Serializable;
10  
11  public class TestCustomEntities {
12  private static final String TEST_FIELD_NAME="email";
13  private static final String TEST_VALUE="test@test.com";
14  
15  public static void main(String[] args) {
16  HibernateUtil.getInstance().getCurrentSession();
17  
18  CustomizableEntityManager contactEntityManager=new
19  CustomizableEntityManagerImpl(Contact.class);
20  
21  contactEntityManager.addCustomField(TEST_FIELD_NAME);
22  
23  Session session=HibernateUtil.getInstance().getCurrentSession();
24  
25  Transaction tx=session.beginTransaction();
26  try {
27  
28  Contact contact=new Contact();
29  contact.setName("Contact Name 1");
30  contact.setValueOfCustomField(TEST_FIELD_NAME, TEST_VALUE);
31  Serializable id=session.save(contact);
32  tx.commit();
33  
34  contact=(Contact) session.get(Contact.class, id);
35  Object value=contact.getValueOfCustomField(TEST_FIELD_NAME);
36  System.out.println("value=" + value);
37  
38  catch (Exception e) {
39  tx.rollback();
40  System.out.println("e=" + e);
41  }
42  }
43 }

清单19-测试创建自定义字段

这个类的main方法负责执行下面的工作:

  1. 创建Contact类的CustomizableEntityManager;
  2. 创建名为“email”的自定义字段;
  3. 在事务中,我们创建一个新的Contact对象,并设置自定义字段的值为“test@test.com”;
  4. 保存Contact;
  5. 获取自定义字段“email”的值。

我们可以看到执行的结果如下:

configuring Hibernate ... ok
session opened.
closing session ... ok
closing session factory ... ok
configuring Hibernate ... ok
session opened.
Hibernate: insert into tbl_contact (fld_name, fld_email) values (?, ?)
value = test@test.com 

清单20-测试结果

在数据库里,可以看到如下所示的记录:

+--------+---------------------+----------------------+
| fld_id    | fld_name                 | fld_email                   |
+--------+---------------------+----------------------+
|     1     | Contact Name 1        | test@test.com          |
+--------+---------------------+----------------------+ 

清单21-DB结果

正如看到的那样,新的字段在运行时被创建,其值也被成功保存。

第二个测试使用新创建的字段来查询数据库:

01 import com.enterra.customfieldsdemo.HibernateUtil;
02  import com.enterra.customfieldsdemo.CustomizableEntityManager;
03  import com.enterra.customfieldsdemo.domain.Contact;
04  import org.hibernate.Session;
05  import org.hibernate.Criteria;
06  import org.hibernate.criterion.Restrictions;
07  import java.util.List;
08  
09  public class TestQueryCustomFields {
10  public static void main(String[] args) {
11  Session session=HibernateUtil.getInstance().getCurrentSession();
12  Criteria criteria=session.createCriteria(Contact.class);
13  criteria.add(Restrictions.eq(CustomizableEntityManager.CUSTOM_COMPONENT_NAME + ".email""test@test.com"));
14  List list=criteria.list();
15  System.out.println("list.size()=" + list.size());
16  }
17 }

清单22-测试自定义字段查询

Execution result:
configuring Hibernate ... ok
session opened.
Hibernate: select this_.fld_id as fld1_0_0_, this_.fld_name as fld2_0_0_,
this_.fld_email as fld3_0_0_ from tbl_contact this_ where this_.fld_email=?
list.size() = 1 

清单23-查询结果

正如看到的,使用我们的方法创建的自定义字段能够很容易地参与到数据库查询中。

进一步改善

很显然,我们上面提到的实现相当简单。它并没有反映出该功能在实际实现中会遇到的各种情况。但是它还是说明了在建议的技术平台上解决方案的大体工作机制。

另外明显的是,该需求还可以使用其它办法(比如代码生成)来实现,这些办法也许会在其它文章中介绍。

这个实现仅支持String类型的自定义字段,但是,基于该方法的实际应用(Enterra CRM)中, 已经实现了对所有原始类型、对象类型(链接到业务对象)以及集合字段的完全支持。

为了在用户界面支持自定义字段,已经实现了针对自定义字段的元描述符系统,该系统使用了用户界面生成系统。但是生成器的机制是另外一篇文章的主题。

结论

最后,Enterra CRM团队创建、验证并在实践中应用了基于ORM平台Hibernate的开放对象模型架构,它满足了客户在运行时不需要对应用源代码做任何改动、就可以按照最终用户的实际需求设置应用的需求。

 

2
1
分享到:
评论

相关推荐

    ssh(structs,spring,hibernate)框架中的上传下载

     您可以使用Hibernate Middlegen、HIbernate Tools、Hibernate Syhchronizer等工具或手工的方式,编写Hibernate的领域对象和映射文件。其中对应T_FILE表的领域对象Tfile.java为:  代码 1 领域对象Tfile 1. ...

    Grails权威指南

     5.1.6 使用约束自定义字段.  5.2 静态脚手架  5.2.1 生成控制器(controller)  5.2.2 生成视图(views)  5.3 本章小结 第6章 测试  6.1 编写高效的单元测试  6.1.1 使用assert关键字...

    Grails 中文参考手册

    6.7.1 用Prototype实现Ajax 6.7.1.1 异步链接 6.7.1.2 更新内容 6.7.1.3 异步表单提交 6.7.1.4 Ajax事件 6.7.2 用Dojo实现Ajax 6.7.3 用GWT实现Ajax 6.7.4 服务端的Ajax 6.8 内容协商 7. 验证 7.1 声明约束 7.2 验证...

    Struts2 in action中文版

    5.3.2 使用OGNL表达式从表单字段名映射到属性 90 5.4 自定义类型转换 101 5.4.1 实现类型转换器 102 5.4.2 在String和Circle之间转换 102 5.4.3 配置框架使用自定义转换器 103 5.5 小结 106 第三部分 构建视图——...

    Spring攻略(第二版 中文高清版).part2

    3.12 将Spring Bean注入领域对象 147 3.12.1 问题 147 3.12.2 解决方案 147 3.12.3 工作原理 148 3.13 小结 151 第4章 Spring中的脚本 152 4.1 用脚本语言实现Bean 152 4.1.1 问题 152 4.1.2 解决...

    Spring攻略(第二版 中文高清版).part1

    3.12 将Spring Bean注入领域对象 147 3.12.1 问题 147 3.12.2 解决方案 147 3.12.3 工作原理 148 3.13 小结 151 第4章 Spring中的脚本 152 4.1 用脚本语言实现Bean 152 4.1.1 问题 152 4.1.2 解决...

    深入浅出Struts 2 .pdf(原书扫描版) part 1

    17.3 使用一个自定义的“等待”页面 265 17.4 小结 266 第18章 定制拦截器 267 18.1 Interceptor接口 267 18.2 编写一个自定义的拦截器 268 18.3 使用DataSourceInjectorInterceptor拦截器 269 18.4 小结 273 第19...

    javapms门户网站源码

    在数据库平台兼容性方面,系统数据库持久层采用hibernate实现,使得系统可以支持几乎所有的数据库平台,包括Oracle、DB2、Microsoft SQL Server、MySQL、PostgreSQL等。这对于已经购买或熟悉某一类型数据库产品的...

Global site tag (gtag.js) - Google Analytics