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

Castor (二) -- 自定义映射

    博客分类:
  • java
阅读更多
    1.概述
 
castor的自定义映射关系通过xml设置。
主要作用有
1)改变映射位置(node): attribute, element, text
2)改变映射名字(name...): attributename, elementtagname
3)改变层级关系(location)
4)改变输出格式(handler): dateformat...
5)改变属性获取和设置方式(get/setmethod, direct="true")
6)隐藏属性(auto-complete="true", transient="true")
 
2.源码
 
 address.java student.java 详见 <span style="color: #000000;"><a class="quote_div" title="castor(一) -- 默认绑定" href="/blog/1060531" target="_blank">castor (一) -- 默认绑定</a></span> 
 
localdatehandler.java
 
package com.siyuan.castor.handler;import java.text.dateformat;import java.text.parseexception;import java.text.simpledateformat;import java.util.date;import org.exolab.castor.mapping.fieldhandler;import org.exolab.castor.mapping.validityexception;import com.siyuan.castor.student;public class localdatehandler implements fieldhandler {		private static final string local_date_format = "yyyy-mm-dd";		public void checkvalidity(object object) throws validityexception,			illegalstateexception {	}		/**	 * @param object the owner of the field	 */	public object getvalue(object object) throws illegalstateexception {		if (object instanceof student) {			date date = ((student) object).getbirthday();			if (date != null) {				dateformat datefmt = new simpledateformat(local_date_format);				return datefmt.format(date);			} else {				return null;			}		}		return null;	}	public object newinstance(object arg0) throws illegalstateexception {		return null;	}	public void resetvalue(object arg0) throws illegalstateexception,			illegalargumentexception {	}		/**	 * @param object the owner of the field	 * @param datestring the field value in the xml source file	 */	public void setvalue(object object, object datestring)			throws illegalstateexception, illegalargumentexception {		if (object instanceof student) {			dateformat datefmt = new simpledateformat(local_date_format);			try {				date date = datefmt.parse((string) datestring);				((student) object).setbirthday(date);			} catch (parseexception e) {				throw new illegalargumentexception(e);			}					}	}}
 
 divdatehandler.java
 
package com.siyuan.castor.handler;import java.text.dateformat;import java.text.parseexception;import java.text.simpledateformat;import java.util.date;import org.exolab.castor.mapping.generalizedfieldhandler;public class divdatehandler extends generalizedfieldhandler {	private static final string local_date_format = "yyyy-mm-dd";		/**	 * automatically supports iterating over the items of a collection 	 * and passing them one-by-one to the convertuponget	 * 	 * setcollectioniteration : could modify it	 */	public divdatehandler() {		setcollectioniteration(false);	}		/**	 * @override	 * @param value the object value to convert after                 *  performing a get operation	 * @return the converted value.	 */	public object convertuponget(object value) {		if (value == null) 			return null;		dateformat datefmt = new simpledateformat(local_date_format);		return datefmt.format((date) value);	}	/**	 * @override	 * @param value the object value to convert before                 *  performing a set operation                 * @return the converted value.	 */	public object convertuponset(object value) {		if (value == null) 			return null;		dateformat datefmt = new simpledateformat(local_date_format);		date date = null;		try {			date = datefmt.parse((string) value);		} catch (parseexception e) {			throw new illegalargumentexception(e);		}			return date;	}	/**	 * @override	 * returns the class type for the field that this     	 * generalizedfieldhandler converts to and from. this     	 * should be the type that is used in the     	 * object model.     	 *                 * @return the class type of of the field	 */	public class getfieldtype() {		return date.class;	}}
 
configuredatehandler.java
 
