Why this class not serializable? - java

I have error:
com.google.gwt.user.client.rpc.SerializationException: Type 'ru.xxx.empeditor.client.Dept$$EnhancerByCGLIB$$2f6af516' was not included in the set of types which can be serialized by this SerializationPolicy or its Class object could not be loaded. For security purposes, this type will not be serialized.: instance = ru.xxx.empeditor.client.Dept#e53d4e
Why this class not serializable?
package ru.xxx.empeditor.client;
import java.util.HashSet;
import java.util.Set;
import com.google.gwt.user.client.rpc.IsSerializable;
/**
* Dept generated by hbm2java
*/
public class Dept implements IsSerializable {
private byte deptno;
private String dname;
private String loc;
private Set<Emp> emps = new HashSet<Emp>(0);
public Dept() {
}
public Dept(byte deptno) {
this.deptno = deptno;
}
public Dept(byte deptno, String dname, String loc, Set<Emp> emps) {
this.deptno = deptno;
this.dname = dname;
this.loc = loc;
this.emps = emps;
}
public byte getDeptno() {
return this.deptno;
}
public void setDeptno(byte deptno) {
this.deptno = deptno;
}
public String getDname() {
return this.dname;
}
public void setDname(String dname) {
this.dname = dname;
}
public String getLoc() {
return this.loc;
}
public void setLoc(String loc) {
this.loc = loc;
}
public Set<Emp> getEmps() {
return this.emps;
}
public void setEmps(Set<Emp> emps) {
this.emps = emps;
}
}

Check if the class Emp is serialiable.
Another potential issue (since you are using Hibernate - noticed the auto-generated comment) could be because of Proxies that modify your bean's byte code, as a result of which GWT fails to serialize it. As mentioned here - http://code.google.com/webtoolkit/articles/using_gwt_with_hibernate.html

Related

cannot fetch the exact dto returned from ejb to liferay controller

