updating a record in a db - JSF JPA etc - java

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.

Related

Hibernate 4.3 Exception occurred inside setter when load all element for the DB when try mapping a Three structure

I'm getting into a hibernate error when I run a query that returns all the BD elements of type MessageUser.
I am mapping a binary tree and the MessageUser class contains a copy of this tree.
I mapped the tree with de objects children and a parent object and I mapped the two children with the same father, I suppose this is the error but I don't know an alternative way to have a similar but working solution.
This is my code
AbstractNode.java
/**
* This code is under license Creative Commons Attribution-ShareAlike 1.0
*
*/
package it.unibas.codinghuffman.model.logic.composit;
import it.unibas.codinghuffman.model.MessageUser;
import it.unibas.codinghuffman.model.logic.visitor.IVisitor;
import java.util.Objects;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.OneToOne;
import javax.persistence.Transient;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
*
* #author Vincenzo Palazzo
*/
#Entity(name = "abstract_node")
#Inheritance(strategy = InheritanceType.JOINED)
public class AbstractNode implements INode, Comparable<AbstractNode> {
private static final Log LOGGER = LogFactory.getLog(AbstractNode.class);
protected String value;
protected int frequency;
protected int valueArch;
private AbstractNode leaftNode;
private AbstractNode rightNode;
//for hibernate
private Long id;
private MessageUser message;
private AbstractNode father;
public AbstractNode(AbstractNode leaftNode, AbstractNode rightNode) {
this.leaftNode = leaftNode;
this.rightNode = rightNode;
this.leaftNode.setFather(this);
this.leaftNode.setValueArch(0);
this.rightNode.setFather(this);
this.rightNode.setValueArch(1);
if (this.leaftNode.getFather() == null) {
throw new IllegalArgumentException("Fater null");
}
if (this.rightNode.getFather() == null) {
throw new IllegalArgumentException("Fater null");
}
}
public AbstractNode() {
}
#Transient
public boolean isLeaft() {
return leaftNode == null;
}
#OneToOne(mappedBy = "father", cascade = CascadeType.ALL)
public AbstractNode getLeaftNode() {
return leaftNode;
}
public void setLeaftNode(AbstractNode leaftNode) {
this.leaftNode = leaftNode;
this.leaftNode.setFather(this);
this.leaftNode.setValueArch(0);
}
#OneToOne(mappedBy = "father", cascade = CascadeType.ALL)
public AbstractNode getRightNode() {
return rightNode;
}
public void setRightNode(AbstractNode rightNode) {
this.rightNode = rightNode;
this.rightNode.setFather(this);
this.rightNode.setValueArch(1);
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public int getFrequency() {
return frequency;
}
public void setFrequency(int frequency) {
this.frequency = frequency;
}
#Id
#GeneratedValue(strategy = GenerationType.TABLE)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#OneToOne
public MessageUser getMessage() {
return message;
}
public void setMessage(MessageUser message) {
this.message = message;
}
#OneToOne
public AbstractNode getFather() {
return father;
}
public void setFather(AbstractNode father) {
this.father = father;
}
public int getValueArch() {
return valueArch;
}
public void setValueArch(int valueArch) {
this.valueArch = valueArch;
}
public void accept(IVisitor visitor) {
if (visitor == null) {
LOGGER.error("The visitor into method accept is null");
throw new IllegalArgumentException("The visitor into method accept is null");
}
}
#Override
public int hashCode() {
int hash = 7;
hash = 83 * hash + Objects.hashCode(this.value);
hash = 83 * hash + Objects.hashCode(this.leaftNode);
hash = 83 * hash + Objects.hashCode(this.rightNode);
return hash;
}
#Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final AbstractNode other = (AbstractNode) obj;
if (!Objects.equals(this.value, other.value)) {
return false;
}
if (!Objects.equals(this.leaftNode, other.leaftNode)) {
return false;
}
if (!Objects.equals(this.rightNode, other.rightNode)) {
return false;
}
return true;
}
#Override
public int compareTo(AbstractNode o) {
return ((Integer) frequency).compareTo(o.getFrequency());
}
}
NodeComplex.java
/**
* This code is under license Creative Commons Attribution-ShareAlike 1.0
*
*/
package it.unibas.codinghuffman.model.logic.composit;
import it.unibas.codinghuffman.model.logic.visitor.IVisitor;
import javax.persistence.Entity;
/**
*
* #author Vincenzo Palazzo
*/
#Entity(name = "complex_node")
public class NodeComplex extends AbstractNode{
public NodeComplex(String value, int frequency, AbstractNode leaftNode, AbstractNode rightNode) {
super(leaftNode, rightNode);
this.value = value;
this.frequency = frequency;
}
public NodeComplex() {
super();
//throw new IllegalArgumentException("You are creating a lefth node, please you use the NodeLeaft implementation");
}
#Override
public void accept(IVisitor visitor) {
super.accept(visitor);
visitor.visitComplexNode(this);
}
}
NodeLeaft.class
/**
* This code is under license Creative Commons Attribution-ShareAlike 1.0
*
*/
package it.unibas.codinghuffman.model.logic.composit;
import it.unibas.codinghuffman.model.logic.visitor.IVisitor;
import javax.persistence.Entity;
/**
*
* #author Vincenzo Palazzo
*/
#Entity(name = "leafth_node")
public class NodeLeaft extends AbstractNode {
public NodeLeaft(AbstractNode leaftNode, AbstractNode rightNode) {
throw new IllegalArgumentException("You are creating a complex node, please you use the NodeComplex implementation");
}
public NodeLeaft(String value, int frequency) {
super();
this.value = value;
this.frequency = frequency;
}
public NodeLeaft() {
super();
}
#Override
public void accept(IVisitor visitor) {
super.accept(visitor);
visitor.visitLeaftNode(this);
}
#Override
public String toString() {
return value + frequency;
}
}
MessageUser.class
/*
* This code is under license Creative Commons Attribution-ShareAlike 1.0
*
*/
package it.unibas.codinghuffman.model;
import it.unibas.codinghuffman.model.logic.composit.AbstractNode;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
/**
*
* #author https://github.com/vincenzopalazzo
*/
#Entity(name = "messages")
public class MessageUser {
private Long id;
private String word;
private int lenghtAsci;
private int lenghtHuffman;
private int ratioCompression;
//This is not request to app
private AbstractNode huffmanTree;
private String huffmanCoding;
private String stringHuffmanTree;
public MessageUser() {}
public MessageUser(String word, int lenghtAsci, int lenghtHuffman, int ratioCompression) {
this.word = word;
this.lenghtAsci = lenghtAsci;
this.lenghtHuffman = lenghtHuffman;
this.ratioCompression = ratioCompression;
}
#Id
#GeneratedValue(strategy = GenerationType.TABLE)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
// #Column(nullable = false)
public String getWord() {
return word;
}
public void setWord(String word) {
this.word = word;
}
//#Column(nullable = false)
public int getLenghtAsci() {
return lenghtAsci;
}
public void setLenghtAsci(int lenghtAsci) {
this.lenghtAsci = lenghtAsci;
}
// #Column(nullable = false)
public int getLenghtHuffman() {
return lenghtHuffman;
}
public void setLenghtHuffman(int lenghtHuffman) {
this.lenghtHuffman = lenghtHuffman;
}
// #Column(nullable = false)
public int getRatioCompression() {
return ratioCompression;
}
public void setRatioCompression(int ratioCompression) {
this.ratioCompression = ratioCompression;
}
#OneToOne(mappedBy = "message", cascade = CascadeType.ALL)
public AbstractNode getHuffmanTree() {
return huffmanTree;
}
public void setHuffmanTree(AbstractNode huffmanTree) {
this.huffmanTree = huffmanTree;
huffmanTree.setMessage(this);
}
public String getHuffmanCoding() {
return huffmanCoding;
}
public void setHuffmanCoding(String huffmanCoding) {
this.huffmanCoding = huffmanCoding;
}
public String getStringHuffmanTree() {
return stringHuffmanTree;
}
public void setStringHuffmanTree(String stringHuffmanTree) {
this.stringHuffmanTree = stringHuffmanTree;
}
}
Exception generater
Caused by: org.hibernate.PropertyAccessException: Exception occurred inside setter of it.unibas.codinghuffman.model.logic.composit.AbstractNode.leaftNode
at org.hibernate.property.BasicPropertyAccessor$BasicSetter.set(BasicPropertyAccessor.java:91)
at org.hibernate.tuple.entity.AbstractEntityTuplizer.setPropertyValues(AbstractEntityTuplizer.java:713)
at org.hibernate.tuple.entity.PojoEntityTuplizer.setPropertyValues(PojoEntityTuplizer.java:362)
at org.hibernate.persister.entity.AbstractEntityPersister.setPropertyValues(AbstractEntityPersister.java:4718)
at org.hibernate.engine.internal.TwoPhaseLoad.doInitializeEntity(TwoPhaseLoad.java:188)
at org.hibernate.engine.internal.TwoPhaseLoad.initializeEntity(TwoPhaseLoad.java:144)
at org.hibernate.loader.Loader.initializeEntitiesAndCollections(Loader.java:1115)
at org.hibernate.loader.Loader.processResultSet(Loader.java:973)
at org.hibernate.loader.Loader.doQuery(Loader.java:921)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:355)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:325)
at org.hibernate.loader.Loader.loadEntity(Loader.java:2149)
at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:78)
at org.hibernate.loader.entity.EntityLoader.loadByUniqueKey(EntityLoader.java:161)
at org.hibernate.persister.entity.AbstractEntityPersister.loadByUniqueKey(AbstractEntityPersister.java:2385)
at org.hibernate.type.EntityType.loadByUniqueKey(EntityType.java:767)
at org.hibernate.type.EntityType.resolve(EntityType.java:505)
at org.hibernate.engine.internal.TwoPhaseLoad.doInitializeEntity(TwoPhaseLoad.java:170)
at org.hibernate.engine.internal.TwoPhaseLoad.initializeEntity(TwoPhaseLoad.java:144)
at org.hibernate.loader.Loader.initializeEntitiesAndCollections(Loader.java:1115)
at org.hibernate.loader.Loader.processResultSet(Loader.java:973)
at org.hibernate.loader.Loader.doQuery(Loader.java:921)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:355)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:325)
at org.hibernate.loader.Loader.loadEntity(Loader.java:2149)
at org.hibernate.loader.entity.AbstractEntityLoader.load(AbstractEntityLoader.java:78)
at org.hibernate.loader.entity.EntityLoader.loadByUniqueKey(EntityLoader.java:161)
at org.hibernate.persister.entity.AbstractEntityPersister.loadByUniqueKey(AbstractEntityPersister.java:2385)
at org.hibernate.type.EntityType.loadByUniqueKey(EntityType.java:767)
at org.hibernate.type.EntityType.resolve(EntityType.java:505)
at org.hibernate.engine.internal.TwoPhaseLoad.doInitializeEntity(TwoPhaseLoad.java:170)
at org.hibernate.engine.internal.TwoPhaseLoad.initializeEntity(TwoPhaseLoad.java:144)
at org.hibernate.loader.Loader.initializeEntitiesAndCollections(Loader.java:1115)
at org.hibernate.loader.Loader.processResultSet(Loader.java:973)
at org.hibernate.loader.Loader.doQuery(Loader.java:921)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:355)
at org.hibernate.loader.Loader.doList(Loader.java:2554)
at org.hibernate.loader.Loader.doList(Loader.java:2540)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2370)
at org.hibernate.loader.Loader.list(Loader.java:2365)
at org.hibernate.loader.criteria.CriteriaLoader.list(CriteriaLoader.java:126)
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1718)
at org.hibernate.internal.CriteriaImpl.list(CriteriaImpl.java:380)
at it.unibas.codinghuffman.persistence.hibernate.DAOGenericoHibernate.findByCriteria(DAOGenericoHibernate.java:105)
... 47 more
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.hibernate.property.BasicPropertyAccessor$BasicSetter.set(BasicPropertyAccessor.java:68)
... 90 more
Caused by: java.lang.NullPointerException
at it.unibas.codinghuffman.model.logic.composit.AbstractNode.setLeaftNode(AbstractNode.java:78)
I want to give at this question an answer, the exception generate from hibernate is generated because hibernate fin two objects with the same id, for resolving this but I must add another information to the children of the configuration and this configuration is this JoinColum("fater_id")
The mapping for the children is this
#OneToOne(mappedBy = "father", cascade = CascadeType.ALL)
#JoinColum("fater_id")
public AbstractNode getLeaftNode() {
return leaftNode;
}
#OneToOne(mappedBy = "father", cascade = CascadeType.ALL)
#JoinColum("fater_id")
public AbstractNode getRightNode() {
return rightNode;
}

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

No getter method for property

Hi I am trying to use struts to get a bean to my jsp code the bean I am using in my jsp page is: but whenever I run the jsp I am receiving
No getter method for property: "testData.team.type" of bean: "unitForm".
I am trying to write baseball to my JSP page.
The code for my action form is:
import com.TestGettingData;
import org.apache.struts.action.ActionForm;
public class UnitForm extends ActionForm {
private TestGettingData testData = new TestGettingData();
public TestGettingData getTestData() {
return testData;
}
public void setTestData(TestGettingData testData) {
this.testData = testData;
}
}
testing data class has:
public class TestGettingData extends Sport{
private String team = "Yankees";
private String position = "short stop";
public void setTeam(String tm) {
team = tm; }
public String getTeam() {
return team; }
public void setPosition(String po) {
position = po; }
public String getPosition() {
return position;
}
}
and finally in my sport class:
public class Sport{
public String type = "baseball";
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
Instead of testData.team.type, try testData.type. type is a property in testData not in team.
Update
${unitForm.testData.type} should display "baseball" in your JSP.

Why this class not serializable?

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

Categories