package com.siyuan.castor.handler;import java.text.dateformat;import java.text.parseexception;import java.text.simpledateformat;import java.util.date;import java.util.properties;import org.exolab.castor.mapping.configurablefieldhandler;import org.exolab.castor.mapping.fieldhandler;import org.exolab.castor.mapping.validityexception;import com.siyuan.castor.student;public class configuredatehandler implements fieldhandler,		configurablefieldhandler {		private static final string date_format_param_name = "date-format";		private dateformat dateformat;		public void checkvalidity(object arg0) throws validityexception,			illegalstateexception {	}	public object getvalue(object object) throws illegalstateexception {		if (object instanceof student) {			date date = ((student) object).getbirthday();			if (date != null) {				return dateformat.format(date);			} else {				return null;			}		}		return null;	}	public object newinstance(object arg0) throws illegalstateexception {		return null;	}	public void resetvalue(object arg0) throws illegalstateexception,			illegalargumentexception {	}	public void setvalue(object object, object datestring)			throws illegalstateexception, illegalargumentexception {		if (object instanceof student) {			try {				date date = dateformat.parse((string) datestring);				((student) object).setbirthday(date);			} catch (parseexception e) {				throw new illegalargumentexception(e);			}					}	}		/**	 * @param params configure information in the xml	 */	public void setconfiguration(properties params) throws validityexception {		string pattern = params.getproperty(date_format_param_name);		if (pattern == null)			throw new validityexception("required parameter \"" + date_format_param_name + "\" is missing");		try {			dateformat = new simpledateformat(pattern);		} catch (illegalargumentexception e) {			throw new validityexception("pattern \"" + pattern + "\" is not a valid date format.");		}	}}
 
student.cst.xml
 
<!doctype mapping public "-//exolab/castor object mapping dtd version 1.0//en""http://castor.exolab.org/mapping.dtd"><mapping>	<description>used for com.siyuan.castor.student</description>		<!-- 	<include href=""></include>	 -->	 	<!-- 	<field-handler />	 -->	<field-handler name="localdatehandler" class="com.siyuan.castor.handler.configuredatehandler">		<param name="date-format" value="yyyy-mm-dd"/>	</field-handler>		<!-- 	verify-constructable="false" 	used with the set-method="%1-9%"	make it able to omit the no-parameter constructor	 -->	<class name="com.siyuan.castor.student" auto-complete="true">				<description>com.siyuan.castor.student</description>				<map-to xml="person"/>					<!-- 			type="java.lang.string" handler="" required="true" direct="true" transient="true"			 set-method="%1-9%" get-method="getname" type="string" //can not omit the no-parameter constructor		-->		<field name="name">			<description>property name</description>      		<bind-xml name="stuname" node="attribute"/>   		</field>				<!-- 		type="string" handler="com.siyuan.castor.handler.divdatehandler" 		type="string" handler="com.siyuan.castor.handler.localdatehandler" 		//type could not be omitted and must be string		location="birthday/birthday1"		-->		<field name="birthday" type="string" handler="localdatehandler">      		<bind-xml name="birth" node="attribute"/>   		</field>   				<field name="friends" collection="set" type="com.siyuan.castor.student" get-method="getfriends" set-method="addfriend">      		<bind-xml name="friend" node="element"/>   		</field>   		   		<field name="subjects" collection="arraylist" type="string" get-method="getsubjects" set-method="addsubject">      		<bind-xml name="subjects" node="element"/>   		</field>   		   		<field name="teachers" collection="map">      		<bind-xml name="teachers" node="element">	      		<class name="org.exolab.castor.mapping.mapitem">	      			<field name="key" type="java.lang.string">	      				<bind-xml name="name" node="attribute"/>	      			</field>	      			<field name="value" type="java.lang.string">	      				<bind-xml name="subject" node="attribute"/>	      			</field>	      		</class>      		</bind-xml>   		</field>   			</class>		<!-- not used for xml mapping	<key-generator />	 -->	</mapping> 
 
castordiytest.java
 