I am doing a liferay project which use ejb at back end. so my ejb method looks like this:-
#Override
public List<RmisPaymentDetailsDto> getEpaymentDetails(String ebpCode) {
Query q = entityManager.createQuery("select s from EpaymentBo s where s.ebpCode=:ebpcode")
.setParameter("ebpcode",ebpCode);
#SuppressWarnings("unchecked")
List<ProductBo> list = q.getResultList();
Iterator<ProductBo> i = list.iterator();
List<RmisPaymentDetailsDto> rList = new ArrayList<RmisPaymentDetailsDto>();
while(i.hasNext()){
EpaymentBo ep =(EpaymentBo) i.next();
RmisPaymentDetailsDto dto = new RmisPaymentDetailsDto();
dto.setAdvertisementcode(ep.getAdvertisementcode());
dto.setAmount(ep.getAmount());
dto.setStudentmasterid(ep.getStudentmasterid());
dto.setEbpgendate(ep.getEbp_gen_date());
dto.setEbpcode(ep.getEbpCode());
dto.setPaymentstatus(ep.getPaymentstatus());
dto.setCandidatenameinnepali(ep.getCandidatenameinnepali());
rList.add(dto);
}
return rList;
}
the above method successfully fetches data from database and sets it to my RmisPaymentDetailsDto.
like this:-
now i am calling same method from my liferay controlller.
PreExaminationRemote preRef = (PreExaminationRemote) jndiContext
.lookup("PreExamination/remote");
List<RmisPaymentDetailsDto> rDto = preRef.getEpaymentDetails(ebpCode);
I am wondering how my one property(candidatenameinnepali) is lost as i return same dto from my ejb.
My dto looks like this:-
public class RmisPaymentDetailsDto implements Serializable {
private static final long serialVersionUID = 1L;
private String advertisementcode;
private String ebpcode;
private String amount;
private String studentmasterid;
private Date ebpgendate;
private String paymentstatus;
private String candidatenameinnepali;
public String getCandidatenameinnepali() {
return candidatenameinnepali;
}
public void setCandidatenameinnepali(String candidatenameinnepali) {
this.candidatenameinnepali = candidatenameinnepali;
}
public String getAdvertisementcode() {
return advertisementcode;
}
public void setAdvertisementcode(String advertisementcode) {
this.advertisementcode = advertisementcode;
}
public String getEbpcode() {
return ebpcode;
}
public void setEbpcode(String ebpcode) {
this.ebpcode = ebpcode;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
public String getStudentmasterid() {
return studentmasterid;
}
public void setStudentmasterid(String studentmasterid) {
this.studentmasterid = studentmasterid;
}
public Date getEbpgendate() {
return ebpgendate;
}
public void setEbpgendate(Date ebpgendate) {
this.ebpgendate = ebpgendate;
}
public String getPaymentstatus() {
return paymentstatus;
}
public void setPaymentstatus(String paymentstatus) {
this.paymentstatus = paymentstatus;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
}

Access to class attributes' values using Java Annotations

I am working with a java example using annotations, I created a simple POJO (java bean) using annotations to its attributes. I want to have the ability to create new objects of this type and retrieve the values of its attributes using the annotations created.
My POJO :
import java.io.Serializable;
import annotations.BusinessObject;
import annotations.BusinessObjectAttribute;
import annotations.BusinessObjectName;
import annotations.BusinessObjectPolicy;
import annotations.BusinessObjectRevision;
import annotations.BusinessObjectVault;
#BusinessObject
public class IndusTask implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
// Mandatory to create new object !
#BusinessObjectName
private String taskName;
#BusinessObjectRevision
private String taskRevision;
#BusinessObjectVault
private String vault;
// Mandatory to invoke iTask.create(context, policy) in Database
#BusinessObjectPolicy
private String policy;
//Specific attributes
#BusinessObjectAttribute
private String taskDescription;
#BusinessObjectAttribute
private String creationDate;
#BusinessObjectAttribute
private Integer weight;
public IndusTask() {
}
public IndusTask(String taskName, String taskRevision, String vault, String policy, String taskDescription,
String creationDate, Integer weight) {
super();
this.taskName = taskName;
this.taskRevision = taskRevision;
this.vault = vault;
this.policy = policy;
this.taskDescription = taskDescription;
this.creationDate = creationDate;
this.weight = weight;
}
public String getTaskName() {
return taskName;
}
public void setTaskName(String taskName) {
this.taskName = taskName;
}
public String getTaskRevision() {
return taskRevision;
}
public void setTaskRevision(String taskRevision) {
this.taskRevision = taskRevision;
}
public String getVault() {
return vault;
}
public void setVault(String vault) {
this.vault = vault;
}
public String getTaskDescription() {
return taskDescription;
}
public void setTaskDescription(String taskDescription) {
this.taskDescription = taskDescription;
}
public String getCreationDate() {
return this.creationDate;
}
public void setCreationDate(String creationDate) {
this.creationDate = creationDate;
}
public Integer getWeight() {
return weight;
}
public void setWeight(Integer weight) {
this.weight = weight;
}
public String getPolicy() {
return policy;
}
public void setPolicy(String policy) {
this.policy = policy;
}
}
Example of attributes' declaration:
*Business Object Type declaration
package annotations;
import java.lang.annotation.*;
//#Target(ElementType.TYPE)
#Retention(RetentionPolicy.RUNTIME)
public #interface BusinessObject {
}
*Business Object Name Attribute:
package annotations;
import java.lang.annotation.*;
//#Target(ElementType.FIELD)
#Retention(RetentionPolicy.RUNTIME)
public #interface BusinessObjectName {
}
I Created a main to test if all the annotations are detected:
public class MainImpl {
public static void main(String[] args) {
// TODO Auto-generated method stub
IndusTask myTask = new IndusTask("mytstTask", "001", "eService Production", "TstTask Process",
"myTstTask Description", "2018/02/16#15:30:10:GMT", 200);
System.out.println(myTask.getClass().getAnnotations().length);
}
}
Output is displaying 1 ! so only the first annotation is detected !
I was told also that the object attributes values can be accessed using these annotation (something similar to) :
object.getClass().getAnnotations()
How can i do ?
You need to iterate through the fields, get their annotations and set the value wherever the annotation matches (it can match multiple fields):
#Retention(RetentionPolicy.RUNTIME)
public #interface Field1 {}
#Retention(RetentionPolicy.RUNTIME)
public #interface Field2 {}
public static class UnderTest {
#Field1
private String field1;
#Field2
private int field2;
public UnderTest(String field1, int field2) {
this.field1 = field1;
this.field2 = field2;
}
#Override
public String toString() {
return field1 + "=" + field2;
}
}
public static void setter(Object obj, Class<? extends Annotation> fieldAnnotation, Object fieldValue) throws IllegalAccessException {
for (Field field: obj.getClass().getDeclaredFields()) {
for (Annotation annot: field.getDeclaredAnnotations()) {
if (annot.annotationType().isAssignableFrom(fieldAnnotation)) {
if (!field.isAccessible()) {
field.setAccessible(true);
}
field.set(obj, fieldValue);
}
}
}
}
public static void main(String[] argv) throws IllegalAccessException {
UnderTest underTest = new UnderTest("A", 1);
System.out.println(underTest);
setter(underTest, Field1.class, "B");
setter(underTest, Field2.class, 2);
System.out.println(underTest);
}
Running this prints
A=1
B=2
Sounds like you're after the annotations on the fields too?
E.g. for the first private field:
myTask.getClass().getDeclaredFields()[0].getAnnotations()
Note depending how you're accessing a private field, you will sometimes also need to first ensure it is accessible:
...getDeclaredFields()[0].setAccessible(true);
[edit]
The values are reachable too from the fields. A basic worked example:
for (Field f : myTask.getClass().getDeclaredFields()) {
f.setAccessible(true);
System.out.println(f.getName() + "=" + f.get(myTask));
System.out.println(" annotations=" + java.util.Arrays.toString(f.getAnnotations()));
}

Jpa annotated custom user type error property mapping has wrong number of columns

