NPE when marshalling/unmarshalling JAXBElement - jaxb

I have following JAXB-mapped class:
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "date_or_period_t", propOrder = {
"date", "beginDate", "endDate"
})
public class DateOrPeriodT
implements Serializable
{
private final static long serialVersionUID = 1L;
#XmlElementRef(name = "date", type = JAXBElement.class, required = false)
protected JAXBElement<DateOrDatetimeT> date;
#XmlElementRef(name = "begin_date", type = JAXBElement.class, required = false)
protected JAXBElement<Date> beginDate;
#XmlElementRef(name = "end_date", type = JAXBElement.class, required = false)
protected JAXBElement<Date> endDate;
public JAXBElement<DateOrDatetimeT> getDate() { return date; }
public void setDate(JAXBElement<DateOrDatetimeT> value) { this.date = value; }
public JAXBElement<Date> getBeginDate() { return beginDate; }
public void setBeginDate(JAXBElement<Date> value) { this.beginDate = value; }
public JAXBElement<Date> getEndDate() { return endDate; }
public void setEndDate(JAXBElement<Date> value) { this.endDate = value; }
}
and corresponding xsd:
<xsd:complexType name="date_or_period_t">
<xsd:choice minOccurs="0">
<xsd:element name="date" type="date_or_datetime_t" nillable="true"></xsd:element>
<xsd:sequence>
<xsd:element name="begin_date" type="xsd:date" nillable="true"></xsd:element>
<xsd:element name="end_date" type="xsd:date" nillable="true"></xsd:element>
</xsd:sequence>
</xsd:choice>
</xsd:complexType>
When one or both end_date, begin_date is set to xsi:nil="true", MOXy throws NPE:
Caused by: java.lang.NullPointerException
at org.eclipse.persistence.internal.jaxb.XMLJavaTypeConverter.convertDataValueToObjectValue(XMLJavaTypeConverter.java:155)
at org.eclipse.persistence.oxm.mappings.converters.XMLConverterAdapter.convertDataValueToObjectValue(XMLConverterAdapter.java:28)
at org.eclipse.persistence.oxm.mappings.converters.XMLConverterAdapter.convertDataValueToObjectValue(XMLConverterAdapter.java:1)
at org.eclipse.persistence.internal.jaxb.JAXBElementConverter.convertDataValueToObjectValue(JAXBElementConverter.java:78)
at org.eclipse.persistence.internal.jaxb.JAXBElementConverter.convertDataValueToObjectValue(JAXBElementConverter.java:56)
at org.eclipse.persistence.oxm.mappings.XMLDirectMapping.convertDataValueToObjectValue(XMLDirectMapping.java:526)
at org.eclipse.persistence.oxm.mappings.XMLDirectMapping.getAttributeValue(XMLDirectMapping.java:296)
at org.eclipse.persistence.oxm.mappings.XMLDirectMapping.getAttributeValue(XMLDirectMapping.java:1)
at org.eclipse.persistence.internal.oxm.XMLDirectMappingNodeValue.endElement(XMLDirectMappingNodeValue.java:165)
at org.eclipse.persistence.internal.oxm.XMLChoiceObjectMappingNodeValue.endElement(XMLChoiceObjectMappingNodeValue.java:177)
at org.eclipse.persistence.internal.oxm.record.UnmarshalRecordImpl.endElement(UnmarshalRecordImpl.java:1050)
at org.eclipse.persistence.internal.oxm.record.XMLStreamReaderReader.parseEvent(XMLStreamReaderReader.java:154)
at org.eclipse.persistence.internal.oxm.record.XMLStreamReaderReader.parse(XMLStreamReaderReader.java:99)
at org.eclipse.persistence.internal.oxm.record.XMLStreamReaderReader.parse(XMLStreamReaderReader.java:86)
at org.eclipse.persistence.internal.oxm.record.SAXUnmarshaller.unmarshal(SAXUnmarshaller.java:895)
at org.eclipse.persistence.oxm.XMLUnmarshaller.unmarshal(XMLUnmarshaller.java:659)
at org.eclipse.persistence.jaxb.JAXBUnmarshaller.unmarshal(JAXBUnmarshaller.java:585)
at org.eclipse.persistence.jaxb.JAXBUnmarshaller.unmarshal(JAXBUnmarshaller.java:140)
When date is xsi:nil it works fine, when both begin_date and end_date is not xsi:nil it's fine.
#XmlElementDecl(namespace = "", name = "date", scope = DateOrPeriodT.class)
public JAXBElement<DateOrDatetimeT> createDateOrPeriodTDate(DateOrDatetimeT value) {
return new JAXBElement<DateOrDatetimeT>(_DateOrPeriodTDate_QNAME, DateOrDatetimeT.class, DateOrPeriodT.class, value);
}
#XmlElementDecl(namespace = "", name = "begin_date", scope = DateOrPeriodT.class)
#XmlJavaTypeAdapter(AdapterDate.class)
public JAXBElement<Date> createDateOrPeriodTBeginDate(Date value) {
return new JAXBElement<Date>(_DateOrPeriodTBeginDate_QNAME, Date.class, DateOrPeriodT.class, value);
}
#XmlElementDecl(namespace = "", name = "end_date", scope = DateOrPeriodT.class)
#XmlJavaTypeAdapter(AdapterDate.class)
public JAXBElement<Date> createDateOrPeriodTEndDate(Date value) {
return new JAXBElement<Date>(_DateOrPeriodTEndDate_QNAME, Date.class, DateOrPeriodT.class, value);

When I use the following setup, everything works fine.
class DateOrDatetimeT ->
package org.eclipse.persistence.testing.jaxb.aso.np;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlType;
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "date", propOrder = {
"date"
})
public class DateOrDatetimeT {
private java.util.Date date;
public java.util.Date getDate() {
return date;
}
public void setDate(java.util.Date date) {
this.date = date;
}
#Override
public String toString() {
return "DateOrDatetimeT [date=" + date + "]";
}
}
class DateOrPeriodT ->
package org.eclipse.persistence.testing.jaxb.aso.np;
import java.io.Serializable;
import java.util.Date;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlType;
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "date_or_period_t", propOrder = {
"date", "beginDate", "endDate"
})
public class DateOrPeriodT
implements Serializable {
private final static long serialVersionUID = 1L;
#XmlElementRef(name = "date", type = JAXBElement.class, required = false)
protected JAXBElement<DateOrDatetimeT> date;
#XmlElementRef(name = "begin_date", type = JAXBElement.class, required = false)
protected JAXBElement<Date> beginDate;
#XmlElementRef(name = "end_date", type = JAXBElement.class, required = false)
protected JAXBElement<Date> endDate;
public JAXBElement<DateOrDatetimeT> getDate() {
return date;
}
public void setDate(JAXBElement<DateOrDatetimeT> value) {
this.date = value;
}
public JAXBElement<Date> getBeginDate() {
return beginDate;
}
public void setBeginDate(JAXBElement<Date> value) {
this.beginDate = value;
}
public JAXBElement<Date> getEndDate() {
return endDate;
}
public void setEndDate(JAXBElement<Date> value) {
this.endDate = value;
}
#Override
public String toString() {
return "DateOrPeriodT [date=" + getJAXBElementString(date) + ", beginDate=" + getJAXBElementString(beginDate) + ", endDate=" + getJAXBElementString(endDate) + "]";
}
private String getJAXBElementString(JAXBElement<?> element) {
if (null == element) {
return null;
}
return "{" + element.getName() + ":" + element.getValue() + "}";
}
}
class ObjectFactory
package org.eclipse.persistence.testing.jaxb.aso.np;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlElementDecl;
import javax.xml.bind.annotation.XmlRegistry;
import javax.xml.namespace.QName;
import java.util.Date;
#XmlRegistry
public class ObjectFactory {
#XmlElementDecl(name = "date")
JAXBElement<DateOrDatetimeT> createDate(Date date) {
DateOrDatetimeT dateOrDateTime = new DateOrDatetimeT();
dateOrDateTime.setDate(date);
return new JAXBElement<DateOrDatetimeT>(new QName("date"), DateOrDatetimeT.class, dateOrDateTime);
}
#XmlElementDecl(name = "begin_date")
JAXBElement<Date> createBeginDate(Date date) {
return new JAXBElement<Date>(new QName("begin_date"), Date.class, date);
}
#XmlElementDecl(name = "end_date")
JAXBElement<Date> createEndDate(Date date) {
return new JAXBElement<Date>(new QName("end_date"), Date.class, date);
}
}
file jaxb.properties
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
class Test
package org.eclipse.persistence.testing.jaxb.aso.np;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.Unmarshaller;
import java.io.InputStream;
import java.util.HashMap;
public class Test {
public static void main(String[] args) throws Exception {
try (InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("org/eclipse/persistence/testing/jaxb/aso/date.xml")) {
JAXBContext jc = JAXBContext.newInstance(new Class[]{DateOrPeriodT.class, DateOrDatetimeT.class, ObjectFactory.class}, new HashMap<String, Object>());
Unmarshaller marshaller = jc.createUnmarshaller();
JAXBElement el = (JAXBElement) marshaller.unmarshal(is);
DateOrPeriodT dateOrPeriodT = (DateOrPeriodT) el.getValue();
System.out.println("dateOrPeriodT=" + dateOrPeriodT);
}
}
}
different versions of date.xml (tested with EclipseLink 2.5.2)
<date_or_period_t xsi:type="date_or_period_t" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<date>2015-02-16T14:49:46.583+01:00</date>
<begin_date>2015-02-16T14:49:46.583+01:00</begin_date>
<end_date>2015-02-15T14:49:46.583+01:00</end_date>
</date_or_period_t>
<date_or_period_t xsi:type="date_or_period_t" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<date>2015-02-16T14:49:46.583+01:00</date>
<begin_date xsi:nil="true" />
<end_date>2015-02-15T14:49:46.583+01:00</end_date>
</date_or_period_t>
<date_or_period_t xsi:type="date_or_period_t" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<date>2015-02-16T14:49:46.583+01:00</date>
<begin_date xsi:nil="true" />
<end_date xsi:nil="true" />
</date_or_period_t>
<date_or_period_t xsi:type="date_or_period_t" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<begin_date xsi:nil="true" />
<end_date>2015-02-15T14:49:46.583+01:00</end_date>
</date_or_period_t>
<date_or_period_t xsi:type="date_or_period_t" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<begin_date xsi:nil="true" />
<end_date xsi:nil="true" />
</date_or_period_t>
<date_or_period_t xsi:type="date_or_period_t" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<begin_date>2015-02-15T14:49:46.583+01:00</begin_date>
<end_date>2015-02-15T14:49:46.583+01:00</end_date>
</date_or_period_t>
If you use EclipseLink 2.6.0, xml needs nested date element:
<date_or_period_t xsi:type="date_or_period_t" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<date><date>2015-02-16T14:49:46.583+01:00</date></date>
<begin_date>2015-02-16T14:49:46.583+01:00</begin_date>
<end_date>2015-02-15T14:49:46.583+01:00</end_date>
</date_or_period_t>

