Skip to content

Flatten And Encapsulate

Alessandro Vurro edited this page Nov 21, 2016 · 13 revisions

Important! this is an example that shows how to apply a simple nested mapping without an explicit use of nested mapping configuration.

Since 1.3.2 release is possible to use get and set placeholders for destination and source, but what's the advantages of this new feature?
The following is a quick example (this is a system to avoid an explicit nested mapping definition):

public class Encapsulate {

	private User user;
	
        public Encapsulate(){
           user = new User();
        }

        // getter and setter..

        public static class User {
		
           private String name;
           private String surname;
           private String address;
           private String number;
                
           // getter and setter..
        }
}

And

public class Flatten {

        private String name;
        private String surname;
        private String address;
        private String number;

        //getter and setter..
}

My purpose is to map Flatten in Encapsulate and viceversa.
With any mapper you are obliged to define every relationship, in this case:

user.name = name
user.surname = surname
etc..

With JMapper all you need are two methods that define a mapping for each direction:

@JGlobalMap("user")
public class Flatten {

	private String name;
	private String surname;
	private String address;
	private String number;

	@JMapConversion(to={"user"},type=Type.DYNAMIC,avoidSet=true)
	public static String fromDestConversion(){
		return "${destination}.${source.set}(${source});";
	}
	
	@JMapConversion(from={"user"},type=Type.DYNAMIC)
	public static String fromSourceConversion(){
		return "return ${source}.${destination.get}();";
	}

	//getter and setter..
}

or in XML:

<?xml version="1.0" encoding="UTF-8"?>
<jmapper xmlns="https://jmapper-framework.googlecode.com"
	xmlns:xsi="https://jmapper-framework.googlecode.com/svn"
	xsi:noNamespaceSchemaLocation="https://jmapper-framework.googlecode.com/svn/jmapper-1.3.1.xsd">

   <class name="package.Encapsulate">
      <global>
         <value name="user"/>
      </global>
      <attribute name="name" get="gName" set="sName"/>
      <conversion name="fromFlatten" from="name,surname,address,number" type="DYNAMIC" avoidSet="true">
         ${destination}.${source.set}(${source});
      </conversion>
      <conversion name="fromEncapsulate" from="user" type="DYNAMIC">
         return ${source}.${destination.get}();
      </conversion>
   </class>
</jmapper>

This mapping suppose that:

  • from Flatten to Encapsulate the set method name is the same for both
  • from Encapsulate to Flatten the get method name is the same for both

with these precautions you can add new fields, on the classes used, without having to put hands to the configuration.

Clone this wiki locally