I recently mapped a field of a class with a custom hibernate UserType.
this is my custom user type
package service.dao.hibernate;
import java.io.IOException;
import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Properties;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.internal.util.ReflectHelper;
import org.hibernate.usertype.ParameterizedType;
import org.hibernate.usertype.UserType;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.type.SimpleType;
import com.google.common.base.Objects;
public abstract class JSONUserType implements UserType { //ParameterizedType, Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private static final ObjectMapper Mapper;
private static final String CLASS_TYPE = "classType";
private static final String TYPE = "type";
private static final int[] SQL_TYPES = new int[] { Types.LONGVARCHAR,
Types.CLOB, Types.BLOB };
private Class classType;
private int sqlType = Types.LONGVARCHAR; // before any guessing
static {
Mapper = new ObjectMapper();
Mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
}
#Override
public Object assemble(Serializable cached, Object owner)
throws HibernateException {
return this.deepCopy(cached);
}
#Override
public Object deepCopy(Object value) throws HibernateException {
Object copy = null;
if (value != null) {
try {
return Mapper.readValue(Mapper.writeValueAsString(value),
this.classType);
} catch (IOException e) {
throw new HibernateException("unable to deep copy object", e);
}
}
return copy;
}
#Override
public Serializable disassemble(Object value) throws HibernateException {
try {
return Mapper.writeValueAsString(value);
} catch (JsonProcessingException e) {
throw new HibernateException("unable to disassemble object", e);
}
}
#Override
public boolean equals(Object x, Object y) throws HibernateException {
if (x == y) {
return true;
} else if (x == null || y == null) {
return false;
} else {
return x.equals(y);
}
}
#Override
public int hashCode(Object x) throws HibernateException {
return null == x ? 0 : x.hashCode();
}
#Override
public boolean isMutable() {
return true;
}
#Override
public Object nullSafeGet(ResultSet rs, String[] names,
SessionImplementor session, Object owner)
throws HibernateException, SQLException {
Object obj = null;
if (!rs.wasNull()) {
if (this.sqlType == Types.CLOB || this.sqlType == Types.BLOB) {
byte[] bytes = rs.getBytes(names[0]);
if (bytes != null) {
try {
obj = Mapper.readValue(bytes, createJavaType(Mapper));
} catch (IOException e) {
throw new HibernateException(
"unable to read object from result set", e);
}
}
} else {
try {
String content = rs.getString(names[0]);
if (content != null) {
obj = Mapper.readValue(content, createJavaType(Mapper));
}
} catch (IOException e) {
throw new HibernateException(
"unable to read object from result set", e);
}
}
}
return obj;
}
#Override
public void nullSafeSet(PreparedStatement st, Object value, int index,
SessionImplementor session) throws HibernateException, SQLException {
if (value == null) {
st.setNull(index, this.sqlType);
} else {
if (this.sqlType == Types.CLOB || this.sqlType == Types.BLOB) {
try {
st.setBytes(index, Mapper.writeValueAsBytes(value));
} catch (JsonProcessingException e) {
throw new HibernateException(
"unable to set object to result set", e);
}
} else {
try {
st.setString(index, Mapper.writeValueAsString(value));
} catch (JsonProcessingException e) {
throw new HibernateException(
"unable to set object to result set", e);
}
}
}
}
#Override
public Object replace(Object original, Object target, Object owner)
throws HibernateException {
return this.deepCopy(original);
}
// #Override
// public Class returnedClass() {
// return this.classType;
// }
#Override
public int[] sqlTypes() {
return SQL_TYPES;
}
// #Override
// public void setParameterValues(Properties params) {
// String classTypeName = params.getProperty(CLASS_TYPE);
// try {
// this.classType = ReflectHelper.classForName(classTypeName,
// this.getClass());
// } catch (ClassNotFoundException cnfe) {
// throw new HibernateException("classType not found", cnfe);
// }
// String type = params.getProperty(TYPE);
// if (type != null) {
// this.sqlType = Integer.decode(type).intValue();
// }
// }
/**
* By default we are expecting to use a simple object / not a collection (Set, List)
*
* #param mapper : instance jackson object mapper
*
* #return A jackson JavaType to specify wich object represent the json string representation
*
*/
public JavaType createJavaType (ObjectMapper mapper){
return SimpleType.construct(returnedClass());
}
}
this is the specific user type
package model.common;
import service.dao.hibernate.JSONUserType;
public class DocumentInfoType extends JSONUserType {
#Override
public Class returnedClass() {
return DocumentInfo.class;
}
}
Here is my entity with custom type field
package model.common;
import model.SimpleAuditedEntity;
import model.lk.DocumentMode;
import model.lk.DocumentType;
import service.dao.hibernate.JSONUserType;
import java.io.Serializable;
import javax.persistence.*;
import org.hibernate.annotations.Parameter;
import org.hibernate.annotations.Type;
import org.hibernate.annotations.TypeDef;
import org.hibernate.annotations.TypeDefs;
import java.sql.Timestamp;
/**
* The persistent class for the documents database table.
*
*/
#Entity
#Table(name = "documents")
#NamedQuery(name = "Document.findAll", query = "SELECT d FROM Document d")
public class Document extends SimpleAuditedEntity implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#Column(name = "content_type")
private String contentType;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "type")
private DocumentType documentType;
#Column
private Timestamp created;
#Column
private String description;
#Column
private String filename;
#Column
private String name;
#Column
private String ref;
#Type(type = "model.common.DocumentInfoType")
#Column
private DocumentInfo info;
public Document() {
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getContentType() {
return this.contentType;
}
public void setContentType(String contentType) {
this.contentType = contentType;
}
public Timestamp getCreated() {
return this.created;
}
public void setCreated(Timestamp created) {
this.created = created;
}
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
public String getFilename() {
return this.filename;
}
public void setFilename(String filename) {
this.filename = filename;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getRef() {
return this.ref;
}
public void setRef(String ref) {
this.ref = ref;
}
/**
* #return the documentType
*/
public DocumentType getDocumentType() {
return documentType;
}
/**
* #param documentType
* the documentType to set
*/
public void setDocumentType(DocumentType documentType) {
this.documentType = documentType;
}
public DocumentMode getDocumentMode() {
return this.documentType != null ? DocumentMode
.getType(this.documentType.getId()) : DocumentMode.UNDEFINED;
}
/**
* #return the info
*/
public DocumentInfo getInfo() {
return info;
}
/**
* #param info the info to set
*/
public void setInfo(DocumentInfo info) {
this.info = info;
}
}
The problem is when I launch the application I get immediately the exception
Caused by: org.hibernate.MappingException: property mapping has wrong number of columns: model.common.Document.info type: model.common.DocumentInfoType
at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:497) [hibernate-core-4.3.7.Final.jar:4.3.7.Final]
at org.hibernate.mapping.RootClass.validate(RootClass.java:270) [hibernate-core-4.3.7.Final.jar:4.3.7.Final]
at org.hibernate.cfg.Configuration.validate(Configuration.java:1360) [hibernate-core-4.3.7.Final.jar:4.3.7.Final]
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1851) [hibernate-core-4.3.7.Final.jar:4.3.7.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:852) [hibernate-entitymanager-4.3.7.Final.jar:4.3.7.Final]
Any idea about? I've mapped all the columns and I've tried many modifications but nothing!
Thanks in advance
You return an array of SQLTypes from JSONUserType.sqlTypes() that contains 3 elements:
private static final int[] SQL_TYPES = new int[] { Types.LONGVARCHAR,
Types.CLOB, Types.BLOB };
This tells hibernate that your type maps to 3 columns.
You should choose one of the types only.
See the javadoc for UserType.sqlTypes():
Return the SQL type codes for the columns mapped by this type

