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
divdatehandler.java
configuredatehandler.java
student.cst.xml
castordiytest.java
3. 输出结果
4.参考资料
[url=http://www.castor.org/xml-mapping.html]http://www.castor.org/xml-mapping.html[/url]
[url=http://www.castor.org/xml-fieldhandlers.html#use-configurablefieldhandler-for-more-flexibility]http://www.castor.org/xml-fieldhandlers.html#use-configurablefieldhandler-for-more-flexibility[/url]
附件为mapping文件对应的dtd和xsd文件
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.参考资料
[url=http://www.castor.org/xml-mapping.html]http://www.castor.org/xml-mapping.html[/url]
[url=http://www.castor.org/xml-fieldhandlers.html#use-configurablefieldhandler-for-more-flexibility]http://www.castor.org/xml-fieldhandlers.html#use-configurablefieldhandler-for-more-flexibility[/url]
附件为mapping文件对应的dtd和xsd文件