Related

Create xml string for java jaxb bean with Root class & inner classes having different name spaces

I have a Root Class called Employee, which has two elements empid and name and another jaxb class called Address. Below is the sample snippet.
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "Request",propOrder = {
"header",
"body",
"signature"
})
#XmlRootElement(name="Employee")
public class Employee
implements Serializable
{
#XmlElement(name = "Header", required = true)
protected String empId;
#XmlElement(name = "Body", required = true)
protected String empName;
#XmlElement(name = "Address", required = true)
protected Address address;
.. setters and getters
}
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "Address", propOrder = {
"streetLine1",
"streetLine2",
})
#XmlRootElement(name="Address",namespace= "http://www.w3.org/2000/09/xmldsig#")
public class Employee
implements Serializable
{
private final static long serialVersionUID = 100L;
#XmlElement(name = "addressLine1", required = true)
protected String addressLine1;
#XmlElement(name = "addressLine2", required = true)
protected String addressLine2;
//Setters and getters
}
Now when I generate the XML string with jaxb marshalling I want the expected result like this:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Employee xmlns="http://www.test.com">
<empId>124</empId>
<empName>name</empName>
<Address xmlns:ns2="http://www.w3.org/2000/09/xmldsig#">
<ns2:streetLine1 Id="line1"/>
<ns2:streetLine2 Id="Line2"/>
</Address>
</Request>
Please suggest. Thanks in Advance.
There are some problems with your JAXB classes, I think you have copy pasted and changed some names wrongly. The following elements inside #XMLType must be defined as #XMLElement.
#XmlType(name = "Request",propOrder = {
"header",
"body",
"signature"
})
Anyways assuming the classes are right. You will need 2 changes to generate XML that has elements referred in different namespace.
Move the namespace to package level using #XMLSchema. i.e Add package-info.java at the package level to specify the namespaces.
Provide Address element with its own namespace in Employee class. Each element if not in parent namespace, must be overridden at this level.
package-info.java
#XmlSchema(
namespace = "http://www.test.com",
elementFormDefault = XmlNsForm.QUALIFIED)
package int1.d;
import javax.xml.bind.annotation.*;
Employee.java
package int1.d;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "Request",propOrder = {
"header",
"body",
"signature"
})
#XmlRootElement(name="Employee")
public class Employee
implements Serializable
{
private static final long serialVersionUID = 8293193254658211943L;
#XmlElement(name = "Header", required = true)
protected String empId;
#XmlElement(name = "Body", required = true)
protected String empName;
#XmlElement(name = "Address", namespace="http://www.w3.org/2000/09/xmldsig#", required = true )
protected Address address;
public String getEmpId() {
return empId;
}
public void setEmpId(String empId) {
this.empId = empId;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
package-info.java
#XmlSchema(
namespace = "http://www.w3.org/2000/09/xmldsig#",
elementFormDefault=XmlNsForm.QUALIFIED )
package int1.d2;
import javax.xml.bind.annotation.*;
Address.java
package int1.d2;
import java.io.Serializable;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
#XmlAccessorType(XmlAccessType.FIELD)
#XmlType(name = "Address", propOrder = {
"streetLine1",
"streetLine2",
})
#XmlRootElement(name="Address")
public class Address
implements Serializable
{
private final static long serialVersionUID = 100L;
#XmlElement(name = "addressLine1", required = true)
protected String addressLine1;
#XmlElement(name = "addressLine2", required = true)
protected String addressLine2;
public String getAddressLine1() {
return addressLine1;
}
public void setAddressLine1(String addressLine1) {
this.addressLine1 = addressLine1;
}
public String getAddressLine2() {
return addressLine2;
}
public void setAddressLine2(String addressLine2) {
this.addressLine2 = addressLine2;
}
}
output generated by JAXB
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Employee xmlns="http://www.test.com" xmlns:ns2="http://www.w3.org/2000/09/xmldsig#">
<Header>124</Header>
<Body>bae</Body>
<ns2:Address>
<ns2:addressLine1>line1</ns2:addressLine1>
<ns2:addressLine2>line2</ns2:addressLine2>
</ns2:Address>
</Employee>

