Creating a New Record in OFBiz using Java

This is an example on how to create a record in OFBiz using Java as engine.

First, you have to create a service containing the attributes/values to be passed in your Java method. This service is invoked in your controller.xml.

<service name=“addPerson” engine=“java” location=“org.ofbiz.person.PersonServices” invoke=“addPerson” auth=“true”>
<description>Add Person Service</description>
<attribute name=“firstName” mode=“IN” type=“String” optional=“true”></attribute>
<attribute name=“lastName” mode=“IN” type=“String” optional=“true”></attribute>
<attribute name=“gender” mode=“IN” type=“String” optional=“true”></attribute>
<attribute name=“email” mode=“IN” type=“String” optional=“true”></attribute>
</service>

Once you have the service in your xml. Create the method with the same name as the value of the invoke attribute in the xml.

public static Map addPerson(DispatchContext dctx, Map context) {
Map resultMap = ServiceUtil.returnSuccess();

//this is how you fetch the values from the request
String firstName = (String) context.get("firstName");
String lastName = (String) context.get("lastName");
String gender = (String) context.get("gender");
String email = (String) context.get("email");

try {
//delegator.getNextSeqId(String EntityName) for auto-increment id
Map personValue = UtilMisc.toMap("id", delegator.getNextSeqId("Person"),
"firstName", firstName,
"lastName", lastName,
"gender", gender,
"email", email);

GenericValue personGV = delegator.makeValue("Person", personValue);
personGV.create();
} catch (GenericEntityException e) {
return ServiceUtil.returnError("Failed. " +e.getMessage());
}
return resultMap;
}

No comments:

Post a Comment