Jackson multiple abstract Objet serialisation - java

I have a problem when i want deserialize the object "ObjectAbstract1". I have this error :
I tried several solutions but without success ... If someone has an idea? The problem is located on object ObjectAbstract2 but I do not see what jackson anotation to add
-- serializing --
{"object1Type":"INSTANCE_OBJECT1","autor":"John","objectAbstract2":{"nameProc":"Processus transfert","identifiant":null,"nomObject3":"Demande de transfert"},"state":"En cours","priority":null}
-- deserializing --
Exception in thread "main" com.fasterxml.jackson.databind.JsonMappingException: Can not construct instance of fr.test.jakson.ObjectAbstract2, problem: abstract types either need to be mapped to concrete types, have custom deserializer, or be instantiated with additional type information
at [Source: {"object1Type":"INSTANCE_OBJECT1","autor":"John","objectAbstract2":{"nameProc":"Processus transfert","identifiant":null,"nomObject3":"Demande de transfert"},"state":"En cours","priority":null}; line: 1, column: 49] (through reference chain: fr.test.jakson.Object1["objectAbstract2"])
at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:148)
at com.fasterxml.jackson.databind.DeserializationContext.instantiationException(DeserializationContext.java:892)
at com.fasterxml.jackson.databind.deser.AbstractDeserializer.deserialize(AbstractDeserializer.java:139)
at com.fasterxml.jackson.databind.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:520)
at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:95)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:258)
at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeOther(BeanDeserializer.java:161)
at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:136)
at com.fasterxml.jackson.databind.jsontype.impl.AsPropertyTypeDeserializer._deserializeTypedForId(AsPropertyTypeDeserializer.java:122)
at com.fasterxml.jackson.databind.jsontype.impl.AsPropertyTypeDeserializer.deserializeTypedFromObject(AsPropertyTypeDeserializer.java:93)
at com.fasterxml.jackson.databind.deser.AbstractDeserializer.deserializeWithType(AbstractDeserializer.java:131)
at com.fasterxml.jackson.databind.deser.impl.TypeWrappedDeserializer.deserialize(TypeWrappedDeserializer.java:42)
at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:3736)
at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2726)
at fr.test.jakson.MainTest.main(MainTest.java:33)
ObjectAbstract1 :
package fr.test.jakson;
import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonSubTypes.Type;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
#JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "object1Type")
#JsonSubTypes({ #Type(value = Object1.class, name = "INSTANCE_OBJECT1") })
public abstract class ObjectAbstract1 implements Serializable {
private static final long serialVersionUID = 1L;
private String autor;
private ObjectAbstract2 objectAbstract2;
public ObjectAbstract1() {
}
public String getAutor() {
return autor;
}
public void setAutor(String autor) {
this.autor = autor;
}
public ObjectAbstract2 getObjectAbstract2() {
return objectAbstract2;
}
public void setObjectAbstract2(ObjectAbstract2 objectAbstract2) {
this.objectAbstract2 = objectAbstract2;
}
}
Object1 :
package fr.test.jakson;
import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonTypeName;
#JsonTypeName("INSTANCE_OBJECT1")
public class Object1 extends ObjectAbstract1 implements Serializable {
private static final long serialVersionUID = 1L;
private String state;
private String priority;
public Object1() {
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getPriority() {
return priority;
}
public void setPriority(String priority) {
this.priority = priority;
}
}
ObjectAbstract2 :
package fr.test.jakson;
import java.io.Serializable;
public abstract class ObjectAbstract2 implements Serializable {
private static final long serialVersionUID = 1L;
private String nameProc;
public ObjectAbstract2() {
}
public String getNameProc() {
return nameProc;
}
public void setNameProc(String nameProc) {
this.nameProc = nameProc;
}
}
ObjectAbstract3 :
package fr.test.jakson;
import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonSubTypes.Type;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
#JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "objectAbstract3Type")
#JsonSubTypes({ #Type(value = Object3.class, name = "Object3"), #Type(value = Object2.class, name = "Object2") })
public abstract class ObjectAbstract3 extends ObjectAbstract2 implements Serializable {
private static final long serialVersionUID = 1L;
private String identifiant;
public ObjectAbstract3() {
}
public String getIdentifiant() {
return identifiant;
}
public void setIdentifiant(String identifiant) {
this.identifiant = identifiant;
}
}
Object2 :
package fr.test.jakson;
import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonTypeName;
#JsonTypeName("Object2")
public class Object2 extends ObjectAbstract3 implements Serializable {
private static final long serialVersionUID = 1L;
private String nomObject2;
public Object2() {
}
public String getNomObject2() {
return nomObject2;
}
public void setNomObject2(String nomObject2) {
this.nomObject2 = nomObject2;
}
}
Object 3 :
package fr.test.jakson;
import java.io.Serializable;
import com.fasterxml.jackson.annotation.JsonTypeName;
#JsonTypeName("Object3")
public class Object3 extends ObjectAbstract3 implements Serializable {
private static final long serialVersionUID = 1L;
private String nomObject3;
public Object3() {
}
public String getNomObject3() {
return nomObject3;
}
public void setNomObject3(String nomObject3) {
this.nomObject3 = nomObject3;
}
}
Main Class test :
package fr.test.jakson;
import java.io.IOException;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
public class MainTest {
public static void main(String[] args) throws JsonParseException, JsonMappingException, IOException {
Object1 object1 = new Object1();
object1.setAutor("John");
object1.setState("En cours");
Object3 object3 = new Object3();
object3.setNomObject3("Demande de transfert");
ObjectAbstract2 objectAbstract2 = (ObjectAbstract2) object3;
objectAbstract2.setNameProc("Processus transfert");
ObjectAbstract1 objectAbstract1 = (ObjectAbstract1) object1;
objectAbstract1.setObjectAbstract2(objectAbstract2);
System.out.println("-- serializing --");
ObjectMapper om = new ObjectMapper();
String s = om.writeValueAsString(objectAbstract1);
System.out.println(s);
System.out.println("-- deserializing --");
ObjectAbstract1 instanceTacheDeserializing;
ObjectMapper om1 = new ObjectMapper();
String jsonTest = "{\"object1Type\":\"INSTANCE_OBJECT1\",\"autor\":\"John\",\"objectAbstract2\":{\"nameProc\":\"Processus transfert\",\"identifiant\":null,\"nomObject3\":\"Demande de transfert\"},\"state\":\"En cours\",\"priority\":null}";
instanceTacheDeserializing = om1.readValue(jsonTest, ObjectAbstract1.class);
}
}

ObjectAbstract2 cannot be an Abstract class. Deserializer requires concrete class to convert into java object. Change ObjectAbstract2 class like below
package fr.test.jakson;
import java.io.Serializable;
public class ObjectAbstract2 implements Serializable {
private static final long serialVersionUID = 1L;
private String nameProc;
public ObjectAbstract2() {
}
public String getNameProc() {
return nameProc;
}
public void setNameProc(String nameProc) {
this.nameProc = nameProc;
}
}

Related

Null List returning for Multiple Occurrence sections in JAXB

Hi i'm new to JAXB Conversions.
I'm Unmarshalling an xml into java objects. For single occurrence sections there is no issue, but for multiple occurrence not able to map properly. Each time I'm getting null list for multiple occurrence section.
Please suggest me any useful url's or suggest me changes need to be done.
XML ::
<?xml version="1.0" encoding="UTF-8"?>
<designTheory>
<Administartor>
<circuitId>67565675476</circuitId>
<processId>567855</processId>
<version>01</version>
<circuitReferenceValue>ciruit-0001</circuitReferenceValue>
<property>cal-circuit</property>
</Administartor>
<designSec>
<priloc>priloc</priloc>
<secloc>secloc</secloc>
<remarks>remarks field</remarks>
</designSec>
<designNotes>
<notesNumber>1</notesNumber>
<notes>designNotes 1</notes>
</designNotes>
<designNotes>
<notesNumber>2</notesNumber>
<notes>designNotes 2</notes>
</designNotes>
<designNotes>
<notesNumber>3</notesNumber>
<notes>designNotes 3</notes>
</designNotes>
<designNotes>
<notesNumber>4</notesNumber>
<notes>designNotes 4</notes>
</designNotes>
</designTheory>
Code Snippets are as below :
DesignTheory.java
package org.manjunath.jaxbconversions.beans;
import java.util.List;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlElementWrapper;
import javax.xml.bind.annotation.XmlRootElement;
#XmlAccessorType(XmlAccessType.FIELD)
#XmlRootElement(name = "designTheory")
public class DesignTheory {
#XmlElement(name = "Administartor", required = true)
private Administartor admin;
#XmlElement(name = "designSec", required = true)
private DesignSec designSec;
#XmlElementWrapper
#XmlElementRef(name = "designNotes")
private List<JAXBElement<DesignNotes>> designNotesList;
public void setAdministartor(Administartor admin){
this.admin = admin;
}
public Administartor getAdministartor() {
return admin;
}
public DesignSec getDesignSec() {
return designSec;
}
public void setDesignSec(DesignSec designSec) {
this.designSec = designSec;
}
public List<JAXBElement<DesignNotes>> getDlrnotes() {
return designNotesList;
}
public void setDlrnotes(List<JAXBElement<DesignNotes>> designNotesList) {
this.designNotesList = designNotesList;
}
}
Administartor.java
package org.manjunath.jaxbconversions.beans;
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 = "Administartor")
public class Administartor {
#XmlElement(name = "circuitId")
private String circuitId;
#XmlElement(name = "processId")
private String processId;
#XmlElement(name = "version")
private String version;
#XmlElement(name = "circuitReferenceValue")
private String circuitReferenceValue;
#XmlElement(name = "property")
private String property;
public String getcircuitId() {
return circuitId;
}
public void setcircuitId(String circuitId) {
this.circuitId = circuitId;
}
public String getprocessId() {
return processId;
}
public void setprocessId(String processId) {
this.processId = processId;
}
public String getVer() {
return version;
}
public void setVer(String version) {
this.version = version;
}
public String getcircuitReferenceValue() {
return circuitReferenceValue;
}
public void setcircuitReferenceValue(String circuitReferenceValue) {
this.circuitReferenceValue = circuitReferenceValue;
}
public String getproperty() {
return property;
}
public void setproperty(String property) {
this.property = property;
}
}
DesignSec.java
package org.manjunath.jaxbconversions.beans;
import java.util.ArrayList;
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.XmlRootElement;
#XmlAccessorType(XmlAccessType.FIELD)
#XmlRootElement(name = "designSec")
public class DesignSec {
#XmlElement (name = "priloc")
private String priloc;
#XmlElement (name = "secloc")
private String secloc;
#XmlElement (name = "remarks")
private String remarks;
public String getpriloc() {
return priloc;
}
public void setpriloc(String priloc) {
this.priloc = priloc;
}
public String getSecloc() {
return secloc;
}
public void setSecloc(String secloc) {
this.secloc = secloc;
}
public String getremarks() {
return remarks;
}
public void setEcspc(String remarks) {
this.remarks = remarks;
}
}
DesignNotes.java
package org.manjunath.jaxbconversions.beans;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
#XmlRootElement(name = "designNotes")
#XmlAccessorType(XmlAccessType.FIELD)
public class DesignNotes {
#XmlElement (name = "notesNumber")
private String notesNumber;
#XmlElement (name = "notes")
private String notes;
public String getnotesNumber() {
return notesNumber;
}
public void setnotesNumber(String notesNumber) {
this.notesNumber = notesNumber;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
}
And I found somewhere the #XmlRegistry and #XmlElementDecl will solve my problem.
But I'm not so good with these annotations, but I tried by using ObjectFactory.java class. No use of this class
ObjectFactory.java
package org.manjunath.jaxbconversions.factory;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlElementDecl;
import javax.xml.bind.annotation.XmlRegistry;
import javax.xml.namespace.QName;
import org.manjunath.jaxbconversions.beans.DesignNotes;
#XmlRegistry
public class ObjectFactory {
private final static QName _DesignNotes_QNAME = new QName("designNotes");
public ObjectFactory(){
}
#XmlElementDecl(name="designNotes")
public JAXBElement<DesignNotes> createDesignNotes(DesignNotes value) {
return new JAXBElement<DesignNotes>(_DesignNotes_QNAME, DesignNotes.class, value);
}
}
Please suggest me to solve this problem
In your class DesignTheory the definition
#XmlElementWrapper
#XmlElementRef(name = "designNotes")
private List<JAXBElement<DesignNotes>> designNotesList;
is wrong.
In your XML you have
<designNotes>
...
</desinNotes>
<designNotes>
...
</designNotes>
...
But you do not have an additional wrapper around these <designNotes> like this
<designNotesList>
<designNotes>
...
</desinNotes>
<designNotes>
...
</designNotes>
...
<designNotesList>
That's why you need to remove the #XmlElementWrapper annotation.
And you should change its type from List<JAXBElement<DesignNotes>>
to List<DesignNotes>. So you end up with
#XmlElementRef(name = "designNotes")
private List<DesignNotes> designNotesList;
Also change the associated getter and setter from List<JAXBElement<DesignNotes>>
to List<DesignNotes>.
Then you don't need the ObjectFactory anymore and can remove it completely.
I verified the corrected classes with your XML and the following test-code
#Test
public void testUnmarshall() throws Exception {
JAXBContext context = JAXBContext.newInstance(DesignTheory.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
File file = new File("design-theory.xml");
DesignTheory designTheory = (DesignTheory) unmarshaller.unmarshal(file);
Assert.assertNotNull(designTheory.getDlrnotes());
Assert.assertEquals(4, designTheory.getDlrnotes().size());
}
The unmarshalled designTheory correctly has a non-null List<DesignNotes> with 4 elements.

java.util.LinkedHashMap cannot be cast to com.common.pojo.myDataDetails

My java class is throwing some error. In my class i am using this to get my data.
((myDataDetails) Names.get(0)).InputParamNames().add("SomeValue");
But it is throwing error
Here is my Pohjo Class.
package common.pojo;
import java.util.Date;
import java.util.List;
public class myDataDetails
{
private String myID;
private List<String> InputParamNames;
private List InputParamData;
public String getmyID() {
return this.myID;
}
public void setmyID(String myID) {
this.myID = myID;
}
public List<String> getInputParamNames() {
return this.InputParamNames;
}
public void setInputParamNames(List<String> InputParamNames) {
this.InputParamNames = InputParamNames;
}
public List getInputParamData() {
return this.InputParamData;
}
public void setInputParamData(List InputParamData) {
this.InputParamData = InputParamData;
}
}
What should I need to change in pojo to avoid this exception.
Your class 'myDataDetails' needs to extend from LinkedHashMap in order to cast it.
What you have right now is a regular POJO class that is not an instance of LinkedHashMap, so you can't cast it as such.
EDIT: It should look like this
package common.pojo;
import java.util.Date;
import java.util.List;
import java.util.LinkedHashMap;
public class myDataDetails extends LinkedHashMap<Object, Object>
{
private String myID;
private List<String> InputParamNames;
private List InputParamData;
public String getmyID() {
return this.myID;
}
public void setmyID(String myID) {
this.myID = myID;
}
public List<String> getInputParamNames() {
return this.InputParamNames;
}
public void setInputParamNames(List<String> InputParamNames) {
this.InputParamNames = InputParamNames;
}
public List getInputParamData() {
return this.InputParamData;
}
public void setInputParamData(List InputParamData) {
this.InputParamData = InputParamData;
}
}

How to create encoder for custom Java objects?

I am using following class to create bean from Spark Encoders
Class OuterClass implements Serializable {
int id;
ArrayList<InnerClass> listofInner;
public int getId() {
return id;
}
public void setId (int num) {
this.id = num;
}
public ArrayList<InnerClass> getListofInner() {
return listofInner;
}
public void setListofInner(ArrayList<InnerClass> list) {
this.listofInner = list;
}
}
public static class InnerClass implements Serializable {
String streetno;
public void setStreetno(String streetno) {
this.streetno= streetno;
}
public String getStreetno() {
return streetno;
}
}
Encoder<OuterClass> outerClassEncoder = Encoders.bean(OuterClass.class);
Dataset<OuterClass> ds = spark.createDataset(Collections.singeltonList(outerclassList), outerClassEncoder)
And I am getting the following error
Exception in thread "main" java.lang.UnsupportedOperationException: Cannot infer type for class OuterClass$InnerClass because it is not bean-compliant
How can I implement this type of use case for Spark in Java? This worked fine if I remove the inner class. But I need to have an inner class for my use case.
Your JavaBean class should have a public no-argument constructor, getter and setters and it should implement Serializable interface. Spark SQL works on valid JavaBean class.
EDIT : Adding working sample with inner class
OuterInnerDF.java
package com.abaghel.examples;
import java.util.ArrayList;
import java.util.Collections;
import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Encoder;
import org.apache.spark.sql.Encoders;
import org.apache.spark.sql.SparkSession;
import com.abaghel.examples.OuterClass.InnerClass;
public class OuterInnerDF {
public static void main(String[] args) {
SparkSession spark = SparkSession
.builder()
.appName("OuterInnerDF")
.config("spark.sql.warehouse.dir", "/file:C:/temp")
.master("local[2]")
.getOrCreate();
System.out.println("====> Create DataFrame");
//Outer
OuterClass us = new OuterClass();
us.setId(111);
//Inner
OuterClass.InnerClass ic = new OuterClass.InnerClass();
ic.setStreetno("My Street");
//list
ArrayList<InnerClass> ar = new ArrayList<InnerClass>();
ar.add(ic);
us.setListofInner(ar);
//DF
Encoder<OuterClass> outerClassEncoder = Encoders.bean(OuterClass.class);
Dataset<OuterClass> ds = spark.createDataset(Collections.singletonList(us), outerClassEncoder);
ds.show();
}
}
OuterClass.java
package com.abaghel.examples;
import java.io.Serializable;
import java.util.ArrayList;
public class OuterClass implements Serializable {
int id;
ArrayList<InnerClass> listofInner;
public int getId() {
return id;
}
public void setId(int num) {
this.id = num;
}
public ArrayList<InnerClass> getListofInner() {
return listofInner;
}
public void setListofInner(ArrayList<InnerClass> list) {
this.listofInner = list;
}
public static class InnerClass implements Serializable {
String streetno;
public void setStreetno(String streetno) {
this.streetno = streetno;
}
public String getStreetno() {
return streetno;
}
}
}
Console Output
====> Create DataFrame
16/08/28 18:02:55 INFO CodeGenerator: Code generated in 32.516369 ms
+---+-------------+
| id| listofInner|
+---+-------------+
|111|[[My Street]]|
+---+-------------+

Table is not mapped ejb3.0

Hello i use EJB 3 and i'm trying to get a simple list from DB but i find this message" travauxdereseauurbain is not mapped [select Tr from travauxdereseauurbain Tr]" and i don't really get what does it means
Here is the entity
package com.pfe.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.xml.soap.Text;
#Entity
#Table(name="travauxdereseauurbain")
public class Traveauxdereseauurbain implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name="idtru")
private int idtru;
#Column(name = "article")
private String article;
#Column (name="designationtraveau")
private String designationtraveau;
#Column(name="unite")
private String unite;
#Column(name="prixHTVA")
private float prixHTVA;
#Column(name="prixTTC")
private float prixTTC;
#Column (name="qtt")
private float qtt;
#Column(name="montantHTVA")
private float montantHTVA;
#Column(name="montantTTC")
private float montantTTC;
public int getIdtru() {
return idtru;
}
public void setIdtru(int idtru) {
this.idtru = idtru;
}
public String getArticle() {
return article;
}
public void setArticle(String article) {
this.article = article;
}
public String getDesignationtraveau() {
return designationtraveau;
}
public void setDesignationtraveau(String designationtraveau) {
this.designationtraveau = designationtraveau;
}
public String getUnite() {
return unite;
}
public void setUnite(String unite) {
this.unite = unite;
}
public float getPrixHTVA() {
return prixHTVA;
}
public void setPrixHTVA(float prixHTVA) {
this.prixHTVA = prixHTVA;
}
public float getPrixTTC() {
return prixTTC;
}
public void setPrixTTC(float prixTTC) {
this.prixTTC = prixTTC;
}
public float getQtt() {
return qtt;
}
public void setQtt(float qtt) {
this.qtt = qtt;
}
public float getMontantHTVA() {
return montantHTVA;
}
public void setMontantHTVA(float montantHTVA) {
this.montantHTVA = montantHTVA;
}
public float getMontantTTC() {
return montantTTC;
}
public void setMontantTTC(float montantTTC) {
this.montantTTC = montantTTC;
}
public Traveauxdereseauurbain(int idtru, String article,
String designationtraveau, String unite, float prixHTVA, float prixTTC,
float qtt, float montantHTVA, float montantTTC) {
super();
this.idtru = idtru;
this.article = article;
this.designationtraveau = designationtraveau;
this.unite = unite;
this.prixHTVA = prixHTVA;
this.prixTTC = prixTTC;
this.qtt = qtt;
this.montantHTVA = montantHTVA;
this.montantTTC = montantTTC;
}
public Traveauxdereseauurbain() {
super();
}
}
`
and the DAO class
package com.pfe.data;
import java.util.ArrayList;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import com.pfe.controller.travauxdereseauurbainBean;
import com.pfe.model.Traveauxdereseauurbain;
import com.pfe.model.Traveauxdereseauurbain;
#Stateless
public class TravauxdereseauurbainDAO {
#PersistenceContext
private EntityManager em;
public void AddTravauxdereseauurbainDAO (Traveauxdereseauurbain Trurbain)
{
em.persist(Trurbain);
}
public Traveauxdereseauurbain affichernimpr()
{
Query q =em.createNamedQuery("select tr from travauxdereseauurbain tr");
return (Traveauxdereseauurbain) q.getResultList().get(0);
}
}
`
and i got this error:
Caused by: javax.ejb.EJBException:
java.lang.IllegalArgumentException:
org.hibernate.hql.internal.ast.QuerySyntaxException:
travauxdereseauurbain is not mapped [select Tr from
travauxdereseauurbain Tr]
use createQuery instead of createNamedQuery..
There is a difference between those two..
A named query must be defined on the entity before being referenced by an entity managers. This might explain it in more details: http://www.objectdb.com/java/jpa/query/named