getting null response of parsing XML using JaxB

how i can parse the XML using Jaxb.
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://www.xyz.in"><root><Del><NUMBER>13691991</NUMBER><PIECES>2</PIECES><SHEETNO>D1415/001005</SHEETNO></Del></root></string>
Try to create these classes:
The class Del
package jaxb;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlAccessorType(XmlAccessType.FIELD)
#XmlRootElement( name = "Del")
public class Del {
#XmlElement(name = "NUMBER")
private String number;
#XmlElement(name = "PIECES")
private String pieces;
#XmlElement(name = "SHEETNO")
private String sheetno;
public Del() {
super();
}
public void setNumber(String number) {
this.number = number;
}
public String getNumber() {
return number;
}
public void setPieces(String pieces) {
this.pieces = pieces;
}
public String getPieces() {
return pieces;
}
public void setSheetno(String sheetno) {
this.sheetno = sheetno;
}
public String getSheetno() {
return sheetno;
}
}
The class MyString
package jaxb;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlAccessorType(XmlAccessType.FIELD)
#XmlRootElement( name = "string")
public class MyString {
#XmlElement(name = "root")
private Root root;
public MyString() {
super();
}
public void setRoot(Root root) {
this.root = root;
}
public Root getRoot() {
return root;
}
}
The class Root
package jaxb;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlAccessorType(XmlAccessType.FIELD)
#XmlRootElement( name = "root")
public class Root {
#XmlElement(name = "Del")
private Del del;
public Root() {
super();
}
public void setDel(Del del) {
this.del = del;
}
public Del getDel() {
return del;
}
}
The file package-info.java
#XmlSchema( namespace="http://www.xyz.in",
xmlns={ #XmlNs( prefix = "", namespaceURI = "http://www.xyz.in")},
elementFormDefault = XmlNsForm.QUALIFIED)
package jaxb;
import javax.xml.bind.annotation.XmlNs;
import javax.xml.bind.annotation.XmlNsForm;
import javax.xml.bind.annotation.XmlSchema;
**The Main class to test **
package jaxb;
import java.io.StringReader;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Unmarshaller;
public class Main {
public static void main(String[] args){
try {
String file = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
"<string xmlns=\"http://www.xyz.in\">\n" +
" <root>\n" +
" <Del>\n" +
" <NUMBER>13691991</NUMBER>\n" +
" <PIECES>2</PIECES>\n" +
" <SHEETNO>D1415/001005</SHEETNO>\n" +
" </Del>\n" +
" </root>\n" +
"</string>";
JAXBContext jaxbContext = JAXBContext.newInstance(MyString.class);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
StringReader reader = new StringReader(file);
MyString myString = (MyString)jaxbUnmarshaller.unmarshal(reader);
System.out.println(myString);
} catch (JAXBException e) {
e.printStackTrace();
}
}
}