package com.siyuan.castor.test;import java.io.ioexception;import java.io.inputstream;import java.io.stringreader;import java.io.stringwriter;import java.text.dateformat;import java.text.parseexception;import java.text.simpledateformat;import java.util.arraylist;import java.util.arrays;import java.util.date;import java.util.hashmap;import java.util.hashset;import java.util.list;import java.util.map;import java.util.set;import org.exolab.castor.mapping.mapping;import org.exolab.castor.mapping.mappingexception;import org.exolab.castor.xml.marshalexception;import org.exolab.castor.xml.marshaller;import org.exolab.castor.xml.unmarshaller;import org.exolab.castor.xml.validationexception;import org.xml.sax.inputsource;import com.siyuan.castor.address;import com.siyuan.castor.student;public class castordiytest {	/**	 * @param args	 * @throws validationexception 	 * @throws marshalexception 	 * @throws validationexception 	 * @throws marshalexception 	 */	public static void main(string[] args) throws marshalexception, validationexception{		student stusrc = new student();		stusrc.setage(22);		stusrc.setname("singleman");		stusrc.setmale(true);		address address = new address();		address.setstreet("renmin road");		stusrc.setaddress(address);		dateformat datefmt = new simpledateformat("yyyy-mm-dd");		try {			date birthday = datefmt.parse("1988-11-21");			stusrc.setbirthday(birthday);		} catch (parseexception e) {			e.printstacktrace();		}				student girl = new student();		girl.setage(20);		stusrc.setgirlfriend(girl);				set<student> students = new hashset<student>();		student stu1 = new student();		stu1.setage(21);		students.add(stu1);		student stu2 = new student();		stu2.setage(23);		students.add(stu2);				stusrc.addfriend(stu1);		stusrc.addfriend(stu2);				stusrc.addsubject("english");		stusrc.addsubject("math");		stusrc.addsubject("chinese");				map<string, string> teachers = new hashmap<string, string>();		teachers.put("english", "teacher a");		teachers.put("math", "teacher b");		teachers.put("chinese", "teacher c");		stusrc.setteachers(teachers);				mapping mapping = new mapping();		try {			inputstream mappingfilein = student.class				.getresourceasstream("/com/siyuan/castor/student.cst.xml");			mapping.loadmapping(new inputsource(mappingfilein));						stringwriter result = new stringwriter();			marshaller marshaller = new marshaller();			marshaller.setmapping(mapping);			marshaller.setwriter(result);			marshaller.marshal(stusrc);			system.out.println(result);						system.out.println("=================================================================");						unmarshaller unmarshaller = new unmarshaller(mapping);			student studist = (student) unmarshaller.unmarshal(new stringreader(result.tostring()));			system.out.println(studist);					} catch (mappingexception e) {			e.printstacktrace();		} catch (ioexception e) {			e.printstacktrace();		}	}}
 
3. 输出结果
 
<?xml version="1.0" encoding="utf-8"?><person stuname="singleman" birth="1988-11-21" male="true" age="22"><friend male="false" age="23"/><friend male="false" age="21"/><subjects>english</subjects><subjects>math</subjects><subjects>chinese</subjects><teachers name="english" subject="teacher a"/><teachers name="math" subject="teacher b"/><teachers name="chinese" subject="teacher c"/><girl-friend male="false" age="20"/><address><street>renmin road</street></address></person>=================================================================student[name=singleman,age=22,male=true,birthday=mon nov 21 00:00:00 cst 1988,address=address[street=renmin road],girlfriend=student[name=null,age=20,male=false,birthday=null,address=null,girlfriend=null,friends=[],subjects=[],teachers={}],friends=[student[name=null,age=23,male=false,birthday=null,address=null,girlfriend=null,friends=[],subjects=[],teachers={}], student[name=null,age=21,male=false,birthday=null,address=null,girlfriend=null,friends=[],subjects=[],teachers={}]],subjects=[english, math, chinese],teachers={english=teacher a, math=teacher b, chinese=teacher c}]
 
 
4.参考资料
 
http://www.castor.org/xml-mapping.html
 
http://www.castor.org/xml-fieldhandlers.html#use-configurablefieldhandler-for-more-flexibility
 
附件为mapping文件对应的dtd和xsd文件
 
 
0
3
分享到:
评论