Java/JAXB: Unmarshall XML attributes to specific Java object attributes

There's ugly XML file that has to be unmarshalled:
<?xml version="1.0" ?>
<configuration>
<section name="default_options">
<value name="default_port">8081</value>
<value name="log_level">WARNING</value>
</section>
<section name="custom_options">
<value name="memory">64M</value>
<value name="compatibility">yes</value>
</section>
</configuration>
Resulting Java Objects should be:
public class DefaultOptions {
private int defaultPort;
private String logLevel;
// etc...
}
public class CustomOptions {
private String memory;
private String compatibility;
// etc...
}
This question's answer is very close but I can't figure out the final solution.
How about?
Introduce a common super class called Options:
import javax.xml.bind.annotation.XmlAttribute;
public abstract class Options {
private String name;
#XmlAttribute
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Then on your class with the list of options (Configuration in this example), specify an #XmlJavaTypeAdapter on that property:
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
#XmlRootElement
public class Configuration {
private List<Options> section = new ArrayList<Options>();
#XmlJavaTypeAdapter(OptionsAdapter.class)
public List<Options> getSection() {
return section;
}
public void setSection(List<Options> section) {
this.section = section;
}
}
The XmlAdapter will look something like this:
import javax.xml.bind.annotation.adapters.XmlAdapter;
public class OptionsAdapter extends XmlAdapter<AdaptedOptions, Options> {
#Override
public Options unmarshal(AdaptedOptions v) throws Exception {
if("default_options".equals(v.name)) {
DefaultOptions options = new DefaultOptions();
options.setName(v.getName());
options.setDefaultPort(Integer.valueOf(v.map.get("default_port")));
options.setLogLevel(v.map.get("log_level"));
return options;
} else {
CustomOptions options = new CustomOptions();
options.setName(v.getName());
options.setCompatibility(v.map.get("compatibility"));
options.setMemory(v.map.get("memory"));
return options;
}
}
#Override
public AdaptedOptions marshal(Options v) throws Exception {
AdaptedOptions adaptedOptions = new AdaptedOptions();
adaptedOptions.setName(v.getName());
if(DefaultOptions.class == v.getClass()) {
DefaultOptions options = (DefaultOptions) v;
adaptedOptions.map.put("default_port", String.valueOf(options.getDefaultPort()));
adaptedOptions.map.put("log_level", options.getLogLevel());
} else {
CustomOptions options = (CustomOptions) v;
adaptedOptions.map.put("compatibility", options.getCompatibility());
adaptedOptions.map.put("memory", options.getMemory());
}
return adaptedOptions;
}
}
AdaptedOptions looks like:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlValue;
public class AdaptedOptions extends Options {
#XmlAttribute String name;
#XmlElement List<Value> value = new ArrayList<Value>();
Map<String, String> map = new HashMap<String, String>();
public void beforeMarshal(Marshaller marshaller) {
for(Entry<String, String> entry : map.entrySet()) {
Value aValue = new Value();
aValue.name = entry.getKey();
aValue.value = entry.getValue();
value.add(aValue);
}
}
public void afterUnmarshal(Unmarshaller unmarshaller, Object parent) {
for(Value aValue : value) {
map.put(aValue.name, aValue.value);
}
}
private static class Value {
#XmlAttribute String name;
#XmlValue String value;
}
}
You may create a separate classes to represent structure of your XML:
public class Section {
#XmlAttribute
public String name;
#XmlElement(name = "value")
public List<Value> values;
}
public class Value {
#XmlAttribute
public String name;
#XmlValue
public String value;
}
and then use an XmlAdapter to perform conversion:
public class OptionsAdapter extends XmlAdapter<Section, Options> {
public Options unmarshal(Section s) {
if ("default_options".equals(s.name)) {
...
} else if (...) {
...
}
...
}
...
}
#XmlElement
public class Configuration {
#XmlElement(name = "section")
#XmlJavaTypeAdapter(OptionsAdapter.class)
public List<Options> options;
}
public class DefaultOptions extends Options { ... }
public class CustomOptions extends Options { ... }

Categories