Adding default namespace declarations using a generic list wrapper with JAXB

I am all new to JAXB and having wrecked my brains for a week over this I would like to ask the following question. How can I obtain default namespace declarations like these using a generic list wrapper as Blaise Doughan indroduced:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<departments xmlns="urn:example.org/departments">
<department>
<iddepartment>1</iddepartment>
<department>Deparment A</department>
<v_iddepartment>1</v_iddepartment>
</department>
<department>
<iddepartment>2</iddepartment>
<department>Department B</department>
<v_iddepartment>1</v_iddepartment>
</department>
</departments>
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<employees xmlns="urn:example.org/employees">
<employee>
<firstname>Tom</firstname>
<lastname>Jones</lastname>
<praefix>Dr.</praefix>
<birthdate>1970-01-01</birthdate>
<ipnumber>1234</ipnumber>
</employee>
<employee>
<firstname>Elvis</firstname>
<lastname>Knoxville</lastname>
<praefix/>
<birthdate>1970-01-02</birthdate>
<ipnumber>4567</ipnumber>
</employee>
</employees>
I have several annotated classes like these:
package org.bp24.server.table;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
#XmlRootElement(name = "department", namespace = "urn:example.org/departments")
#XmlType(propOrder = {"iddepartment", "department", "v_iddepartment"})
public class Department {
private int iddepartment;
private String department;
private int v_iddepartment;
public int getIddepartment() {
return iddepartment;
}
public void setIddepartment(int iddepartment) {
this.iddepartment = iddepartment;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public int getV_iddepartment() {
return v_iddepartment;
}
public void setV_iddepartment(int v_iddepartment) {
this.v_iddepartment = v_iddepartment;
}
}
package org.bp24.server.table;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import javax.xml.bind.annotation.XmlType;
#XmlRootElement(name = "employee", namespace = "urn:example.org/employees")
#XmlType(propOrder = {"firstname", "lastname", "praefix", "suffix", "birthdate", "ipnumber"})
public class Employee {
private int idemployee;
private String firstname;
private String lastname;
private String praefix;
private String suffix;
private String birthdate;
private String ipnumber;
private int v_iduser;
#XmlTransient
public int getIdemployee() {
return idemployee;
}
public void setIdemployee(int idemployee) {
this.idemployee = idemployee;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getPraefix() {
return praefix;
}
public void setPraefix(String praefix) {
this.praefix = praefix;
}
public String getSuffix() {
return suffix;
}
public void setSuffix(String suffix) {
this.suffix = suffix;
}
public String getBirthdate() {
return birthdate;
}
public void setBirthdate(String birthdate) {
this.birthdate = birthdate;
}
public String getIpnumber() {
return ipnumber;
}
public void setIpnumber(String ipnumber) {
this.ipnumber = ipnumber;
}
#XmlTransient
public int getV_iduser() {
return v_iduser;
}
public void setV_iduser(int v_iduser) {
this.v_iduser = v_iduser;
}
}
Here is the list wrapper I use:
package org.bp24.server.xml.copy;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAnyElement;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementWrapper;
public class GenericList <T> {
private List<T> list = new ArrayList<T>();
public GenericList() {
}
public GenericList(List<T> list) {
this.list = list;
}
public void add (T element){
list.add(element);
}
public boolean isEmpty(){
if(list.isEmpty()) return true;
return false;
}
public T get (int pos){
return list.get(pos);
}
#XmlAnyElement(lax=true)
public List<T> getList(){
return list;
}
}
And here is the marshalling code:
package org.bp24.server.xml.copy;
import java.util.HashMap;
import java.util.List;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.namespace.QName;
import org.bp24.server.xml.GenericList;
public class MarshallMatters<T> {
private static volatile HashMap<Class, JAXBContext> contextStore = new HashMap<Class, JAXBContext>();
//synchronized to ensure orderly concurrent contextStore access
private synchronized JAXBContext getContext (Class clazz) throws JAXBException{
if(contextStore.containsKey(clazz)) return contextStore.get(clazz);
JAXBContext context = JAXBContext.newInstance(GenericList.class, clazz);
contextStore.put(clazz, context);
return context;
}
private Class getClassFromList(List<T> list){
if(!list.isEmpty()) return list.get(0).getClass();
return null;
}
public void writeXml(List<T> list) throws JAXBException{
Class clazz = getClassFromList(list);
if(clazz==null){
System.out.println("Error message");
return;
}
JAXBContext jc = getContext(clazz);
GenericList<T> genList = new GenericList<T>(list);
Marshaller m = jc.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
QName qn = new QName(clazz.getSimpleName().toLowerCase() + "s");
JAXBElement<GenericList> jaxbe = new JAXBElement<GenericList>(qn, GenericList.class, genList);
m.marshal(jaxbe, System.out);
}
public void readXml(List<T> list) throws JAXBException{
...
}
}
Thank you very much in advance for your help.

Transactions in JSF Netbeans 7.3.1 generated code

I'm new to Java EE, following the learning by doing approach. In a very simple Mysql database with Netbeans 7.3.1 having a Patient table relates to a Person table, I'm having trouble understanding Netbeans generated code. I want to create a transaction where a Person and a Patient should be created and persisted with roll back possibility. Should i create a separate controller to handle such a transaction. Kindly help with a link to some similar example code. Code generated by Netbeans is below. (Some imports and redundant code removed)
Person.java
package entity;
import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
#Entity
#Table(name = "person")
#XmlRootElement
public class Person implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 45)
#Column(name = "firstname")
private String firstname;
#Size(max = 255)
#Column(name = "email")
private String email;
#Size(max = 15)
#Column(name = "mobile")
private String mobile;
#Size(max = 15)
#Column(name = "residence")
private String residence;
#Size(max = 15)
#Column(name = "office")
private String office;
#Size(max = 255)
#Column(name = "address")
private String address;
#Size(max = 20)
#Column(name = "nic")
private String nic;
#Basic(optional = false)
#NotNull
#Column(name = "regdate")
#Temporal(TemporalType.DATE)
private Date regdate;
#Basic(optional = false)
#NotNull
#Column(name = "dob")
#Temporal(TemporalType.DATE)
private Date dob;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 45)
#Column(name = "lastname")
private String lastname;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 25)
#Column(name = "city")
private String city;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "personid")
private Collection<Patient> patientCollection;
public Person() {
}
public Person(Integer id) {
this.id = id;
}
public Person(Integer id, String firstname, Date regdate, Date dob, String lastname, String city) {
this.id = id;
this.firstname = firstname;
this.regdate = regdate;
this.dob = dob;
this.lastname = lastname;
this.city = city;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getResidence() {
return residence;
}
public void setResidence(String residence) {
this.residence = residence;
}
public String getOffice() {
return office;
}
public void setOffice(String office) {
this.office = office;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getNic() {
return nic;
}
public void setNic(String nic) {
this.nic = nic;
}
public Date getRegdate() {
return regdate;
}
public void setRegdate(Date regdate) {
this.regdate = regdate;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
#XmlTransient
public Collection<Patient> getPatientCollection() {
return patientCollection;
}
public void setPatientCollection(Collection<Patient> patientCollection) {
this.patientCollection = patientCollection;
}
}
Patient.java
package entity;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
#Entity
#Table(name = "patient")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Patient.findAll", query = "SELECT p FROM Patient p"),
#NamedQuery(name = "Patient.findById", query = "SELECT p FROM Patient p WHERE p.id = :id"),
#NamedQuery(name = "Patient.findByPatientcode", query = "SELECT p FROM Patient p WHERE p.patientcode = :patientcode"),
#NamedQuery(name = "Patient.findByHistory", query = "SELECT p FROM Patient p WHERE p.history = :history"),
#NamedQuery(name = "Patient.findByExtPatientCode", query = "SELECT p FROM Patient p WHERE p.extPatientCode = :extPatientCode")})
public class Patient implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 20)
#Column(name = "patientcode")
private String patientcode;
#Size(max = 255)
#Column(name = "history")
private String history;
#Size(max = 20)
#Column(name = "ExtPatientCode")
private String extPatientCode;
#JoinColumn(name = "personid", referencedColumnName = "id")
#ManyToOne(optional = false)
private Person personid;
public Patient() {
}
public Patient(Integer id) {
this.id = id;
}
public Patient(Integer id, String patientcode) {
this.id = id;
this.patientcode = patientcode;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getPatientcode() {
return patientcode;
}
public void setPatientcode(String patientcode) {
this.patientcode = patientcode;
}
public String getHistory() {
return history;
}
public void setHistory(String history) {
this.history = history;
}
public String getExtPatientCode() {
return extPatientCode;
}
public void setExtPatientCode(String extPatientCode) {
this.extPatientCode = extPatientCode;
}
public Person getPersonid() {
return personid;
}
public void setPersonid(Person personid) {
this.personid = personid;
}
}
AbstractFacade.java
package session;
import java.util.List;
import javax.persistence.EntityManager;
public abstract class AbstractFacade<T> {
private Class<T> entityClass;
public AbstractFacade(Class<T> entityClass) {
this.entityClass = entityClass;
}
protected abstract EntityManager getEntityManager();
public void create(T entity) {
getEntityManager().persist(entity);
}
public void edit(T entity) {
getEntityManager().merge(entity);
}
public void remove(T entity) {
getEntityManager().remove(getEntityManager().merge(entity));
}
public T find(Object id) {
return getEntityManager().find(entityClass, id);
}
public List<T> findAll() {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
return getEntityManager().createQuery(cq).getResultList();
}
public List<T> findRange(int[] range) {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
javax.persistence.Query q = getEntityManager().createQuery(cq);
q.setMaxResults(range[1] - range[0]);
q.setFirstResult(range[0]);
return q.getResultList();
}
}
PatientFacade.java
package session;
import entity.Patient;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
#Stateless
public class PatientFacade extends AbstractFacade<Patient> {
#PersistenceContext(unitName = "WebApplication4PU")
private EntityManager em;
#Override
protected EntityManager getEntityManager() {
return em;
}
public PatientFacade() {
super(Patient.class);
}
}
PersonFacade.java
package session;
import entity.Person;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
#Stateless
public class PersonFacade extends AbstractFacade<Person> {
#PersistenceContext(unitName = "WebApplication4PU")
private EntityManager em;
#Override
protected EntityManager getEntityManager() {
return em;
}
public PersonFacade() {
super(Person.class);
}
}
PersonController.java
package controllers;
import entity.Person;
import controllers.util.JsfUtil;
import controllers.util.PaginationHelper;
import session.PersonFacade;
import java.io.Serializable;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
#Named("personController")
#SessionScoped
public class PersonController implements Serializable {
private Person current;
private DataModel items = null;
#EJB
private session.PersonFacade ejbFacade;
private PaginationHelper pagination;
private int selectedItemIndex;
public PersonController() {
}
public Person getSelected() {
if (current == null) {
current = new Person();
selectedItemIndex = -1;
}
return current;
}
private PersonFacade getFacade() {
return ejbFacade;
}
public PaginationHelper getPagination() {
if (pagination == null) {
pagination = new PaginationHelper(10) {
#Override
public int getItemsCount() {
return getFacade().count();
}
#Override
public DataModel createPageDataModel() {
return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
}
};
}
return pagination;
}
public String prepareList() {
recreateModel();
return "List";
}
public String prepareView() {
current = (Person) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
return "View";
}
public String prepareCreate() {
current = new Person();
selectedItemIndex = -1;
return "Create";
}
public String create() {
try {
getFacade().create(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("PersonCreated"));
return prepareCreate();
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
return null;
}
}
public String prepareEdit() {
current = (Person) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
return "Edit";
}
public String update() {
try {
getFacade().edit(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("PersonUpdated"));
return "View";
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
return null;
}
}
public String destroy() {
current = (Person) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
performDestroy();
recreatePagination();
recreateModel();
return "List";
}
public String destroyAndView() {
performDestroy();
recreateModel();
updateCurrentItem();
if (selectedItemIndex >= 0) {
return "View";
} else {
// all items were removed - go back to list
recreateModel();
return "List";
}
}
private void performDestroy() {
try {
getFacade().remove(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("PersonDeleted"));
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
}
}
private void updateCurrentItem() {
int count = getFacade().count();
if (selectedItemIndex >= count) {
// selected index cannot be bigger than number of items:
selectedItemIndex = count - 1;
// go to previous page if last page disappeared:
if (pagination.getPageFirstItem() >= count) {
pagination.previousPage();
}
}
if (selectedItemIndex >= 0) {
current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0);
}
}
public DataModel getItems() {
if (items == null) {
items = getPagination().createPageDataModel();
}
return items;
}
private void recreateModel() {
items = null;
}
private void recreatePagination() {
pagination = null;
}
public String next() {
getPagination().nextPage();
recreateModel();
return "List";
}
public String previous() {
getPagination().previousPage();
recreateModel();
return "List";
}
public SelectItem[] getItemsAvailableSelectMany() {
return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
}
public SelectItem[] getItemsAvailableSelectOne() {
return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
}
public Person getPerson(java.lang.Integer id) {
return ejbFacade.find(id);
}
#FacesConverter(forClass = Person.class)
public static class PersonControllerConverter implements Converter {
#Override
public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
if (value == null || value.length() == 0) {
return null;
}
PersonController controller = (PersonController) facesContext.getApplication().getELResolver().
getValue(facesContext.getELContext(), null, "personController");
return controller.getPerson(getKey(value));
}
java.lang.Integer getKey(String value) {
java.lang.Integer key;
key = Integer.valueOf(value);
return key;
}
String getStringKey(java.lang.Integer value) {
StringBuilder sb = new StringBuilder();
sb.append(value);
return sb.toString();
}
}
}
PatientController.java
package controllers;
import entity.Patient;
import controllers.util.JsfUtil;
import controllers.util.PaginationHelper;
import session.PatientFacade;
import java.io.Serializable;
import java.util.ResourceBundle;
import javax.ejb.EJB;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
#Named("patientController")
#SessionScoped
public class PatientController implements Serializable {
private Patient current;
private DataModel items = null;
#EJB
private session.PatientFacade ejbFacade;
private PaginationHelper pagination;
private int selectedItemIndex;
public PatientController() {
}
public Patient getSelected() {
if (current == null) {
current = new Patient();
selectedItemIndex = -1;
}
return current;
}
private PatientFacade getFacade() {
return ejbFacade;
}
public PaginationHelper getPagination() {
if (pagination == null) {
pagination = new PaginationHelper(10) {
#Override
public int getItemsCount() {
return getFacade().count();
}
#Override
public DataModel createPageDataModel() {
return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
}
};
}
return pagination;
}
public String prepareList() {
recreateModel();
return "List";
}
public String prepareView() {
current = (Patient) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
return "View";
}
public String prepareCreate() {
current = new Patient();
selectedItemIndex = -1;
return "Create";
}
public String create() {
try {
getFacade().create(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("PatientCreated"));
return prepareCreate();
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
return null;
}
}
public String prepareEdit() {
current = (Patient) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
return "Edit";
}
public String update() {
try {
getFacade().edit(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("PatientUpdated"));
return "View";
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
return null;
}
}
public String destroy() {
current = (Patient) getItems().getRowData();
selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
performDestroy();
recreatePagination();
recreateModel();
return "List";
}
public String destroyAndView() {
performDestroy();
recreateModel();
updateCurrentItem();
if (selectedItemIndex >= 0) {
return "View";
} else {
// all items were removed - go back to list
recreateModel();
return "List";
}
}
private void performDestroy() {
try {
getFacade().remove(current);
JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/Bundle").getString("PatientDeleted"));
} catch (Exception e) {
JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/Bundle").getString("PersistenceErrorOccured"));
}
}
private void updateCurrentItem() {
int count = getFacade().count();
if (selectedItemIndex >= count) {
// selected index cannot be bigger than number of items:
selectedItemIndex = count - 1;
// go to previous page if last page disappeared:
if (pagination.getPageFirstItem() >= count) {
pagination.previousPage();
}
}
if (selectedItemIndex >= 0) {
current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0);
}
}
public DataModel getItems() {
if (items == null) {
items = getPagination().createPageDataModel();
}
return items;
}
private void recreateModel() {
items = null;
}
private void recreatePagination() {
pagination = null;
}
public String next() {
getPagination().nextPage();
recreateModel();
return "List";
}
public String previous() {
getPagination().previousPage();
recreateModel();
return "List";
}
public SelectItem[] getItemsAvailableSelectMany() {
return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
}
public SelectItem[] getItemsAvailableSelectOne() {
return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
}
public Patient getPatient(java.lang.Integer id) {
return ejbFacade.find(id);
}
#FacesConverter(forClass = Patient.class)
public static class PatientControllerConverter implements Converter {
#Override
public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
if (value == null || value.length() == 0) {
return null;
}
PatientController controller = (PatientController) facesContext.getApplication().getELResolver().
getValue(facesContext.getELContext(), null, "patientController");
return controller.getPatient(getKey(value));
}
java.lang.Integer getKey(String value) {
java.lang.Integer key;
key = Integer.valueOf(value);
return key;
}
String getStringKey(java.lang.Integer value) {
StringBuilder sb = new StringBuilder();
sb.append(value);
return sb.toString();
}
#Override
public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
if (object == null) {
return null;
}
if (object instanceof Patient) {
Patient o = (Patient) object;
return getStringKey(o.getId());
} else {
throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + Patient.class.getName());
}
}
}
}
Thanks in advance.
Fact: a single #Stateless EJB method call counts as a single full transaction.
Just make use of this fact. Create a new method in the #Stateless EJB which executes all necessary queries at once and then let your JSF backing bean call exactly that single method.
That's by the way exactly one of main reasons why EJBs exist: transparent transaction management. You seem to have missed this not unimportant fact while learning Java EE.

