1. Introduction
Dozer is a JavaBean mapping tool, similar to the Apache Beanutils. But Dozer is more powerful, it can handle the mapping between complex types flexibly. Not only can simple attribute mapping, complex type mapping, bidirectional mapping, recursive mapping and so on, and can be flexibly configured through XML configuration file.
2. Preparation
Let's try it out for a little bit now.
First, you need to download the jar package,
Dozer.jar:http://dozer.sourceforge.net/downloading.html
We need Slf4j.jar,commons-lang.jar,commons-beanutil.jar, Commons-loggin.jar.
3. Code
Two beans
Java code
- Public class Book {
- private String name;
- private String author;
- Public String GetName () {
- return name;
- }
- public void SetName (String name) {
- this.name = name;
- }
- Public String Getauthor () {
- return author;
- }
- public void Setauthor (String author) {
- This.author = author;
- }
- Public book () {
- }
- }
Java code
- Public class Bookvo {
- private String Namevo;
- private String Authorvo;
- Public String Getnamevo () {
- return Namevo;
- }
- public void Setnamevo (String namevo) {
- This.namevo = Namevo;
- }
- Public String Getauthorvo () {
- return Authorvo;
- }
- public void Setauthorvo (String authorvo) {
- This.authorvo = Authorvo;
- }
- Public Bookvo () {
- }
- }
Bookmapper.xml configuration file, which is used to set the Dozerbeanmapper.
XML code
- <? XML version= "1.0" encoding="UTF-8"?>
- <mappings xmlns="http://dozer.sourceforge.net"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemalocation= "Http://dozer.sourceforge.net
- Http://dozer.sourceforge.net/schema/beanmapping.xsd ">
- <mapping>
- <class-a>test. Book</class-a>
- <class-b>test. Bookvo</class-b>
- <field>
- <a>name</a>
- <b>namevo</b>
- </field>
- <field>
- <a>author</a>
- <b>authorvo</b>
- </field>
- </mapping>
- </Mappings>
Test class
Java code
- Package test;
- Import java.util.ArrayList;
- Import java.util.List;
- Import Org.apache.commons.logging.Log;
- Import Org.apache.commons.logging.LogFactory;
- Import Org.dozer.DozerBeanMapper;
- /**
- Description
- *
- * @author LSR
- * @version 17, 2011
- */
- Public class Dozertest {
- /**
- * @param args
- */
- public static void Main (string[] args) {
- Testbyxml ();
- }
- public static void Testbyxml () {
- Book book = new book ();
- Book.setauthor ("LSR");
- Book.setname ("dozer demo");
- Dozerbeanmapper mapper = new Dozerbeanmapper ();
- list<string> mappers = new arraylist<string> ();
- Mappers.add ("Bookmapper.xml");
- Mapper.setmappingfiles (mappers);
- Bookvo vo = new Bookvo ();
- Mapper.map (book, VO);
- System.out.println ("book ' s Name:" + book.getname ());
- System.out.println ("Bookvo ' s Name:" + Vo.getnamevo ());
- }
- }
dozer-First Knowledge