How to use Object Type Converter
By firstname.lastname@example.org on Feb 16, 2011
User will enter a String in the form which has to be persisted in the database as a Number
From the User Interface we might be getting a String value which has to be persisted in the database as a number. In this scenario we can use converters to map the java object which is of type String to its database value which is a Number.
For example , there is a 'Person' table in database which is used to store the user details passed from the User Interface. It has a 'Status' column which is of the value Number. But from the User Interface String values (Active/InActive) are passed . For persisting the user details we can use Object type converter and provide the mappings for status column corresponding to the String values.
Object type converter can be used if you want to have a mapping for a field for example when departmentName on the entity is of String value and mapped to dept_name field on the database table which is of the value Number.
Sample EJB API for setting the value of status on Person Entity as a String
public void createPerson(String status,String firstName,String lastName)
Person person = new Person();
// status will be set as a String value received from the User Interface
In the sample code shown above status is passed as a String, this has to be converted to Number. The String value obtained will be set on Person object and persistPerson API will be called for creating a new person from the values passed from the User Interface.
Steps to configure Object type converter:
1. Navigate to Person Entity from persistence.xml and navigate to status field
2. Click on Conversion tab and select Converted check box
3. Select Object Type Converter radio button and set the Data Type Class to java.math.BigDecimal and Object Type Class to java.lang.String
4. Specify the conversion values for all the values that can be passed from the user interface as shown below
5. Set the Default Object value
Object Type Converter maps the status column in the database to the corresponding String values set in the converter. In this type of scenario, Object Type Converter can be effectively used to map the Java Object to a database column which is of a different data type.