相关推荐

    castor1.4 xsd生成java

    - 灵活性:Castor允许自定义映射规则,以适应复杂的数据结构和需求。 - 性能:与手动解析和构建XML相比,使用Castor可以提高处理XML的速度。 - 持久化支持:Castor提供了对JDBC和JDO的集成,可以直接将Java对象...

    castor-0.9.9.zip

    2. **src**:这个目录可能包含了Castor的源代码,方便开发者查看和理解内部实现,或者进行自定义扩展。 3. **docs**:文档目录,可能有API参考手册和其他用户指南,帮助开发者更好地理解和使用Castor。 4. **...

    castor-1.3.2.zip

    5. **灵活的映射**:Castor提供了多种映射选项,比如一对一、一对多、多对一和多对多的关系映射,以及自定义转换函数,使开发者能够根据需求定制XML-Java转换。 6. **性能优化**:Castor通过缓存映射信息和利用内存...

    castor 框架jar包和src

    - **自定义扩展**:如果需要对Castor进行定制或添加特定功能,源代码提供了这样的可能性。 - **性能优化**:通过分析源代码,开发者可以识别性能瓶颈并进行优化。 4. **使用步骤** - **配置映射文件**:创建XML...

    castor-1.2-doc.zip

    6. **类型转换**:了解Castor如何自动处理不同类型之间的转换,例如日期、时间、自定义类型等。 7. **继承与多态性支持**:掌握如何处理数据库中的继承结构,以及Java对象的多态性在映射过程中的体现。 8. **性能...

    castor castor castor 资料

    2. **映射机制**:Castor使用XML映射文件来定义Java类和XML元素之间的对应关系。通过这种方式,开发者可以自定义对象到XML的转换规则,比如字段名的映射、复杂类型的处理等。 3. **支持多种数据类型**:Castor支持...

    eclipse中castor插件

    Castor是一个开源Java库,主要用于XML到Java对象的映射(XML Binding)和Java到XML的转换。在Eclipse这样的集成开发环境中,Castor插件的集成极大地简化了数据绑定的过程,使得开发者能够轻松地在Java类和XML文档...

    castor1.3源码

    6. **定制化映射**:通过注解或XML配置文件,开发者可以自定义对象字段与XML元素之间的映射规则,包括字段命名、类型转换、默认值设定等。 7. **异常处理**:在源码中,可以看到Castor如何处理各种可能出现的错误和...

    castor学习教程

    Castor,全称为Java Object/Relational Mapping (ORM) Project,是一个开源的Java库,它提供了对象关系映射(ORM)的功能,使得开发者可以将Java对象的数据映射到数据库的表结构上,反之亦然。这极大地简化了数据库...

    castor :Java与xml互转示例---代码

    - **映射文件**:允许用户自定义Java类和XML元素之间的映射关系。 ### 2. 安装与配置 首先,你需要在项目中添加Castor的依赖。如果你使用Maven,可以在`pom.xml`文件中添加以下依赖: ```xml &lt;groupId&gt;org....

    castor 学习文档英文原版

    例如,日志记录和跟踪的使用、自动缩进的配置、映射自动完成、映射文件的验证,以及如何编写和使用自定义的字段处理器。字段处理器允许开发者以更细粒度控制数据绑定的过程,从而可以处理复杂的XML结构和数据类型...

    castor源代码和实现类样例

    这通常对于开发者来说非常有价值,因为通过查看源代码,可以深入了解Castor的工作原理,以及如何自定义和扩展其功能。此外,提供的样例代码可以帮助开发者快速上手,了解如何在实际项目中应用Castor。 描述中提到的...

    Castor使用例子

    8. **自定义转换**:有时,标准的Castor映射可能无法满足特定需求,你可能需要创建自定义的转换器来处理特定类型的数据。 9. **性能优化**:例子可能还涉及了一些性能优化的技巧,如缓存、预编译映射等,以提高大量...

    Castor学习笔记 (转载)

    映射文件允许用户自定义字段命名、类型转换等,以适应特定的需求。 3. 类与XML的映射 - 类到XML:当一个Java对象被序列化成XML时,Castor会根据映射文件将类的属性转化为XML元素。 - XML到类:反之,当XML数据被...

    Castor入门实例,含完整jar包

    它允许你自定义XML元素如何映射到类的属性,以及类如何映射到XML元素。 2. **序列化与反序列化**:Castor提供了API来实现对象到XML的序列化和XML到对象的反序列化。序列化是将Java对象转换成XML的过程,而反序列化...

    castor入门说明

    通过自定义 XML 映射文件,可以灵活地控制 XML 标签与 Java 属性之间的映射关系,从而满足各种应用场景的需求。此外,通过配置 `castor.properties` 文件还可以进一步优化 XML 文件的生成与解析过程。这对于需要频繁...

    castor 问题 无法解组

    10. **数据类型转换**:Castor默认提供了一些基本类型的数据转换,但对自定义类型或复杂类型的处理需要特别注意。确保在映射文件中为这些类型定义了适当的转换器。 综上所述,解决“castor无法解组”问题需要仔细...

    castor详细示例

    这个"castor详细示例"提供了一个深入理解如何使用Castor进行Java到XML以及XML到Java映射的实践教程。在Java开发中,数据序列化和反序列化是常见的需求,而Castor提供了一种高效且灵活的方式来实现这一目标。 1. **...

    castor2 源代码

    在Castor中,你可以自定义解析规则,以便根据特定的XML结构创建相应的Java对象。 2. **Book.java**:这个文件代表了一个"Book"类,它可能是应用中用于存储书籍信息的数据模型。Book类通常会包含如书名、作者、出版...

Global site tag (gtag.js) - Google Analytics