XML to Object mapping - java

Having hard time to map..
Calling rest and rest return response in XML format..
Help with class mapping in Java Object (method)
<aname>
<bname>
<c id="2">
<cname call="yes" text="no" email="yes"/>
<acc>
<accinfo name="ax" addr="USA"/>
</acc>
</c>
</bname>
</aname>
how can i convert above xml in Java class?
Thank You!

I share solution:
If you use need dependency
<!-- Jaxb -->
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
</dependency>
First class.
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSchemaType;
import javax.xml.bind.annotation.XmlType;
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = { "bname" })
#XmlRootElement(name = "aname")
public class Aname {
#XmlElement(required = true)
protected Aname.Bname bname;
/**
* Gets the value of the bname property.
*
* #return possible object is {#link Aname.Bname }
*
*/
public Aname.Bname getBname() {
return bname;
}
/**
* Sets the value of the bname property.
*
* #param value allowed object is {#link Aname.Bname }
*
*/
public void setBname(Aname.Bname value) {
this.bname = value;
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = { "c" })
public static class Bname {
#XmlElement(required = true)
protected Aname.Bname.C c;
/**
* Gets the value of the c property.
*
* #return possible object is {#link Aname.Bname.C }
*
*/
public Aname.Bname.C getC() {
return c;
}
/**
* Sets the value of the c property.
*
* #param value allowed object is {#link Aname.Bname.C }
*
*/
public void setC(Aname.Bname.C value) {
this.c = value;
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = { "cname", "acc" })
public static class C {
#XmlElement(required = true)
protected Aname.Bname.C.Cname cname;
#XmlElement(required = true)
protected Aname.Bname.C.Acc acc;
#XmlAttribute(name = "id", required = true)
#XmlSchemaType(name = "unsignedByte")
protected short id;
/**
* Gets the value of the cname property.
*
* #return possible object is {#link Aname.Bname.C.Cname }
*
*/
public Aname.Bname.C.Cname getCname() {
return cname;
}
/**
* Sets the value of the cname property.
*
* #param value allowed object is {#link Aname.Bname.C.Cname }
*
*/
public void setCname(Aname.Bname.C.Cname value) {
this.cname = value;
}
/**
* Gets the value of the acc property.
*
* #return possible object is {#link Aname.Bname.C.Acc }
*
*/
public Aname.Bname.C.Acc getAcc() {
return acc;
}
/**
* Sets the value of the acc property.
*
* #param value allowed object is {#link Aname.Bname.C.Acc }
*
*/
public void setAcc(Aname.Bname.C.Acc value) {
this.acc = value;
}
/**
* Gets the value of the id property.
*
*/
public short getId() {
return id;
}
/**
* Sets the value of the id property.
*
*/
public void setId(short value) {
this.id = value;
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "", propOrder = { "accinfo" })
public static class Acc {
#XmlElement(required = true)
protected Aname.Bname.C.Acc.Accinfo accinfo;
/**
* Gets the value of the accinfo property.
*
* #return possible object is {#link Aname.Bname.C.Acc.Accinfo }
*
*/
public Aname.Bname.C.Acc.Accinfo getAccinfo() {
return accinfo;
}
/**
* Sets the value of the accinfo property.
*
* #param value allowed object is {#link Aname.Bname.C.Acc.Accinfo }
*
*/
public void setAccinfo(Aname.Bname.C.Acc.Accinfo value) {
this.accinfo = value;
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "")
public static class Accinfo {
#XmlAttribute(name = "name", required = true)
protected String name;
#XmlAttribute(name = "addr", required = true)
protected String addr;
/**
* Gets the value of the name property.
*
* #return possible object is {#link String }
*
*/
public String getName() {
return name;
}
/**
* Sets the value of the name property.
*
* #param value allowed object is {#link String }
*
*/
public void setName(String value) {
this.name = value;
}
/**
* Gets the value of the addr property.
*
* #return possible object is {#link String }
*
*/
public String getAddr() {
return addr;
}
/**
* Sets the value of the addr property.
*
* #param value allowed object is {#link String }
*
*/
public void setAddr(String value) {
this.addr = value;
}
}
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "")
public static class Cname {
#XmlAttribute(name = "call", required = true)
protected String call;
#XmlAttribute(name = "text", required = true)
protected String text;
#XmlAttribute(name = "email", required = true)
protected String email;
/**
* Gets the value of the call property.
*
* #return possible object is {#link String }
*
*/
public String getCall() {
return call;
}
/**
* Sets the value of the call property.
*
* #param value allowed object is {#link String }
*
*/
public void setCall(String value) {
this.call = value;
}
/**
* Gets the value of the text property.
*
* #return possible object is {#link String }
*
*/
public String getText() {
return text;
}
/**
* Sets the value of the text property.
*
* #param value allowed object is {#link String }
*
*/
public void setText(String value) {
this.text = value;
}
/**
* Gets the value of the email property.
*
* #return possible object is {#link String }
*
*/
public String getEmail() {
return email;
}
/**
* Sets the value of the email property.
*
* #param value allowed object is {#link String }
*
*/
public void setEmail(String value) {
this.email = value;
}
}
}
}
}
Second class.
import javax.xml.bind.annotation.XmlRegistry;
#XmlRegistry
public class ObjectFactory {
/**
* Create a new ObjectFactory that can be used to create new instances of schema
* derived classes for package: generated
*
*/
public ObjectFactory() {
}
/**
* Create an instance of {#link Aname }
*
*/
public Aname createAname() {
return new Aname();
}
/**
* Create an instance of {#link Aname.Bname }
*
*/
public Aname.Bname createAnameBname() {
return new Aname.Bname();
}
/**
* Create an instance of {#link Aname.Bname.C }
*
*/
public Aname.Bname.C createAnameBnameC() {
return new Aname.Bname.C();
}
/**
* Create an instance of {#link Aname.Bname.C.Acc }
*
*/
public Aname.Bname.C.Acc createAnameBnameCAcc() {
return new Aname.Bname.C.Acc();
}
/**
* Create an instance of {#link Aname.Bname.C.Cname }
*
*/
public Aname.Bname.C.Cname createAnameBnameCCname() {
return new Aname.Bname.C.Cname();
}
/**
* Create an instance of {#link Aname.Bname.C.Acc.Accinfo }
*
*/
public Aname.Bname.C.Acc.Accinfo createAnameBnameCAccAccinfo() {
return new Aname.Bname.C.Acc.Accinfo();
}
}
And Main class.
import java.io.StringReader;
import java.text.ParseException;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class Test {
static ObjectMapper mapper = new ObjectMapper();
public static void main(String... strings) throws ParseException {
String xml = "<aname> <bname> <c id=\"2\"> <cname call=\"yes\" text=\"no\" email=\"yes\"/> <acc> <accinfo name=\"ax\" addr=\"USA\"/> </acc> </c> </bname> </aname>";
Aname clazz = convertXMLToObject(Aname.class, xml);
try {
System.out.println(mapper.writeValueAsString(clazz));
} catch (JsonProcessingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#SuppressWarnings("unchecked")
public static <T> T convertXMLToObject(Class<T> clazz, String xml)
{
try {
JAXBContext context = JAXBContext.newInstance(clazz);
Unmarshaller um = context.createUnmarshaller();
return (T) um.unmarshal(new StringReader(xml));
}
catch (JAXBException je){
throw new RuntimeException(String.format("Exception while Unmarshaller: %s", je.getMessage()));
}
}
}
result this.
{"bname":{"c":{"cname":{"call":"yes","text":"no","email":"yes"},"acc":{"accinfo":{"name":"ax","addr":"USA"}},"id":2}}}

Related

"No suitable constructor found for type" and the type exists and has a default constructor

I am receiving this message in a new jersey 1.19.4 app that I am building:
No suitable constructor found for type [simple type, class javax.xml.bind.JAXBElement<com.objex.idms.idd.types.IDDModule>]: can not instantiate from JSON object (need to add/enable type information?)
at [Source: org.apache.catalina.connector.CoyoteInputStream#5a5e4ec1; line: 1, column: 2]
After much searching I have seen many posts that indicate this can be caused by a missing default constructor. However that doesn't seem to the the case here. Note I have tried this implementing "Serializable" with the same result. I am sure it's something simple but am just missing it.
Here is the class in question, any thoughts you might have would be appreciated.
package com.objex.idms.idd.types;
// import java.io.Serializable;
public class IDDModule {
/**
*
*/
//private static final long serialVersionUID = 1897236478938746827L;
private String DictName;
private String DictNode;
private String Name;
private String Version;
private String Language;
private String ModuleMetadata;
private String ModuleSource;
private String Message;
public IDDModule() {
}
/**
* #param dictName the dictName to set
*/
public void setDictName(String DictName) {
this.DictName = DictName;
}
/**
* #return the dictName
*/
public String getDictName() {
return DictName;
}
/**
* #param DictNode the dictNode to set
*/
public void setDictNode(String DictNode) {
this.DictNode = DictNode;
}
/**
* #return the dictNode
*/
public String getDictNode() {
return DictNode;
}
/**
* #param language the language to set
*/
public void setLanguage(String language) {
this.Language = language;
}
/**
* #return the language
*/
public String getLanguage() {
return Language;
}
/**
* #param Message the message to set
*/
public void setMessage(String Message) {
this.Message = Message;
}
/**
* #return the message
*/
public String getMessage() {
return Message;
}
/**
* #param ModuleMetadata the moduleMetadata to set
*/
public void setModuleMetadata(String ModuleMetadata) {
this.ModuleMetadata = ModuleMetadata;
}
/**
* #return the ModuleMetadata
*/
public String getModuleMetadata() {
return ModuleMetadata;
}
/**
* #param ModuleSource the moduleSource to set
*/
public void setModuleSource(String ModuleSource) {
this.ModuleSource = ModuleSource;
}
/**
* #return the moduleSource
*/
public String getModuleSource() {
return ModuleSource;
}
/**
* #param name the name to set
*/
public void setName(String name) {
this.Name = name;
}
/**
* #return the name
*/
public String getName() {
return Name;
}
/**
* #param version the version to set
*/
public void setVersion(String version) {
this.Version = version;
}
/**
* #return the version
*/
public String getVersion() {
return Version;
}
}

JAXB XML Unmarshaller error. Getting null value for all Object

I get the following error when I tried to parse the below string
<?xml version="1.0" encoding="UTF-8"?>
<CC5Response>
<OrderId>ORDER-17305KXSH11966</OrderId>
<GroupId>ORDER-173053333KXSH11966</GroupId>
<Response>Approved</Response>
<AuthCode>0293333584</AuthCode>
<HostRefNum>73051033333011833</HostRefNum>
<ProcReturnCode>00</ProcReturnCode>
<TransId>17305K33245XSH11968</TransId>
<ErrMsg></ErrMsg>
<Extra>
<SETTLEID>1</SETTLEID>
<TRXDATE>20171101 10:23:18</TRXDATE>
<ERRORCODE></ERRORCODE>
<CARDBRAND>VISA</CARDBRAND>
<CARDISSUER>CDM</CARDISSUER>
<NUMCODE>00</NUMCODE>
</Extra>
</CC5Response>
Code snippet for Unmarshalling is given below
JAXBContext jaxbContext = JAXBContext.newInstance(CC5Response.class);
XMLInputFactory xif = XMLInputFactory.newFactory();
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
XMLStreamReader xsr = xif.createXMLStreamReader(IOUtils.toInputStream(sb.toString(), "UTF-8"));
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
CC5Response res = (CC5Response) jaxbUnmarshaller.unmarshal(xsr);
System.out.println("*************"+res.toString());
bean class is given below
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType
#XmlRootElement(name = "CC5Response")
public class CC5Response {
#XmlAttribute
private String ProcReturnCode;
// #XmlAttribute
// private Extra Extra;
/*public Extra getExtra() {
return Extra;
}
public void setExtra(Extra extra) {
Extra = extra;
}*/
#XmlAttribute
private String AuthCode;
#XmlAttribute
private String OrderId;
#XmlAttribute
private String TransId;
#XmlAttribute
private String ErrMsg;
#XmlAttribute
private String Response;
#XmlAttribute
private String HostRefNum;
#XmlAttribute
private String GroupId;
I always get a plain object with null values.
To enable JAXB unmarshaller to work fine, you should simulate your XML into right structure of JAVA classes ... Follow the following steps and it will work with you.
Your XML should be like :
<?xml version="1.0" encoding="UTF-8"?>
<CC5Response>
<OrderId>ORDER-17305KXSH11966</OrderId>
<GroupId>ORDER-173053333KXSH11966</GroupId>
<Response>Approved</Response>
<AuthCode>0293333584</AuthCode>
<HostRefNum>73051033333011833</HostRefNum>
<ProcReturnCode>00</ProcReturnCode>
<TransId>17305K33245XSH11968</TransId>
<ErrMsg>error message</ErrMsg>
<Extra>
<SETTLEID>1</SETTLEID>
<TRXDATE>20171101 10:23:18</TRXDATE>
<ERRORCODE>0000</ERRORCODE>
<CARDBRAND>VISA</CARDBRAND>
<CARDISSUER>CDM</CARDISSUER>
<NUMCODE>00</NUMCODE>
</Extra>
</CC5Response>
We will create 2 necessary classes in Java :
2.1 create class named "CC5Response.java" like :
#XmlRootElement(name = "CC5Response")
public class CC5Response {
private String ProcReturnCode;
private String AuthCode;
private String OrderId;
private String TransId;
private String ErrMsg;
private String Response;
private String HostRefNum;
private String GroupId;
private List<Extra> Extra;
/**
* #return the ProcReturnCode
*/
#XmlElement(name="ProcReturnCode")
public String getProcReturnCode() {
return ProcReturnCode;
}
/**
* #param ProcReturnCode the ProcReturnCode to set
*/
public void setProcReturnCode(String ProcReturnCode) {
this.ProcReturnCode = ProcReturnCode;
}
/**
* #return the AuthCode
*/
#XmlElement(name="AuthCode")
public String getAuthCode() {
return AuthCode;
}
/**
* #param AuthCode the AuthCode to set
*/
public void setAuthCode(String AuthCode) {
this.AuthCode = AuthCode;
}
/**
* #return the OrderId
*/
#XmlElement(name="OrderId")
public String getOrderId() {
return OrderId;
}
/**
* #param OrderId the OrderId to set
*/
public void setOrderId(String OrderId) {
this.OrderId = OrderId;
}
/**
* #return the TransId
*/
#XmlElement(name="TransId")
public String getTransId() {
return TransId;
}
/**
* #param TransId the TransId to set
*/
public void setTransId(String TransId) {
this.TransId = TransId;
}
/**
* #return the ErrMsg
*/
#XmlElement(name="ErrMsg")
public String getErrMsg() {
return ErrMsg;
}
/**
* #param ErrMsg the ErrMsg to set
*/
public void setErrMsg(String ErrMsg) {
this.ErrMsg = ErrMsg;
}
/**
* #return the Response
*/
#XmlElement(name="Response")
public String getResponse() {
return Response;
}
/**
* #param Response the Response to set
*/
public void setResponse(String Response) {
this.Response = Response;
}
/**
* #return the HostRefNum
*/
#XmlElement(name="HostRefNum")
public String getHostRefNum() {
return HostRefNum;
}
/**
* #param HostRefNum the HostRefNum to set
*/
public void setHostRefNum(String HostRefNum) {
this.HostRefNum = HostRefNum;
}
/**
* #return the GroupId
*/
#XmlElement(name="GroupId")
public String getGroupId() {
return GroupId;
}
/**
* #param GroupId the GroupId to set
*/
public void setGroupId(String GroupId) {
this.GroupId = GroupId;
}
/**
* #return the Extra
*/
#XmlElement(name="Extra")
public List<Extra> getExtra() {
return Extra;
}
/**
* #param Extra the Extra to set
*/
public void setExtra(List<Extra> Extra) {
this.Extra = Extra;
}
}
2.2 create class named "Extra.java" like :
public class Extra {
private String SETTLEID;
private String TRXDATE;
private String ERRORCODE;
private String CARDBRAND;
private String CARDISSUER;
private String NUMCODE;
/**
* #return the SETTLEID
*/
public String getSETTLEID() {
return SETTLEID;
}
/**
* #param SETTLEID the SETTLEID to set
*/
public void setSETTLEID(String SETTLEID) {
this.SETTLEID = SETTLEID;
}
/**
* #return the TRXDATE
*/
public String getTRXDATE() {
return TRXDATE;
}
/**
* #param TRXDATE the TRXDATE to set
*/
public void setTRXDATE(String TRXDATE) {
this.TRXDATE = TRXDATE;
}
/**
* #return the ERRORCODE
*/
public String getERRORCODE() {
return ERRORCODE;
}
/**
* #param ERRORCODE the ERRORCODE to set
*/
public void setERRORCODE(String ERRORCODE) {
this.ERRORCODE = ERRORCODE;
}
/**
* #return the CARDBRAND
*/
public String getCARDBRAND() {
return CARDBRAND;
}
/**
* #param CARDBRAND the CARDBRAND to set
*/
public void setCARDBRAND(String CARDBRAND) {
this.CARDBRAND = CARDBRAND;
}
/**
* #return the CARDISSUER
*/
public String getCARDISSUER() {
return CARDISSUER;
}
/**
* #param CARDISSUER the CARDISSUER to set
*/
public void setCARDISSUER(String CARDISSUER) {
this.CARDISSUER = CARDISSUER;
}
/**
* #return the NUMCODE
*/
public String getNUMCODE() {
return NUMCODE;
}
/**
* #param NUMCODE the NUMCODE to set
*/
public void setNUMCODE(String NUMCODE) {
this.NUMCODE = NUMCODE;
}
}
Main Method should be like :
/**
* #param args the command line arguments
* #throws javax.xml.bind.JAXBException
*/
public static void main(String[] args) throws JAXBException {
// TODO code application logic here
try {
File file = new File("file.xml");
if (file.exists()) {
JAXBContext jaxbContext = JAXBContext.newInstance(CC5Response.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
CC5Response response = (CC5Response) jaxbUnmarshaller.unmarshal(file);
if (response != null) {
System.out.println("*************" + response.getAuthCode());
System.out.println("*************" + response.getErrMsg());
System.out.println("*************" + response.getGroupId());
System.out.println("*************" + response.getOrderId());
System.out.println("*************" + response.getResponse());
//you can get any field from Exta class
System.out.println("*************" + response.getExtra());
}
}
} catch (JAXBException e) {
e.printStackTrace();
}
}

Spring JPA - Data fetching selected columns

Am using Spring JPA repository
public String getNextULAID();
// Selecting particular columns from a table
#Query(value="select dbts,firstName from user_details
where ULA_ID= :ulaID and DEL_FLG = 'N'" ,nativeQuery=true)
public UserDetails fetchUser(#Param("ulaID")String ulaId);
}
Throws error
{
"timestamp": 1499336001602,
"status": 500,
"error": "Internal Server Error",
"exception": "org.springframework.dao.InvalidDataAccessResourceUsageException",
"message": "could not extract ResultSet; SQL [n/a];
nested exception is org.hibernate.exception.SQLGrammarException:
could not extract ResultSet",
"path": "/viewProfile/1"
}
But if I select all data from the database,then its working perfectly
public String getNextULAID();
// selecting all records
#Query(value="select * from user_details
where ULA_ID= :ulaID and DEL_FLG = 'N'" ,nativeQuery=true)
public UserDetails fetchUser(#Param("ulaID")String ulaId);
}
Here is my entity...
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
// End of user code
#Entity
#Table(name="user_details")
public class UserDetails {
/**
* Description of the property dbts.
*/
private Integer dbts;
/**
* Description of the property ulaId.
*/
#Id
private String ulaId = "";
/**
* Description of the property firstName.
*/
private String firstName = "";
/**
* Description of the property lastName.
*/
private String lastName = "";
/**
* Description of the property emailId.
*/
private String emailId = "";
/**
* Description of the property mobileNo.
*/
private String mobileNo = "";
/**
* Description of the property gender.
*/
private String gender = "";
/**
* Description of the property dateOfBirth.
*/
private String dateOfBirth = "";
/**
* Description of the property address1.
*/
private String address1 = "";
/**
* Description of the property address2.
*/
private String address2 = "";
/**
* Description of the property city.
*/
private String city = "";
/**
* Description of the property state.
*/
private String state = "";
/**
* Description of the property country.
*/
private String country = "";
/**
* Description of the property pincode.
*/
private String pincode = "";
/**
* Description of the property profileGroup.
*/
private String profileGroup = "";
/**
* Description of the property delFlg.
*/
private String delFlg = "";
/**
* Description of the property remarks.
*/
private String remarks = "";
/**
* Description of the property rCreTime.
*/
private String rCreTime = "";
/**
* Description of the property rModTime.
*/
private String rModTime = "";
// Start of user code (user defined attributes for UserDetails)
// End of user code
/**
* The constructor.
*/
public UserDetails() {
// Start of user code constructor for UserDetails)
super();
// End of user code
}
// Start of user code (user defined methods for UserDetails)
// End of user code
/**
* Returns dbts.
* #return dbts
*/
public Integer getDbts() {
return this.dbts;
}
/**
* Sets a value to attribute dbts.
* #param newDbts
*/
public void setDbts(Integer newDbts) {
this.dbts = newDbts;
}
/**
* Returns ulaId.
* #return ulaId
*/
public String getUlaId() {
return this.ulaId;
}
/**
* Sets a value to attribute ulaId.
* #param newUlaId
*/
public void setUlaId(String newUlaId) {
this.ulaId = newUlaId;
}
/**
* Returns firstName.
* #return firstName
*/
public String getFirstName() {
return this.firstName;
}
/**
* Sets a value to attribute firstName.
* #param newFirstName
*/
public void setFirstName(String newFirstName) {
this.firstName = newFirstName;
}
/**
* Returns lastName.
* #return lastName
*/
public String getLastName() {
return this.lastName;
}
/**
* Sets a value to attribute lastName.
* #param newLastName
*/
public void setLastName(String newLastName) {
this.lastName = newLastName;
}
/**
* Returns emailId.
* #return emailId
*/
public String getEmailId() {
return this.emailId;
}
/**
* Sets a value to attribute emailId.
* #param newEmailId
*/
public void setEmailId(String newEmailId) {
this.emailId = newEmailId;
}
/**
* Returns mobileNo.
* #return mobileNo
*/
public String getMobileNo() {
return this.mobileNo;
}
/**
* Sets a value to attribute mobileNo.
* #param newMobileNo
*/
public void setMobileNo(String newMobileNo) {
this.mobileNo = newMobileNo;
}
/**
* Returns gender.
* #return gender
*/
public String getGender() {
return this.gender;
}
/**
* Sets a value to attribute gender.
* #param newGender
*/
public void setGender(String newGender) {
this.gender = newGender;
}
/**
* Returns dateOfBirth.
* #return dateOfBirth
*/
public String getDateOfBirth() {
return this.dateOfBirth;
}
/**
* Sets a value to attribute dateOfBirth.
* #param newDateOfBirth
*/
public void setDateOfBirth(String newDateOfBirth) {
this.dateOfBirth = newDateOfBirth;
}
/**
* Returns address1.
* #return address1
*/
public String getAddress1() {
return this.address1;
}
/**
* Sets a value to attribute address1.
* #param newAddress1
*/
public void setAddress1(String newAddress1) {
this.address1 = newAddress1;
}
/**
* Returns address2.
* #return address2
*/
public String getAddress2() {
return this.address2;
}
/**
* Sets a value to attribute address2.
* #param newAddress2
*/
public void setAddress2(String newAddress2) {
this.address2 = newAddress2;
}
/**
* Returns city.
* #return city
*/
public String getCity() {
return this.city;
}
/**
* Sets a value to attribute city.
* #param newCity
*/
public void setCity(String newCity) {
this.city = newCity;
}
/**
* Returns state.
* #return state
*/
public String getState() {
return this.state;
}
/**
* Sets a value to attribute state.
* #param newState
*/
public void setState(String newState) {
this.state = newState;
}
/**
* Returns country.
* #return country
*/
public String getCountry() {
return this.country;
}
/**
* Sets a value to attribute country.
* #param newCountry
*/
public void setCountry(String newCountry) {
this.country = newCountry;
}
/**
* Returns pincode.
* #return pincode
*/
public String getPincode() {
return this.pincode;
}
/**
* Sets a value to attribute pincode.
* #param newPincode
*/
public void setPincode(String newPincode) {
this.pincode = newPincode;
}
/**
* Returns profileGroup.
* #return profileGroup
*/
public String getProfileGroup() {
return this.profileGroup;
}
/**
* Sets a value to attribute profileGroup.
* #param newProfileGroup
*/
public void setProfileGroup(String newProfileGroup) {
this.profileGroup = newProfileGroup;
}
/**
* Returns delFlg.
* #return delFlg
*/
public String getDelFlg() {
return this.delFlg;
}
/**
* Sets a value to attribute delFlg.
* #param newDelFlg
*/
public void setDelFlg(String newDelFlg) {
this.delFlg = newDelFlg;
}
/**
* Returns remarks.
* #return remarks
*/
public String getRemarks() {
return this.remarks;
}
/**
* Sets a value to attribute remarks.
* #param newRemarks
*/
public void setRemarks(String newRemarks) {
this.remarks = newRemarks;
}
/**
* Returns rCreTime.
* #return rCreTime
*/
public String getRCreTime() {
return this.rCreTime;
}
/**
* Sets a value to attribute rCreTime.
* #param newRCreTime
*/
public void setRCreTime(String newRCreTime) {
this.rCreTime = newRCreTime;
}
/**
* Returns rModTime.
* #return rModTime
*/
public String getRModTime() {
return this.rModTime;
}
/**
* Sets a value to attribute rModTime.
* #param newRModTime
*/
public void setRModTime(String newRModTime) {
this.rModTime = newRModTime;
}
}
What changes i have to do, to get specific columns from multiple data.
Thanks in advance.
You should return List<Object[]> instead of UserDetails in case of native query.
Another way is to create projection. You can use projections from Spring Data JPA http://docs.spring.io/spring-data/jpa/docs/current/reference/html/#projections.

Java How create a set of object with two classes?

I have a logical problem to understand, how create a private set of inhabitant object. Here my two classes:
package main;
import java.util.Set;
/**
* #author
* #version 0.1
*
*/
public class City {
private String name;
/**
*HERE is my Problem*/
private Set<Inhabitants> Inhabitants {
}
/**
* standard cunstructor
*/
public City(String n, ) {
setName(n);
}
/**
* Search a particular name of inhabitant
* #return object of inhabitant
*/
static Set<Inhabitants> Search(){
return inhabitants;
}
/**
* Creates a inhabitant object and
* add to the set of inhabitants of the city
*
* #param name
* #param datebirth
* #param maritalStatus
* #
*/
public void Add(String name,String datebirth,String maritalStatus) {
}
/**
* Return all inhabitants objects of the city
* #return
*/
static Set<Inhabitants> ReturnAll(){
return inhabitants;
}
/**
* Return city name
* #return
*/
static Set<Inhabitants> ReturnCityName(){
return inhabitants;
}
/**
* #return the name
*/
public String getName() {
return name;
}
/**
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* #return the inhabitants
*/
public Set<Inhabitants> getInhabitants() {
return inhabitants;
}
/**
* #param inhabitants the inhabitants to set
*/
public void setInhabitants(Set<Inhabitants> inhabitants) {
this.inhabitants = inhabitants;
}
}
package main;
/**
* #version 0.1
*/
public class Inhabitants {
private String name;
private String datebirth;
private Boolean maritalStatus;
/**
* standard constructor
*/
public Inhabitants() {
}
/**
* #return the name
*/
public String getName() {
return name;
}
/**
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/**
* #return the datebirth
*/
public String getDatebirth() {
return datebirth;
}
/**
* #param datebirth the datebirth to set
*/
public void setDatebirth(String datebirth) {
this.datebirth = datebirth;
}
/**
* #return the maritalStatus
*/
public Boolean getMaritalStatus() {
return maritalStatus;
}
/**
* #param maritalStatus the maritalStatus to set
*/
public void setMaritalStatus(Boolean maritalStatus) {
this.maritalStatus = maritalStatus;
}
}
It sounds like a simple problem. You didn't need so much code:
package collections;
/**
* Person
* #author Michael
* #link https://stackoverflow.com/questions/30958832/java-how-create-a-set-of-object-with-two-classes
* #since 6/20/2015 5:06 PM
*/
public class Person {
private final String name;
public Person(String name) {
if (name == null || name.trim().length() == 0) throw new IllegalArgumentException("name cannot be blank or null");
this.name = name;
}
public String getName() {
return name;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Person person = (Person) o;
return name.equals(person.name);
}
#Override
public int hashCode() {
return name.hashCode();
}
#Override
public String toString() {
final StringBuilder sb = new StringBuilder("Person{");
sb.append("name='").append(name).append('\'');
sb.append('}');
return sb.toString();
}
}
package collections;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
/**
* City
* #author Michael
* #link https://stackoverflow.com/questions/30958832/java-how-create-a-set-of-object-with-two-classes
* #since 6/20/2015 5:06 PM
*/
public class City {
private Set<Person> inhabitants;
public City(Collection<Person> inhabitants) {
this.inhabitants = (inhabitants == null) ? new HashSet<Person>() : new HashSet<Person>(inhabitants);
}
public void addInhabitant(Person p) {
if (p != null) {
this.inhabitants.add(p);
}
}
#Override
public String toString() {
final StringBuilder sb = new StringBuilder("City{");
sb.append("inhabitants=").append(inhabitants);
sb.append('}');
return sb.toString();
}
}

JAXB #XmlAttribute #XmlValue real example

I'm new to JAXB and have troubles with conversion from XML to a Java class instance.
I have the following XML:
<?xml version="1.0"?>
<response>
<category>client</category>
<action>Greeting</action>
<code>1000</code>
<msg>Your Connection with API Server is Successful</msg>
<resData>
<data name="svDate">2009-02-16 06:22:21</data>
</resData>
</response>
and I develop the following Java code:
/**
* Copyright 2013. ABN Software. All Rights reserved.<br>
* Author ...... Andre<br>
* Created ..... 14.03.2013<br>
* <br>
*/
package net.regmaster.onlinenic.model;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlRootElement;
import net.regmaster.onlinenic.enumtype.OnicEnumAction;
import net.regmaster.onlinenic.enumtype.OnicEnumCategory;
import net.regmaster.onlinenic.model.resdata.GreetingResData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* #author annik
*
*/
#XmlRootElement(name = "response")
// #XmlType( propOrder = { "category", "action", "code", "message"})
public class OnicGreeting
{
private OnicEnumCategory category;
private OnicEnumAction action;
private Integer code;
private String message;
private GreetingResData resData;
//
private Logger LOG = LoggerFactory.getLogger(getClass());
/**
* Getter.
*
* #return the category
*/
public OnicEnumCategory getCategory() {
return category;
}
/**
* Setter.
*
* #param category
* the category to set
*/
public void setCategoryEnum(OnicEnumCategory category) {
this.category = category;
}
#XmlElement
public void setCategory(String category) {
try {
this.category = OnicEnumCategory.getEnum(category);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
LOG.error(e.getMessage());
}
}
/**
* Getter.
*
* #return the action
*/
public OnicEnumAction getAction() {
return action;
}
/**
* Setter.
*
* #param action
* the action to set
*/
public void setActionEnum(OnicEnumAction action) {
this.action = action;
}
#XmlElement
public void setAction(String action) {
try {
this.action = OnicEnumAction.getEnum(action);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
LOG.error(e.getMessage());
}
}
/**
* Getter.
*
* #return the code
*/
#XmlElement
public Integer getCode() {
return code;
}
/**
* Setter.
*
* #param code
* the code to set
*/
public void setCode(Integer code) {
this.code = code;
}
/**
* Getter.
*
* #return the message
*/
#XmlElement(name = "msg")
public String getMessage() {
return message;
}
/**
* Setter.
*
* #param message
* the message to set
*/
public void setMessage(String message) {
this.message = message;
}
/**
* Getter.
*
* #return the resData
*/
#XmlElementRef
public GreetingResData getResData() {
return resData;
}
/**
* Setter.
*
* #param resData
* the resData to set
*/
public void setResData(GreetingResData resData) {
this.resData = resData;
}
#Override
public String toString() {
return "category=" + category + ", action=" + action + ", code=" + code + ", msg=" + message
+ ", resData:" + resData.toString();
}
}
and
/**
* Copyright 2013. ABN Software. All Rights reserved.<br>
* Author ...... Andre<br>
* Created ..... 14.03.2013<br>
* <br>
*/
package net.regmaster.onlinenic.model.resdata;
import java.util.Calendar;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlValue;
/**
* #author annik
*
*/
#XmlRootElement(name="resData")
public class GreetingResData extends AbstractResData
{
String svDate;
/**
* Constructor.
*
*/
public GreetingResData() {
// TODO Auto-generated constructor stub
}
/**
* Getter.
*
* #return the svDate
*/
#XmlAttribute
public String getSvDate() {
return svDate;
}
/**
* Setter.
*
* #param svDate
* the svDate to set
*/
public void setSvDate(String svDate) {
this.svDate = svDate;
}
}
These code examples run but data is wrong :
http://i.stack.imgur.com/qCCIM.png
Please help me.
Also I do not understand in case I will have many different
<data ...>..</data>
What could I do easy and simply?
I mean this case:
<resData>
<data name="crDate">2004-12-17</data>
<data name="exDate">2009-01-02</data>
<data name="password">7fe11fd9d97ee40bdf57e561427c0a6</data>
<data name="dns">dns1.onlinenic.net</data>
<data name="dns">dns2.onlinenic.net</data>
<data name="r_name">123456</data>
<data name="r_org">123456</data>
<data name="r_country">BJ</data>
<data name="r_province">mokcup</data>
<data name="r_city">123456</data>
<data name="r_street">123456</data>
<data name="r_postalcode">123456</data>
<data name="r_voice">+86.5925391800</data>
<data name="r_fax">+86.5925391800</data>
<data name="r_email">asdfasdf#sadf.com</data>
....
Thank you Blaise Doughan.
But after dug more over 10 topics I decide I HAD TO to start with opposite way.
I created new test which MARSHALLING my data (objects). Actually, I used TDD (test Driven Development) way I think.
So, I filled up my Objects with test data and applied Marshalling (created XML from DATA) and saw that I got. Data Was Incorrect. I looked to other topic also (thanx this one Java/JAXB: Unmarshall Xml to specific subclass based on an attribute ) and correct my data Structure
remember Id like to get
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<response>
<code>1000</code>
<message>Big message</message>
<resData>
<data name="svDate">2013.03.14</data>
</resData>
</response>
Now my data are :
package net.regmaster.onlinenic.model.response.resdata;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlValue;
import org.eclipse.persistence.oxm.annotations.XmlCustomizer;
/**
* #author annik
*
*/
#XmlAccessorType(XmlAccessType.FIELD)
#XmlRootElement(name="data")
//#XmlCustomizer(ResDataCustomiser.class)
public class XmlData
{
#XmlAttribute(name="name")
private String name;
#XmlValue
private String value;
/** Getter.
* #return the name
*/
public String getName() {
return name;
}
/** Setter.
* #param name the name to set
*/
public void setName(String name) {
this.name = name;
}
/** Getter.
* #return the value
*/
public String getValue() {
return value;
}
/** Setter.
* #param value the value to set
*/
public void setValue(String value) {
this.value = value;
}
}
and :
package net.regmaster.onlinenic.model.response.resdata;
import java.util.List;
import javax.xml.bind.annotation.XmlRootElement;
/**
* #author annik
*
*/
#XmlRootElement
public class ResData
{
private List<XmlData> data;
/**
* Getter.
*
* #return the data
*/
public List<XmlData> getData() {
return data;
}
/**
* Setter.
*
* #param data
* the data to set
*/
public void setData(List<XmlData> data) {
this.data = data;
}
}
and :
package net.regmaster.onlinenic.model.response;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElements;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import javax.xml.bind.annotation.XmlType;
import net.regmaster.onlinenic.enumtype.OnicEnumAction;
import net.regmaster.onlinenic.enumtype.OnicEnumCategory;
import net.regmaster.onlinenic.model.response.resdata.ResData;
import net.regmaster.onlinenic.model.response.resdata.XmlData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* #author annik
*
*/
#XmlRootElement(name = "response")
//#XmlType( propOrder = { "category", "action", "code", "message"})
public class OnicGreetingResponse
{
private OnicEnumCategory category;
private OnicEnumAction action;
private Integer code;
private String message;
// private GreetingResData resData;
private ResData resData;
//
#XmlTransient
private Logger LOG = LoggerFactory.getLogger(getClass());
/**
* Getter.
*
* #return the category
*/
public OnicEnumCategory getCategory() {
return category;
}
/**
* Setter.
*
* #param category
* the category to set
*/
public void setCategoryEnum(OnicEnumCategory category) {
this.category = category;
}
#XmlElement
public void setCategory(String category) {
try {
this.category = OnicEnumCategory.getEnum(category);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
LOG.error(e.getMessage());
}
}
/**
* Getter.
*
* #return the action
*/
public OnicEnumAction getAction() {
return action;
}
/**
* Setter.
*
* #param action
* the action to set
*/
public void setActionEnum(OnicEnumAction action) {
this.action = action;
}
#XmlElement
public void setAction(String action) {
try {
this.action = OnicEnumAction.getEnum(action);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
LOG.error(e.getMessage());
}
}
/**
* Getter.
*
* #return the code
*/
#XmlElement
public Integer getCode() {
return code;
}
/**
* Setter.
*
* #param code
* the code to set
*/
public void setCode(Integer code) {
this.code = code;
}
/**
* Getter.
*
* #return the message
*/
#XmlElements(value={#XmlElement})
public String getMessage() {
return message;
}
/**
* Setter.
*
* #param message
* the message to set
*/
public void setMessage(String message) {
this.message = message;
}
/** Getter.
* #return the resData
*/
public ResData getResData() {
return resData;
}
/** Setter.
* #param resData the resData to set
*/
#XmlElement
public void setResData(ResData resData) {
this.resData = resData;
}
#Override
public String toString() {
return "category=" + category + ", action=" + action + ", code=" + code + ", msg=" + message
+ ", resData:" + resData.toString();
}
}
and vu-alja :
I got that !
And as you can see below it works to another way :
http://i.stack.imgur.com/35nzb.png

Categories