com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter$UnknownFieldException

This is the frist time I am trying XStream. But when I try to parse my xml file i am getting this exception :
com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter$UnknownFieldException: No such field xmlread.Type.type
---- Debugging information ----
field : type
class : xmlread.Type
required-type : xmlread.Type
converter-type : com.thoughtworks.xstream.converters.reflection.ReflectionConverter
path : /root/type
line number : 10
version : 1.4.8
-------------------------------
at com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter.handleUnknownField(AbstractReflectionConverter.java:501)
at com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter.doUnmarshal(AbstractReflectionConverter.java:357)
at com.thoughtworks.xstream.converters.reflection.AbstractReflectionConverter.unmarshal(AbstractReflectionConverter.java:263)
at com.thoughtworks.xstream.core.TreeUnmarshaller.convert(TreeUnmarshaller.java:72)
at com.thoughtworks.xstream.core.AbstractReferenceUnmarshaller.convert(AbstractReferenceUnmarshaller.java:65)
at com.thoughtworks.xstream.core.TreeUnmarshaller.convertAnother(TreeUnmarshaller.java:66)
at com.thoughtworks.xstream.core.TreeUnmarshaller.convertAnother(TreeUnmarshaller.java:50)
at com.thoughtworks.xstream.core.TreeUnmarshaller.start(TreeUnmarshaller.java:134)
at com.thoughtworks.xstream.core.AbstractTreeMarshallingStrategy.unmarshal(AbstractTreeMarshallingStrategy.java:32)
at com.thoughtworks.xstream.XStream.unmarshal(XStream.java:1206)
at com.thoughtworks.xstream.XStream.unmarshal(XStream.java:1190)
at com.thoughtworks.xstream.XStream.fromXML(XStream.java:1061)
at xmlread.Main.main(Main.java:23)
So we can see that the error is on row 10 in my Type class.
And row 10 is the this line : #XStreamAlias("root")
package xmlread;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamImplicit;
#XStreamAlias("root")
public class Type {
#XStreamAlias("INFO")
private Info info;
#XStreamAlias("OBJECT_TYPE")
private String objectType;
#XStreamAlias("PROP")
private Properties prop;
#XStreamAlias("PARAM")
private List<Parameters> param;
#XStreamImplicit(itemFieldName = "type")
private List typeList = new ArrayList();
// metodo construtor
public Type() {
// TODO Auto-generated constructor stub
}
//Constructor, Getters and setters
public Info getInfo() {
return info;
}
public void setInfo(Info info) {
this.info = info;
}
public String getObjectType() {
return objectType;
}
public void setObjectType(String objectType) {
this.objectType = objectType;
}
public Properties getProp() {
return prop;
}
public void setProp(Properties prop) {
this.prop = prop;
}
public List<Parameters> getParam() {
return param;
}
public void setParam(List<Parameters> param) {
this.param = param;
}
public List getTypeList() {
return typeList;
}
public void setTypeList(List typeList) {
this.typeList = typeList;
}
}
And the xml looks like this :
<root>
<info>
<CORE_NAME>DataModel_Core</CORE_NAME>
<CORE_VERSION>..</CORE_VERSION>
<CORE_PRODUCT_ID>...</CORE_PRODUCT_ID>
<ADAPTATION_NAME />
<ADAPTATION_VERSION />
<ADAPTATION_PRODUCT_ID />
</info>
<type>
<OBJECT_TYPE>data</OBJECT_TYPE>
<prop>
<DESCRIPTION>Site parameters</DESCRIPTION>
<PARENT>NULL</PARENT>
<VIRTUAL>0</VIRTUAL>
<VISIBLE>1</VISIBLE>
<PICTURE>NULL</PICTURE>
<HELP>10008</HELP>
<MIN_NO>1</MIN_NO>
<MAX_NO>1</MAX_NO>
<NAME_FORMAT>NULL</NAME_FORMAT>
</prop>
<param>
<PARAMETER>nidRbc</PARAMETER>
<DATA_TYPE>INTEGER</DATA_TYPE>
<DESCRIPTION>RBC identity</DESCRIPTION>
<MIN_NO>1</MIN_NO>
<MAX_NO>1</MAX_NO>
<ORDER1>1</ORDER1>
<NESTED>0</NESTED>
<DEFAULT1>NULL</DEFAULT1>
<FORMAT>0:16382</FORMAT>
</param>
</type>
</root>
And my other classes looks like this :
package xmlread;
import java.io.*;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.XStreamException;
public class Main {
public static void main(String[] args) throws Exception {
try {
FileReader reader = new FileReader("enderecos.xml");
//String representacao = xstream.toXML(aluno);
XStream xstream = new XStream();
xstream.processAnnotations(Properties.class);
xstream.processAnnotations(Parameters.class);
xstream.processAnnotations(ObjType.class);
xstream.processAnnotations(Type.class);
Type data = (Type)xstream.fromXML(reader);
//Person newJoe = (Person)xstream.fromXML(xml);
System.out.println(data);
} catch (IOException io) {
io.printStackTrace();
} catch (XStreamException e) {
e.printStackTrace();
}
}
}
____________________________________________________________
package xmlread;
import java.util.List;
import com.thoughtworks.xstream.annotations.XStreamAlias;
#XStreamAlias("PARAM")
public class Parameters {
#XStreamAlias("DATATYPE")
private String datatype;
#XStreamAlias("DESCRIPTION")
private String description;
#XStreamAlias("MIN_NO")
private String min_no;
#XStreamAlias("MAX_NO")
private String max_no;
#XStreamAlias("ORDER1")
private String order1;
#XStreamAlias("NESTED")
private String nested;
#XStreamAlias("DEFAULT1")
private String default1;
#XStreamAlias("FORMAT")
private String format;
#XStreamAlias("PARAMETER")
private List<Parameters> parameter;
public Parameters(String datatype, String description, String min_no,
String max_no, String order1, String nested, String default1,
String format, List<Parameters> parameter) {
super();
setDatatype(datatype);
setDescription(description);
setMin_no(min_no);
setMax_no(max_no);
setOrder1(order1);
setNested(nested);
setDefault1(default1);
setFormat(format);
setParameter(parameter);
} // Getters and setters..
public Parameters() {
// TODO Auto-generated constructor stub
}
public String getDatatype() {
return datatype;
}
public void setDatatype(String datatype) {
this.datatype = datatype;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getMin_no() {
return min_no;
}
public void setMin_no(String min_no) {
this.min_no = min_no;
}
public String getMax_no() {
return max_no;
}
public void setMax_no(String max_no) {
this.max_no = max_no;
}
public String getOrder1() {
return order1;
}
public void setOrder1(String order1) {
this.order1 = order1;
}
public String getNested() {
return nested;
}
public void setNested(String nested) {
this.nested = nested;
}
public String getDefault1() {
return default1;
}
public void setDefault1(String default1) {
this.default1 = default1;
}
public String getFormat() {
return format;
}
public void setFormat(String format) {
this.format = format;
}
public List<Parameters> getParameter() {
return parameter;
}
public void setParameter(List<Parameters> parameter) {
this.parameter = parameter;
}
}
____________________________________________________________
package xmlread;
import com.thoughtworks.xstream.annotations.XStreamAlias;
#XStreamAlias("prop")
public class Properties {
#XStreamAlias("DESCRIPTION")
private String description;
#XStreamAlias("PARENT")
private String parent;
#XStreamAlias("VIRTUAL")
private String virtual;
#XStreamAlias("VISIBLE")
private String visible;
#XStreamAlias("PICTURE")
private String picture;
#XStreamAlias("HELP")
private String help;
#XStreamAlias("MIN_NO")
private String min_no;
#XStreamAlias("MAX_NO")
private String max_no;
#XStreamAlias("NAME_FORMAT")
private String name_format;
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getParent() {
return parent;
}
public void setParent(String parent) {
this.parent = parent;
}
public String getVirtual() {
return virtual;
}
public void setVirtual(String virtual) {
this.virtual = virtual;
}
public String getVisible() {
return visible;
}
public void setVisible(String visible) {
this.visible = visible;
}
public String getPicture() {
return picture;
}
public void setPicture(String picture) {
this.picture = picture;
}
public String getHelp() {
return help;
}
public void setHelp(String help) {
this.help = help;
}
public String getMin_no() {
return min_no;
}
public void setMin_no(String min_no) {
this.min_no = min_no;
}
public String getMax_no() {
return max_no;
}
public void setMax_no(String max_no) {
this.max_no = max_no;
}
public String getName_format() {
return name_format;
}
public void setName_format(String name_format) {
this.name_format = name_format;
}
public static void setInstance(Properties instance) {
Properties.instance = instance;
}
public static Properties instance = null;
public static Properties getInstance() {
if (instance == null) {
instance = new Properties();
}
return instance;
}
public Properties() {
// TODO Auto-generated constructor stub
}
}
____________________________________________________________
package xmlread;
import com.thoughtworks.xstream.annotations.XStreamAlias;
#XStreamAlias("INFO")
public class Info {
#XStreamAlias("CORE_NAME")
private String core_name;
#XStreamAlias("CORE_VERSION")
private String core_version;
#XStreamAlias("CORE_PRODUCT_ID")
private String core_product_id;
#XStreamAlias("ADAPTATION_NAME")
private String adaptation_name;
#XStreamAlias("ADAPTATION_VERSION")
private String adaptation_version;
#XStreamAlias("ADAPTATION_PRODUCT_ID")
private String adaptation_product_id;
public Info(String core_name, String core_version, String core_product_id,
String adaptation_name, String adaptation_version,
String adaptation_product_id) {
super();
setCore_name(core_name);
setCore_version(core_version);
setCore_product_id(core_product_id);
setAdaptation_name(adaptation_name);
setAdaptation_version(adaptation_version);
setAdaptation_product_id(adaptation_product_id);
}
public String getCore_name() {
return core_name;
}
public void setCore_name(String core_name) {
this.core_name = core_name;
}
public String getCore_version() {
return core_version;
}
public void setCore_version(String core_version) {
this.core_version = core_version;
}
public String getCore_product_id() {
return core_product_id;
}
public void setCore_product_id(String core_product_id) {
this.core_product_id = core_product_id;
}
public String getAdaptation_name() {
return adaptation_name;
}
public void setAdaptation_name(String adaptation_name) {
this.adaptation_name = adaptation_name;
}
public String getAdaptation_version() {
return adaptation_version;
}
public void setAdaptation_version(String adaptation_version) {
this.adaptation_version = adaptation_version;
}
public String getAdaptation_product_id() {
return adaptation_product_id;
}
public void setAdaptation_product_id(String adaptation_product_id) {
this.adaptation_product_id = adaptation_product_id;
}
}
____________________________________________________________
package xmlread;
import com.thoughtworks.xstream.annotations.XStreamAlias;
#XStreamAlias("OBJECT_TYPE")
public class ObjType {
#XStreamAlias("OBJECT_TYPE")
private String objectType;
public ObjType() {
} // Getters and setters
public String getObjectType() {
return objectType;
}
public void setObjectType(String objectType) {
this.objectType = objectType;
}
}
Whats the cause of this error?
package xmlread;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import com.thoughtworks.xstream.annotations.XStreamAlias;
import com.thoughtworks.xstream.annotations.XStreamImplicit;
#XStreamAlias("root")
public class SomeOtherClass {
#XStreamAlias("INFO")
private Info info;
#XStreamAlias("TYPE")
private Type type;
#XStreamImplicit(itemFieldName = "type")
private List typeList = new ArrayList();
// metodo construtor
public SomeOtherClass() {
// TODO Auto-generated constructor stub
}
//Constructor, Getters and setters
public void setType(Type type){
this.type = type;
}
public Type getType() {
return this.type;
}
public Info getInfo() {
return info;
}
public void setInfo(Info info) {
this.info = info;
}
}
class Type {
#XStreamAlias("OBJECT_TYPE")
private String objectType;
#XStreamAlias("PROP")
private Properties prop;
#XStreamAlias("PARAM")
private List<Parameters> param;
public String getObjectType() {
return objectType;
}
public void setObjectType(String objectType) {
this.objectType = objectType;
}
public Properties getProp() {
return prop;
}
public void setProp(Properties prop) {
this.prop = prop;
}
public List<Parameters> getParam() {
return param;
}
public void setParam(List<Parameters> param) {
this.param = param;
}
}

updating a record in a db - JSF JPA etc

i am wondering if you could help me
basically i have created a db, and it adds data to two pieces of data to the table, leaving the rest of the columns blank, what i want to do, is be able to update these records with some more data for the blank columns, how can i achieve this ?
this is my code atm, but i just get a null point error and don't know if im doing it right
This is the u.i.
<p>
Student Number : <!--More for me than anything -->
<h:inputText value="#{editMarkingBean.markSectionTwo.studentNumber}" />
</p>
this is where the student number is entered, this is what i want to update, the record that contains this student number (no way can there be more than one of the same username )
<p:spinner id="ajaxspinner80-100" value="#{editMarkingBean.markSectionTwo.markSectionTwo}"
stepFactor="1" min="80" max="100" disabled="#{formBean.number != 8}">
<p:ajax update="ajaxspinnervalue" process="#this" />
</p:spinner>
this is the value i want to add to the column markSectionTwo
the save button
<p:commandButton action="#{editMarkingBean.markSectionTwo}" value="#{bundle.buttonSave}" update=":growl" icon="ui-icon-disk"/>
the backing bean :
private MarkingService markingService;
#Inject
private MarkingFacade markingFacade;
public void markSectionTwo() {
this.markingFacade.edit(this.markSectionTwo);
this.setMessage("Mark Saved");
}
and this is the entity for the table creation
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String studentNumber,markingStage, markingCompleted, markSectionOne, markSectionTwo, markSectionThree, markSectionFour, markSectionFive, overalMark, plagorism, feedback, comments;
i get the error
WARNING: javax.el.PropertyNotFoundException: /lecturer/marking/marking-section-two.xhtml #109,82 value="#{editMarkingBean.markSectionTwo.markSectionTwo}": Target Unreachable, 'null' returned null
how can i update the records based on the student number ?
Thanks guys
EDIT
here is the complete editMarkingController class
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package sws.control;
import java.util.Date;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.view.ViewScoped;
import javax.inject.Inject;
import javax.inject.Named;
import sws.business.MarkingService;
import sws.entities.Marking;
import sws.persistance.MarkingFacade;
/**
*
* #author Richard
*/
#Named(value = "editMarkingBean")
#ViewScoped
public class EditMarkingController {
private String searchString;
private String ordering;
private String criteria;
private String match;
private Date today;
private String caseMatch;
private int spinnerField;
private Marking markSectionOne;
private Marking studentNumber;
private Marking markSectionTwo;
private MarkingService markingService;
#Inject
private MarkingFacade markingFacade;
/*
public String markSectionOne() {
//supposing the data in markSectionOne is filled...
this.markingFacade.create(markSectionOne);
this.setMessage("Mark Saved");
//after saving...
markSectionOne = new Marking();
// now navigating to the next page
return "/lecturer/marking/marking-section-two";
}
*/
public void editMark() {
this.markingFacade.edit(this.markSectionTwo);
this.setMessage("Mark Saved");
}
public void markSectionTwo() {
this.markingFacade.edit(this.markSectionTwo);
this.setMessage("Mark Saved");
}
private void setMessage(String message) {
FacesContext fc = FacesContext.getCurrentInstance();
fc.addMessage(null, new FacesMessage(message, ""));
}
public Marking getMarkSectionTwo() {
return markSectionTwo;
}
public void setMarkSectionTwo(Marking markSectionTwo) {
this.markSectionTwo = markSectionTwo;
}
public String getSearchString() {
return searchString;
}
public void setSearchString(String searchString) {
this.searchString = searchString;
}
public String getOrdering() {
return ordering;
}
public void setOrdering(String ordering) {
this.ordering = ordering;
}
public String getCriteria() {
return criteria;
}
public void setCriteria(String criteria) {
this.criteria = criteria;
}
public String getMatch() {
return match;
}
public void setMatch(String match) {
this.match = match;
}
public Date getToday() {
return today;
}
public void setToday(Date today) {
this.today = today;
}
public String getCaseMatch() {
return caseMatch;
}
public void setCaseMatch(String caseMatch) {
this.caseMatch = caseMatch;
}
public int getSpinnerField() {
return spinnerField;
}
public void setSpinnerField(int spinnerField) {
this.spinnerField = spinnerField;
}
public Marking getMarkSectionOne() {
return markSectionOne;
}
public void setMarkSectionOne(Marking markSectionOne) {
this.markSectionOne = markSectionOne;
}
public Marking getStudentNumber() {
return studentNumber;
}
public void setStudentNumber(Marking studentNumber) {
this.studentNumber = studentNumber;
}
public MarkingService getMarkingService() {
return markingService;
}
public void setMarkingService(MarkingService markingService) {
this.markingService = markingService;
}
public MarkingFacade getMarkingFacade() {
return markingFacade;
}
public void setMarkingFacade(MarkingFacade markingFacade) {
this.markingFacade = markingFacade;
}
}
the complete marking service
import java.util.List;
import javax.ejb.EJB;
import javax.inject.Inject;
import sws.entities.Marking;
import sws.entities.ProjectIdea;
import sws.persistance.MarkingFacade;
import sws.persistance.PersonFacade;
/**
*
* #author Richard
*/
public class MarkingService {
#EJB
private MarkingFacade markingFacade;
public List<Marking> getAllMarks() {
return markingFacade.findAll();
}
}
and comeplte marking entity
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package sws.entities;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
/**
*
* #author Richard
*/
#Entity(name = "MARKING")
public class Marking implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String studentNumber,markingStage, markingCompleted, markSectionOne, markSectionTwo, markSectionThree, markSectionFour, markSectionFive, overalMark, plagorism, feedback, comments;
public String getStudentNumber() {
return studentNumber;
}
public void setStudentNumber(String studentNumber) {
this.studentNumber = studentNumber;
}
public String getMarkingStage() {
return markingStage;
}
public void setMarkingStage(String markingStage) {
this.markingStage = markingStage;
}
public String getMarkingCompleted() {
return markingCompleted;
}
public void setMarkingCompleted(String markingCompleted) {
this.markingCompleted = markingCompleted;
}
public String getMarkSectionOne() {
return markSectionOne;
}
public void setMarkSectionOne(String markSectionOne) {
this.markSectionOne = markSectionOne;
}
public String getMarkSectionTwo() {
return markSectionTwo;
}
public void setMarkSectionTwo(String markSectionTwo) {
this.markSectionTwo = markSectionTwo;
}
public String getMarkSectionThree() {
return markSectionThree;
}
public void setMarkSectionThree(String markSectionThree) {
this.markSectionThree = markSectionThree;
}
public String getMarkSectionFour() {
return markSectionFour;
}
public void setMarkSectionFour(String markSectionFour) {
this.markSectionFour = markSectionFour;
}
public String getMarkSectionFive() {
return markSectionFive;
}
public void setMarkSectionFive(String markSectionFive) {
this.markSectionFive = markSectionFive;
}
public String getOveralMark() {
return overalMark;
}
public void setOveralMark(String overalMark) {
this.overalMark = overalMark;
}
public String getPlagorism() {
return plagorism;
}
public void setPlagorism(String plagorism) {
this.plagorism = plagorism;
}
public String getFeedback() {
return feedback;
}
public void setFeedback(String feedback) {
this.feedback = feedback;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#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 Marking)) {
return false;
}
Marking other = (Marking) 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 "sws.entities.Marking[ id=" + id + " ]";
}
public void setmarkSectionOne(String markSectionOne) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
EDIT 2:
i have added a postconstruct
#PostConstruct
public void markSectionTwo() {
this.markingFacade.edit(this.markSectionTwo);
markSectionTwo = new Marking();
this.setMessage("Mark Saved");
}
but now i get the error message http 500 error
javax.servlet.ServletException: WELD-000049 Unable to invoke public void sws.control.EditMarkingController.markSectionTwo() on sws.control.EditMarkingController#44de1491
root cause
org.jboss.weld.exceptions.WeldException: WELD-000049 Unable to invoke public void sws.control.EditMarkingController.markSectionTwo() on sws.control.EditMarkingController#44de1491
root cause
java.lang.reflect.InvocationTargetException
root cause
javax.ejb.EJBException
root cause
java.lang.IllegalArgumentException: Object: null is not a known entity type.
when i try to load the page
EDIT 3
i have fixed that issue, but now i am only able to add the record, what i am trying to do is merge the records, so if the studentNumber is the same as already in the table then update the markSectionTwo to this value rather than creating a new row in the db for it
private Marking markSectionTwo;
private MarkingService markingService;
#Inject
private MarkingFacade markingFacade;
#PostConstruct
public void init() {
this.markSectionTwo = new Marking();
}
public String markSectionTwo() {
//supposing the data in markSectionOne is filled...
//markSectionOne.setMarkSectionOne("markSectionOne");
//markSectionTwo.setMarkSectionTwo("markSectionTwo");
this.markingFacade.edit(markSectionTwo);
this.setMessage("Mark Saved");
//after saving...
markSectionTwo = new Marking();
this.setMessage("Mark Saved");
// now navigating to the next page
return "/lecturer/marking/marking-section-two";
}
private void setMessage(String message) {
FacesContext fc = FacesContext.getCurrentInstance();
fc.addMessage(null, new FacesMessage(message, ""));
}
your error message
javax.el.PropertyNotFoundException (...) #{editMarkingBean.markSectionTwo.markSectionTwo}"
basically says that you must have
a managed bean called editMarkingBean
an object in your managed bean called markSectionTwo with proper getter and setter
an attribute in your object markSectionTwo called markSectionTwo with proper getter and setter
so what EL is trying to call is
editMarkingBean.getMarkSectionTwo().getMarkSectionTwo()
please check all your classes and, if possible, post all the relevant parts in your question, such as classes names (all of them), managed bean scope annotations, getters and setters and attributes.

Categories