NoSuchMethodException on eclipselink

I'm developing a javaEE project using Glassfish and EclipseLink.
ALthough, when i run my app i get the following exceptions:
Exception [EclipseLink-60] (Eclipse Persistence Services - 2.0.1.v20100213-r6600): org.eclipse.persistence.exceptions.DescriptorException
Exception Description: The method [_persistence_setjuego_vh] or [_persistence_getjuego_vh] is not defined in the object [model.ConcursosJuego].
Internal Exception: java.lang.NoSuchMethodException: model.ConcursosJuego._persistence_getjuego_vh()
i have no clue why i am getting this exception becuase the Entity "Juegos" has that methods, this is the Entity Code:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package model;
import java.io.Serializable;
import java.math.BigInteger;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
/**
*
* #author user
*/
#Entity
#NamedQueries({
#NamedQuery(name = "Juego.findAll", query = "SELECT j FROM Juego j"),
#NamedQuery(name = "Juego.findById", query = "SELECT j FROM Juego j WHERE j.id = :id"),
#NamedQuery(name = "Juego.findByNombre", query = "SELECT j FROM Juego j WHERE j.nombre = :nombre"),
#NamedQuery(name = "Juego.findByUrl", query = "SELECT j FROM Juego j WHERE j.url = :url"),
#NamedQuery(name = "Juego.findByMultijugador", query = "SELECT j FROM Juego j WHERE j.multijugador = :multijugador"),
#NamedQuery(name = "Juego.findByTopejugadores", query = "SELECT j FROM Juego j WHERE j.topejugadores = :topejugadores"),
#NamedQuery(name = "Juego.findByEstado", query = "SELECT j FROM Juego j WHERE j.estado = :estado")})
public class Juego implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 10)
private String id;
#Size(max = 255)
private String nombre;
#Size(max = 1000)
private String url;
private BigInteger multijugador;
private BigInteger topejugadores;
#Size(max = 1)
private String estado;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "juego", fetch = FetchType.LAZY)
private List<Partida> partidaList;
#JoinColumn(name = "RANKING_ID", referencedColumnName = "ID")
#ManyToOne(optional = false, fetch = FetchType.LAZY)
private Ranking ranking;
#JoinColumn(name = "CATEGORIA_ID", referencedColumnName = "ID")
#ManyToOne(optional = false, fetch = FetchType.LAZY)
private Categoria categoria;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "juego", fetch = FetchType.LAZY)
private List<InteraccionUsuarioJuego> interaccionUsuarioJuegoList;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "juego", fetch = FetchType.LAZY)
private List<ConcursosJuego> concursosJuegoList;
public Juego() {
}
public Juego(String id) {
this.id = id;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombre) {
this.nombre = nombre;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public BigInteger getMultijugador() {
return multijugador;
}
public void setMultijugador(BigInteger multijugador) {
this.multijugador = multijugador;
}
public BigInteger getTopejugadores() {
return topejugadores;
}
public void setTopejugadores(BigInteger topejugadores) {
this.topejugadores = topejugadores;
}
public String getEstado() {
return estado;
}
public void setEstado(String estado) {
this.estado = estado;
}
public List<Partida> getPartidaList() {
return partidaList;
}
public void setPartidaList(List<Partida> partidaList) {
this.partidaList = partidaList;
}
public Categoria getCategoria() {
return categoria;
}
public void setCategoria(Categoria categoria) {
this.categoria = categoria;
}
public List<InteraccionUsuarioJuego> getInteraccionUsuarioJuegoList() {
return interaccionUsuarioJuegoList;
}
public void setInteraccionUsuarioJuegoList(List<InteraccionUsuarioJuego> interaccionUsuarioJuegoList) {
this.interaccionUsuarioJuegoList = interaccionUsuarioJuegoList;
}
public List<ConcursosJuego> getConcursosJuegoList() {
return concursosJuegoList;
}
public void setConcursosJuegoList(List<ConcursosJuego> concursosJuegoList) {
this.concursosJuegoList = concursosJuegoList;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Juego)) {
return false;
}
Juego other = (Juego) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "model.Juego[ id=" + id + " ]";
}
public Ranking getRanking() {
return ranking;
}
public void setRanking(Ranking ranking) {
this.ranking = ranking;
}
}
this is the application.xml
<?xml version="1.0" encoding="UTF-8"?>
<application xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:application="http://java.sun.com/xml/ns/javaee/application_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/application_6.xsd" id="Application_ID" version="6">
<display-name>p_ear</display-name>
<module>
<ejb>p.jar</ejb>
</module>
<module>
<web>
<web-uri>p_web.war</web-uri>
<context-root>p_web</context-root>
</web>
</module>
</application>
i have tried eclipse link persistance and methods in other entities and it does work.
(This is the first entity that have more than 1 relation)
thanks

Resources