PropertyNotFoundException: Target Unreachable, 'null' returned null [duplicate] - java

This question already has answers here:
Identifying and solving javax.el.PropertyNotFoundException: Target Unreachable
(18 answers)
Closed 7 years ago.
Hello i have new Problem with Add Form
my problem here
WARNING: /test.xhtml #24,173 value="#{userController.users.username}": Target Unreachable, 'null' returned null
javax.el.PropertyNotFoundException: /test.xhtml #24,173 value="#{userController.users.username}": Target Unreachable, 'null' returned null
at com.sun.faces.facelets.el.TagValueExpression.getType(TagValueExpression.java:93)
at com.sun.faces.renderkit.html_basic.HtmlBasicInputRenderer.getConvertedValue(HtmlBasicInputRenderer.java:95)
at javax.faces.component.UIInput.getConvertedValue(UIInput.java:1008)
at javax.faces.component.UIInput.validate(UIInput.java:934)
at javax.faces.component.UIInput.executeValidate(UIInput.java:1189)
at javax.faces.component.UIInput.processValidators(UIInput.java:691)
at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1080)
at javax.faces.component.UIForm.processValidators(UIForm.java:243)
at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1080)
at javax.faces.component.UIComponentBase.processValidators(UIComponentBase.java:1080)
at javax.faces.component.UIViewRoot.processValidators(UIViewRoot.java:1180)
at com.sun.faces.lifecycle.ProcessValidationsPhase.execute(ProcessValidationsPhase.java:76)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:312)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1523)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:279)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:188)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:641)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:97)
at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:85)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:185)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:325)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:226)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:165)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:791)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:693)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:954)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:170)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:135)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:102)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:88)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:76)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:53)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:57)
at com.sun.grizzly.ContextTask.run(ContextTask.java:69)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:330)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:309)
at java.lang.Thread.run(Thread.java:619)
and my back bean
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.ejb.controller;
import com.ejbbean.iUserBean;
import com.entity.Igroup;
import com.entity.Iuser;
import java.awt.event.ActionEvent;
import java.io.Serializable;
import java.util.List;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import javax.faces.model.SelectItem;
/**
*
* #author KencyWindy
*/
#ManagedBean
#ViewScoped
public class UserController implements Serializable{
#EJB
private iUserBean iUserBean;
private Iuser users ;
private Igroup groupa;
public UserController() {
}
public Igroup getGroupa() {
return groupa;
}
public void setGroupa(Igroup groupa) {
this.groupa = groupa;
}
public Iuser getUsers() {
return users;
}
public void setUsers(Iuser users) {
this.users = users;
}
public List<Iuser> getAllUser(){
return iUserBean.retrieve();
}
public void addUser(){
users = new Iuser();
users = iUserBean.createUser(users);
}
public javax.faces.model.SelectItem[] getAllOfGroups(){
SelectItem[] options = null;
List<Igroup> lgroup = iUserBean.retrieveGroup();
if(lgroup.size() > 0 && lgroup != null){
options = new SelectItem[lgroup.size()];
int i = 0 ;
for ( Igroup igroup : lgroup){
options[i++] = new SelectItem(igroup.getGId(), igroup.getGroupname());
}
}
return options;
}
public void submit(ActionEvent event) {
FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Correct", "Correct");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
}
Igroup Entity Class
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.entity;
import java.io.Serializable;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
/**
*
* #author KencyWindy
*/
#Entity
#Table(name = "igroup")
#NamedQueries({
#NamedQuery(name = "Igroup.findAll", query = "SELECT i FROM Igroup i"),
#NamedQuery(name = "Igroup.findByGId", query = "SELECT i FROM Igroup i WHERE i.gId = :gId"),
#NamedQuery(name = "Igroup.findByGroupname", query = "SELECT i FROM Igroup i WHERE i.Groupname = :Groupname"),
#NamedQuery(name = "Igroup.findByAdministrator", query = "SELECT i FROM Igroup i WHERE i.administrator = :administrator"),
#NamedQuery(name = "Igroup.findByReaded", query = "SELECT i FROM Igroup i WHERE i.readed = :readed"),
#NamedQuery(name = "Igroup.findByDeleted", query = "SELECT i FROM Igroup i WHERE i.deleted = :deleted"),
#NamedQuery(name = "Igroup.findByUpdated", query = "SELECT i FROM Igroup i WHERE i.updated = :updated"),
#NamedQuery(name = "Igroup.findByModed", query = "SELECT i FROM Igroup i WHERE i.moded = :moded"),
#NamedQuery(name = "Igroup.findByAdded", query = "SELECT i FROM Igroup i WHERE i.added = :added")})
public class Igroup implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "g_id")
private Integer gId;
#Basic(optional = false)
#Column(name = "g_name")
private String Groupname;
#Column(name = "administrator")
private Boolean administrator;
#Basic(optional = false)
#Column(name = "readed")
private boolean readed;
#Column(name = "deleted")
private Boolean deleted;
#Column(name = "updated")
private Boolean updated;
#Column(name = "moded")
private Boolean moded;
#Column(name = "added")
private Boolean added;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "igroup")
private List<Iuser> iuserList;
public Igroup() {
}
public Igroup(Integer gId) {
this.gId = gId;
}
public Igroup(Integer gId, String gName, boolean readed) {
this.gId = gId;
this.Groupname = gName;
this.readed = readed;
}
public Integer getGId() {
return gId;
}
public void setGId(Integer gId) {
this.gId = gId;
}
public String getGroupname() {
return Groupname;
}
public void setGroupname(String Groupname) {
this.Groupname = Groupname;
}
public Boolean getAdministrator() {
return administrator;
}
public void setAdministrator(Boolean administrator) {
this.administrator = administrator;
}
public boolean getReaded() {
return readed;
}
public void setReaded(boolean readed) {
this.readed = readed;
}
public Boolean getDeleted() {
return deleted;
}
public void setDeleted(Boolean deleted) {
this.deleted = deleted;
}
public Boolean getUpdated() {
return updated;
}
public void setUpdated(Boolean updated) {
this.updated = updated;
}
public Boolean getModed() {
return moded;
}
public void setModed(Boolean moded) {
this.moded = moded;
}
public Boolean getAdded() {
return added;
}
public void setAdded(Boolean added) {
this.added = added;
}
public List<Iuser> getIuserList() {
return iuserList;
}
public void setIuserList(List<Iuser> iuserList) {
this.iuserList = iuserList;
}
#Override
public int hashCode() {
int hash = 0;
hash += (gId != null ? gId.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 Igroup)) {
return false;
}
Igroup other = (Igroup) object;
if ((this.gId == null && other.gId != null) || (this.gId != null && !this.gId.equals(other.gId))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.entity.Igroup[gId=" + gId + "]";
}
}
Iuser Entity Class
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.entity;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
/**
*
* #author KencyWindy
*/
#Entity
#Table(name = "iuser")
#NamedQueries({
#NamedQuery(name = "Iuser.findAll", query = "SELECT i FROM Iuser i"),
#NamedQuery(name = "Iuser.findByUid", query = "SELECT i FROM Iuser i WHERE i.uid = :uid"),
#NamedQuery(name = "Iuser.findByUsername", query = "SELECT i FROM Iuser i WHERE i.username = :username"),
#NamedQuery(name = "Iuser.findByPassword", query = "SELECT i FROM Iuser i WHERE i.password = :password"),
#NamedQuery(name = "Iuser.findByPnum", query = "SELECT i FROM Iuser i WHERE i.pnum = :pnum"),
#NamedQuery(name = "Iuser.findByZipcode", query = "SELECT i FROM Iuser i WHERE i.zipcode = :zipcode"),
#NamedQuery(name = "Iuser.findByState", query = "SELECT i FROM Iuser i WHERE i.state = :state"),
#NamedQuery(name = "Iuser.findByDob", query = "SELECT i FROM Iuser i WHERE i.dob = :dob"),
#NamedQuery(name = "Iuser.findByEmail", query = "SELECT i FROM Iuser i WHERE i.email = :email"),
#NamedQuery(name = "Iuser.findByLastlogin", query = "SELECT i FROM Iuser i WHERE i.lastlogin = :lastlogin"),
#NamedQuery(name = "Iuser.findByRegdate", query = "SELECT i FROM Iuser i WHERE i.regdate = :regdate"),
#NamedQuery(name = "Iuser.findByAddress", query = "SELECT i FROM Iuser i WHERE i.address = :address"),
#NamedQuery(name = "Iuser.findByCity", query = "SELECT i FROM Iuser i WHERE i.city = :city")})
public class Iuser implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "uid")
private Integer uid;
#Basic(optional = false)
#Column(name = "username")
private String username;
#Basic(optional = false)
#Column(name = "password")
private String password;
#Basic(optional = false)
#Column(name = "pnum")
private int pnum;
#Basic(optional = false)
#Column(name = "zipcode")
private int zipcode;
#Basic(optional = false)
#Column(name = "state")
private String state;
#Basic(optional = false)
#Column(name = "dob")
#Temporal(TemporalType.TIMESTAMP)
private Date dob;
#Basic(optional = false)
#Column(name = "email")
private String email;
#Column(name = "lastlogin")
#Temporal(TemporalType.TIMESTAMP)
private Date lastlogin;
#Column(name = "regdate")
#Temporal(TemporalType.TIMESTAMP)
private Date regdate;
#Basic(optional = false)
#Column(name = "address")
private String address;
#Basic(optional = false)
#Column(name = "city")
private String city;
#JoinColumn(name = "igroup", referencedColumnName = "g_id")
#ManyToOne(optional = false)
private Igroup igroup;
public Iuser() {
}
public Iuser(Integer uid) {
this.uid = uid;
}
public Iuser(Integer uid, String username, String password, int pnum, int zipcode, String state, Date dob, String email, String address, String city) {
this.uid = uid;
this.username = username;
this.password = password;
this.pnum = pnum;
this.zipcode = zipcode;
this.state = state;
this.dob = dob;
this.email = email;
this.address = address;
this.city = city;
}
public Integer getUid() {
return uid;
}
public void setUid(Integer uid) {
this.uid = uid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getPnum() {
return pnum;
}
public void setPnum(int pnum) {
this.pnum = pnum;
}
public int getZipcode() {
return zipcode;
}
public void setZipcode(int zipcode) {
this.zipcode = zipcode;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public Date getDob() {
return dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getLastlogin() {
return lastlogin;
}
public void setLastlogin(Date lastlogin) {
this.lastlogin = lastlogin;
}
public Date getRegdate() {
return regdate;
}
public void setRegdate(Date regdate) {
this.regdate = regdate;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public Igroup getIgroup() {
return igroup;
}
public void setIgroup(Igroup igroup) {
this.igroup = igroup;
}
public Integer getGrouplist(){
return this.igroup.getGId();
}
public void setGrouplist(Integer intgroup){
this.igroup = new Igroup(intgroup);
}
#Override
public int hashCode() {
int hash = 0;
hash += (uid != null ? uid.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 Iuser)) {
return false;
}
Iuser other = (Iuser) object;
if ((this.uid == null && other.uid != null) || (this.uid != null && !this.uid.equals(other.uid))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.entity.Iuser[uid=" + uid + "]";
}
}

value="#{userController.users.username}":
Target Unreachable, 'null' returned null
Either #{userController} or #{userController.users} is null.
My cents that #{userController.users} is null. You aren't prepopulating it in your bean. The #{userController} is correctly declared and used as #ManagedBean.
You need to prepopulate it in the postconstruct of the bean:
#PostConstruct
public void init() {
users = new Iuser();
}

In UserController class, declare your variable like this.
public Iuser users = new Iuser();
Because unless you use new Iuser() the object is not created and it will returned a null value.

initialize your Iuser class in backing bean like this way
public Iuser getUsers() {
if(users == null){
users = (Iuser )super.getInstance(Iuser.Class);
}
return users;
}
this will create a new Iuser object if the object become null

Related

How to recover a product entity with this query below?

I'm waiting for a product type entity object with the quantity and total cahmps containing the values ​​of SUM (lc.quantity) as quantite, SUM (lc.montant) as total, but I get an object of type java.lang.object
This is my query
#NamedQuery(name = "Produit.findAllBuyPorductGroupByProduct",
query = "SELECT p, SUM(lc.quantite) quantite, SUM(lc.montant) total
FROM LigneCommande lc JOIN lc.produit p
GROUP BY p")
This is my product 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 com.instantech.stogeg.data.base.entity;
import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.Transient;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* #author instantech
*/
#Entity
#Table(name = "produit")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Produit.findAll", query = "SELECT p FROM Produit p")
, #NamedQuery(name = "Produit.findById", query = "SELECT p FROM Produit p WHERE p.id = :id")
, #NamedQuery(name = "Produit.findByReference", query = "SELECT p FROM Produit p WHERE p.reference = :reference")
, #NamedQuery(name = "Produit.findByDesignation", query = "SELECT p FROM Produit p WHERE p.designation = :designation")
, #NamedQuery(name = "Produit.findByStock", query = "SELECT p FROM Produit p WHERE p.stock = :stock")
, #NamedQuery(name = "Produit.findAllBuyPorductGroupByProduct", query = "SELECT p, SUM(lc.quantite) quantite, SUM(lc.montant) total FROM LigneCommande lc JOIN lc.produit p GROUP BY p")
, #NamedQuery(name = "Produit.findBy_", query = "SELECT p FROM Produit p WHERE CAST(p.id as CHAR) LIKE :numeroProduit OR CAST(p.pu as CHAR) LIKE :pu OR CAST(p.stock as CHAR) LIKE :stock OR p.reference LIKE :reference OR p.designation LIKE :designation ORDER BY p.designation")
, #NamedQuery(name = "Produit.findByPu", query = "SELECT p FROM Produit p WHERE p.pu = :pu")
, #NamedQuery(name = "Produit.findByDate", query = "SELECT p FROM Produit p WHERE p.date = :date")
, #NamedQuery(name = "Produit.findByHeure", query = "SELECT p FROM Produit p WHERE p.heure = :heure")})
public class Produit implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Basic(optional = false)
#Column(name = "reference")
private String reference;
#Basic(optional = false)
#Column(name = "designation")
private String designation;
#Basic(optional = false)
#Column(name = "stock")
private int stock;
#Basic(optional = false)
#Column(name = "pu")
private float pu;
#Basic(optional = false)
#Column(name = "date")
#Temporal(TemporalType.DATE)
private Date date;
#Basic(optional = false)
#Column(name = "heure")
#Temporal(TemporalType.TIME)
private Date heure;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "produit")
private Collection<LigneCommande> ligneCommandeCollection;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "produit")
private Collection<HistoryStock> historyStockCollection;
#Transient
private int quantite;
#Transient
private double total;
public Produit() {
}
public Produit(Integer id) {
this.id = id;
}
public Produit(Integer id, String reference, String designation, int stock, float pu, Date date, Date heure) {
this.id = id;
this.reference = reference;
this.designation = designation;
this.stock = stock;
this.pu = pu;
this.date = date;
this.heure = heure;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getReference() {
return reference;
}
public void setReference(String reference) {
this.reference = reference;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public int getStock() {
return stock;
}
public void setStock(int stock) {
this.stock = stock;
}
public float getPu() {
return pu;
}
public void setPu(float pu) {
this.pu = pu;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public Date getHeure() {
return heure;
}
public void setHeure(Date heure) {
this.heure = heure;
}
#XmlTransient
public Collection<LigneCommande> getLigneCommandeCollection() {
return ligneCommandeCollection;
}
public void setLigneCommandeCollection(Collection<LigneCommande> ligneCommandeCollection) {
this.ligneCommandeCollection = ligneCommandeCollection;
}
#XmlTransient
public Collection<HistoryStock> getHistoryStockCollection() {
return historyStockCollection;
}
public void setHistoryStockCollection(Collection<HistoryStock> historyStockCollection) {
this.historyStockCollection = historyStockCollection;
}
#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 Produit)) {
return false;
}
Produit other = (Produit) object;
return !((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id)));
}
#Override
public String toString() {
return this.getDesignation() + " ( "+this.getStock()+ " ) ";
}
public Object[] getProduit(){
return new Object [] {
this.getId(), this.getReference(), this.getDesignation(), this.getStock(), this.getPu()
};
}
public int updateStock(int quantite) throws Exception{
if(quantite > this.getStock())
throw new Exception("Le stock du produit est inférieur à la quantité commandé");
else
return (this.getStock() - quantite);
}
public int adQuantity(int quantite) throws Exception{
if(quantite > 0){
return (this.getStock() + quantite);
}else{
throw new Exception("Le stock du produit est ne peut pas être null ou négatif");
}
}
public int getQuantite() {
return quantite;
}
public void setQuantite(int quantite) {
this.quantite = quantite;
}
public double getTotal() {
return total;
}
public void setTotal(double total) {
this.total = total;
}
}
This is my line command 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 com.instantech.stogeg.data.base.entity;
import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* #author instantech
*/
#Entity
#Table(name = "ligne_commande")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "LigneCommande.findAll", query = "SELECT l FROM LigneCommande l")
, #NamedQuery(name = "LigneCommande.findById", query = "SELECT l FROM LigneCommande l WHERE l.id = :id")
, #NamedQuery(name = "LigneCommande.findByQuantite", query = "SELECT l FROM LigneCommande l WHERE l.quantite = :quantite")
, #NamedQuery(name = "LigneCommande.findByMontant", query = "SELECT l FROM LigneCommande l WHERE l.montant = :montant")})
public class LigneCommande implements Serializable {
#Basic(optional = false)
#Column(name = "date")
#Temporal(TemporalType.DATE)
private Date date;
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Basic(optional = false)
#Column(name = "quantite")
private int quantite;
#Basic(optional = false)
#Column(name = "montant")
private double montant;
#ManyToMany(mappedBy = "ligneCommandeCollection")
private Collection<Commande> commandeCollection;
#JoinColumn(name = "produit", referencedColumnName = "id")
#ManyToOne(optional = false)
private Produit produit;
public LigneCommande() {
}
public LigneCommande(Integer id) {
this.id = id;
}
public LigneCommande(Integer id, int quantite, double montant, Date date) {
this.id = id;
this.quantite = quantite;
this.montant = montant;
this.date = date;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public int getQuantite() {
return quantite;
}
public void setQuantite(int quantite) {
this.quantite = quantite;
}
public double getMontant() {
return montant;
}
public void setMontant(double montant) {
this.montant = montant;
}
#XmlTransient
public Collection<Commande> getCommandeCollection() {
return commandeCollection;
}
public void setCommandeCollection(Collection<Commande> commandeCollection) {
this.commandeCollection = commandeCollection;
}
public Produit getProduit() {
return produit;
}
public void setProduit(Produit produit) {
this.produit = produit;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
if (!(object instanceof LigneCommande)) {
return false;
}
LigneCommande other = (LigneCommande) object;
return !((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id)));
}
#Override
public String toString() {
return "com.instantech.entity.LigneCommande[ id=" + id + " ]";
}
public void addQuantite(int quantite){
this.quantite += quantite;
}
public double getTotal() {
return this.getQuantite() * this.getProduit().getPu();
}
public Object[] getLigneCommande(){
return new Object[] {
this.getProduit().getReference(),
this.getProduit().getDesignation(),
this.getQuantite(),
String.format("%, .0f",this.getProduit().getPu()),
String.format("%, .0f",this.getTotal())
};
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
}
The function that retrieves the result of my query
/**
* Return list of product that grouped by product
*
* #return
*/
public List<Produit> findProductGroupBy() {
TypedQuery<Produit> query = this.getEntitymanager().createNamedQuery("Produit.findAllBuyPorductGroupByProduct", Produit.class);
return query.getResultList();
}
Test of my query
public class test {
private static ProduitManager pm;
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
pm = new ProduitManager();
pm.findProductGroupBy().forEach((p)->{
System.out.println(p);
});
pm.close();
}
}
This is the result after execution
Exception in thread "main" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to com.instantech.stogeg.data.base.entity.Produit
at java.util.Vector.forEach(Vector.java:1275)
at test.main(test.java:22)
NB: In my product table in the database, the quantity and total field that are in my product entity are not there.
1) Create some sort of a TO:
public class ResultDTO{
private Product product;
private Integer quantity;
private Double total;
public ResultDTO(Product product, Integer quantity, Double total){
// set fields
}
2) Alter the query to use that class:
#NamedQuery(name = "Produit.findAllBuyPorductGroupByProduct",
query = "SELECT new com.mypackage.ResultDTO(
p as product, SUM(lc.quantite) as quantity, SUM(lc.montant) as total)
FROM LigneCommande lc JOIN lc.produit p
GROUP BY p")
3) Change generic type to ResultDTO:
public List<ResultDTO> findProductGroupBy() {
TypedQuery<ResultDTO> query = this.getEntitymanager().createNamedQuery(
"Produit.findAllBuyPorductGroupByProduct", ResultDTO.class);
return query.getResultList();
}
What you are looking for is called projections. How to use them is very thoroughly explained over here. They work better than custom objects (via new keyword) because they support native queries and are generally easier to understand.
Step 1: Declare a simple bean data transfer object (dto)
#Data
#NoArgsConstructor
#AllArgsConstructor
public class ProductSummaryDto {
private Product product;
private Integer quantity;
private Double total;
}
Step 2: Create custom spring data query in your repository
#Query("SELECT p product, SUM(lc.quantite) quantity, SUM(lc.montant) total FROM LigneCommande lc JOIN lc.produit p GROUP BY p")
List<ProductSummaryDto> getProductSummaries();

JPA ManytoOne bidirectional

i use web serice maven with jersey the data base sql server with jpa
and netbeans .
i have a probleme when i want do login.getPersonne(); the print return null;
i'm not understand why can you help me please .
thanks you
/*
* 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 fr.ietevents.serviceweb.Entity;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* #author IETEVENTS
*/
#Entity
#Table(name = "Login")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Login.findAll", query = "SELECT l FROM Login l"),
#NamedQuery(name = "Login.connexion", query = "SELECT l FROM Login l WHERE l.login = :login and l.password = :password"),
#NamedQuery(name = "Login.findByKeyLogin", query = "SELECT l FROM Login l WHERE l.keyLogin = :keyLogin"),
#NamedQuery(name = "Login.findByActif", query = "SELECT l FROM Login l WHERE l.actif = :actif"),
#NamedQuery(name = "Login.findByDateCreation", query = "SELECT l FROM Login l WHERE l.dateCreation = :dateCreation"),
#NamedQuery(name = "Login.findByKeyPersonne", query = "SELECT l FROM Login l WHERE l.personne = :personne"),
#NamedQuery(name = "Login.findByLogin", query = "SELECT l FROM Login l WHERE l.login = :login"),
#NamedQuery(name = "Login.findByPassword", query = "SELECT l FROM Login l WHERE l.password = :password")})
public class Login implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "KeyLogin")
private Integer keyLogin;
#Size(max = 255)
#Column(name = "Actif")
private String actif;
#Column(name = "DateCreation")
#Temporal(TemporalType.TIMESTAMP)
private Date dateCreation;
#ManyToOne()
#JoinColumn(name = "KeyPersonne",referencedColumnName = "KeyPersonne")
private Personne personne;
#Size(max = 255)
#Column(name = "Login")
private String login;
#Size(max = 255)
#Column(name = "Password")
private String password;
public Login() {
}
public Login(Integer keyLogin) {
this.keyLogin = keyLogin;
}
public Integer getKeyLogin() {
return keyLogin;
}
public void setKeyLogin(Integer keyLogin) {
this.keyLogin = keyLogin;
}
public String getActif() {
return actif;
}
public void setActif(String actif) {
this.actif = actif;
}
public Date getDateCreation() {
return dateCreation;
}
public void setDateCreation(Date dateCreation) {
this.dateCreation = dateCreation;
}
public Personne getPersonne() {
return personne;
}
public void setPersonne(Personne personne) {
this.personne = personne;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Override
public int hashCode() {
int hash = 0;
hash += (keyLogin != null ? keyLogin.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 Login)) {
return false;
}
Login other = (Login) object;
if ((this.keyLogin == null && other.keyLogin != null) || (this.keyLogin != null && !this.keyLogin.equals(other.keyLogin))) {
return false;
}
return true;
}
#Override
public String toString() {
return "fr.ietevents.serviceweb.Entity.Login[ keyLogin=" + keyLogin + " ]";
}
}
/*
* 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 fr.ietevents.serviceweb.Entity;
import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* #author IETEVENTS
*/
#Entity
#Table(name = "Personne")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Personne.findAll", query = "SELECT p FROM Personne p"),
#NamedQuery(name = "Personne.findByKeyPersonne", query = "SELECT p FROM Personne p WHERE p.keyPersonne = :keyPersonne"),
#NamedQuery(name = "Personne.findByActif", query = "SELECT p FROM Personne p WHERE p.actif = :actif"),
#NamedQuery(name = "Personne.findByDateCreation", query = "SELECT p FROM Personne p WHERE p.dateCreation = :dateCreation"),
#NamedQuery(name = "Personne.findByDateModification", query = "SELECT p FROM Personne p WHERE p.dateModification = :dateModification"),
#NamedQuery(name = "Personne.findByEmail", query = "SELECT p FROM Personne p WHERE p.email = :email"),
#NamedQuery(name = "Personne.findByFax", query = "SELECT p FROM Personne p WHERE p.fax = :fax"),
#NamedQuery(name = "Personne.findByKeyCivilite", query = "SELECT p FROM Personne p WHERE p.keyCivilite = :keyCivilite"),
#NamedQuery(name = "Personne.findByKeySociete", query = "SELECT p FROM Personne p WHERE p.keySociete = :keySociete"),
#NamedQuery(name = "Personne.findByKeyTypeUser", query = "SELECT p FROM Personne p WHERE p.TypeUser = :TypeUser"),
#NamedQuery(name = "Personne.findByNom", query = "SELECT p FROM Personne p WHERE p.nom = :nom"),
#NamedQuery(name = "Personne.findByPortable", query = "SELECT p FROM Personne p WHERE p.portable = :portable"),
#NamedQuery(name = "Personne.findByPrenom", query = "SELECT p FROM Personne p WHERE p.prenom = :prenom"),
#NamedQuery(name = "Personne.findByTelephone", query = "SELECT p FROM Personne p WHERE p.telephone = :telephone")})
public class Personne implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "KeyPersonne")
private Integer keyPersonne;
#Size(max = 255)
#Column(name = "Actif")
private String actif;
#Column(name = "DateCreation")
#Temporal(TemporalType.TIMESTAMP)
private Date dateCreation;
#Column(name = "DateModification")
#Temporal(TemporalType.TIMESTAMP)
private Date dateModification;
// #Pattern(regexp="[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", message="Invalid email")//if the field contains email address consider using this annotation to enforce field validation
#Size(max = 255)
#Column(name = "Email")
private String email;
// #Pattern(regexp="^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{4})$", message="Invalid phone/fax format, should be as xxx-xxx-xxxx")//if the field contains phone or fax number consider using this annotation to enforce field validation
#Size(max = 255)
#Column(name = "Fax")
private String fax;
#Column(name = "KeyCivilite")
private Integer keyCivilite;
#Column(name = "KeySociete")
private Integer keySociete;
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "KeyTypeUser")
private TypeUser TypeUser;
#Size(max = 255)
#Column(name = "Nom")
private String nom;
#Size(max = 255)
#Column(name = "Portable")
private String portable;
#Size(max = 255)
#Column(name = "Prenom")
private String prenom;
#Size(max = 255)
#Column(name = "Telephone")
private String telephone;
#OneToMany(cascade = CascadeType.ALL,mappedBy = "personne")
private Collection<Login> ListLogin;
public Personne() {
}
public Personne(Integer keyPersonne) {
this.keyPersonne = keyPersonne;
}
public Collection<Login> getListLogin() {
return ListLogin;
}
public void setListLogin(Collection<Login> ListLogin) {
this.ListLogin = ListLogin;
}
public TypeUser getTypeUser() {
return TypeUser;
}
public void setTypeUser(TypeUser TypeUser) {
this.TypeUser = TypeUser;
}
public Integer getKeyPersonne() {
return keyPersonne;
}
public void setKeyPersonne(Integer keyPersonne) {
this.keyPersonne = keyPersonne;
}
public String getActif() {
return actif;
}
public void setActif(String actif) {
this.actif = actif;
}
public Date getDateCreation() {
return dateCreation;
}
public void setDateCreation(Date dateCreation) {
this.dateCreation = dateCreation;
}
public Date getDateModification() {
return dateModification;
}
public void setDateModification(Date dateModification) {
this.dateModification = dateModification;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFax() {
return fax;
}
public void setFax(String fax) {
this.fax = fax;
}
public Integer getKeyCivilite() {
return keyCivilite;
}
public void setKeyCivilite(Integer keyCivilite) {
this.keyCivilite = keyCivilite;
}
public Integer getKeySociete() {
return keySociete;
}
public void setKeySociete(Integer keySociete) {
this.keySociete = keySociete;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getPortable() {
return portable;
}
public void setPortable(String portable) {
this.portable = portable;
}
public String getPrenom() {
return prenom;
}
public void setPrenom(String prenom) {
this.prenom = prenom;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
#Override
public int hashCode() {
int hash = 0;
hash += (keyPersonne != null ? keyPersonne.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 Personne)) {
return false;
}
Personne other = (Personne) object;
if ((this.keyPersonne == null && other.keyPersonne != null) || (this.keyPersonne != null && !this.keyPersonne.equals(other.keyPersonne))) {
return false;
}
return true;
}
#Override
public String toString() {
return "fr.ietevents.serviceweb.Entity.Personne[ keyPersonne=" + keyPersonne + " ]";
}
}
The value for CLIENT_IDclient is null. That is why you're getting this exception. Add a null check before passing values to the query.
Hope this helps.

How to display all reviews for a specific product using JSTL <c:forEach> tag?

I have set up a form that successfully insert a user product review into database. Now i'm trying to display all the reviews for the given product using c:forEach but it does not work. Basically im trying to tell the program for each selected product get productReviews but it returns blank. I have 3 classes (ProductReview, ProductHasReview, ProductHasReviewPK) that take care of holding the setter/getter methods as well as the session Beans for the entities.
Servlet
import entity.ProductHasReview;
import entity.Product;
import java.util.Collection;
import javax.ejb.EJB;
import session.ProductFacade;
#EJB
private ProductFacade productFacade;
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String userPath = request.getServletPath();
HttpSession session = request.getSession();
Collection<ProductHasReview> productReview = null;
// if product page is requested
} else if (userPath.equals("/viewProduct")) {
String productId = request.getQueryString();
if (productId != null) {
// get selected product
selectedProduct = productFacade.find(Integer.parseInt(productId));
// place selected product in session scope
session.setAttribute("selectedProduct", selectedProduct);
// get all reviews for selected products
productReview = selectedProduct.getProductHasReviewCollection();
// place products reviews in session scope
session.setAttribute("productReview", productReview);
}
userPath = "/product";
Product.jsp
<c:forEach var="product" items="${productReview}" varStatus="iter">
<div class="content ProdReviewRow">
<h3>${productReview.name}, ${productReview.age}, ${productReview.gender} </h3>
<h6>${productReview.dateCreated}<h6>
${productReview.review}
</div>
</c:forEach>
Product.java
package entity;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Lob;
import javax.persistence.ManyToMany;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
#Entity
#Table(name = "product")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Product.findAll", query = "SELECT p FROM Product p"),
#NamedQuery(name = "Product.findById", query = "SELECT p FROM Product p WHERE p.id = :id"),
#NamedQuery(name = "Product.findByPrice", query = "SELECT p FROM Product p WHERE p.price = :price"),
#NamedQuery(name = "Product.findByLastUpdate", query = "SELECT p FROM Product p WHERE p.lastUpdate = :lastUpdate")})
public class Product implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Basic(optional = false)
#NotNull
#Lob
#Size(min = 1, max = 16777215)
#Column(name = "name")
private String name;
// #Max(value=?) #Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
#Basic(optional = false)
#NotNull
#Column(name = "price")
private BigDecimal price;
#Basic(optional = false)
#NotNull
#Lob
#Size(min = 1, max = 2147483647)
#Column(name = "description")
private String description;
#Basic(optional = false)
#NotNull
#Column(name = "last_update")
#Temporal(TemporalType.TIMESTAMP)
private Date lastUpdate;
#Basic(optional = false)
#NotNull
#Lob
#Size(min = 1, max = 2147483647)
#Column(name = "faq")
private String faq;
#ManyToMany(mappedBy = "productCollection")
private Collection<Category> categoryCollection;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "product")
private Collection<ProductHasBadRating> productHasBadRatingCollection;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "product")
private Collection<OrderedProduct> orderedProductCollection;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "product")
private Collection<ProductHasGoodRating> productHasGoodRatingCollection;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "product")
private Collection<ProductHasReview> productHasReviewCollection;
public Product() {
}
public Product(Integer id) {
this.id = id;
}
public Product(Integer id, String name, BigDecimal price, String description, Date lastUpdate, String faq) {
this.id = id;
this.name = name;
this.price = price;
this.description = description;
this.lastUpdate = lastUpdate;
this.faq = faq;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Date getLastUpdate() {
return lastUpdate;
}
public void setLastUpdate(Date lastUpdate) {
this.lastUpdate = lastUpdate;
}
public String getFaq() {
return faq;
}
public void setFaq(String faq) {
this.faq = faq;
}
#XmlTransient
public Collection<Category> getCategoryCollection() {
return categoryCollection;
}
public void setCategoryCollection(Collection<Category> categoryCollection) {
this.categoryCollection = categoryCollection;
}
#XmlTransient
public Collection<ProductHasBadRating> getProductHasBadRatingCollection() {
return productHasBadRatingCollection;
}
public void setProductHasBadRatingCollection(Collection<ProductHasBadRating> productHasBadRatingCollection) {
this.productHasBadRatingCollection = productHasBadRatingCollection;
}
#XmlTransient
public Collection<OrderedProduct> getOrderedProductCollection() {
return orderedProductCollection;
}
public void setOrderedProductCollection(Collection<OrderedProduct> orderedProductCollection) {
this.orderedProductCollection = orderedProductCollection;
}
#XmlTransient
public Collection<ProductHasGoodRating> getProductHasGoodRatingCollection() {
return productHasGoodRatingCollection;
}
public void setProductHasGoodRatingCollection(Collection<ProductHasGoodRating> productHasGoodRatingCollection) {
this.productHasGoodRatingCollection = productHasGoodRatingCollection;
}
#XmlTransient
public Collection<ProductHasReview> getProductHasReviewCollection() {
return productHasReviewCollection;
}
public void setProductHasReviewCollection(Collection<ProductHasReview> productHasReviewCollection) {
this.productHasReviewCollection = productHasReviewCollection;
}
#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 Product)) {
return false;
}
Product other = (Product) 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 "entity.Product[ id=" + id + " ]";
}
}
ProductReview.java
#Entity
#Table(name = "product_review")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "ProductReview.findAll", query = "SELECT p FROM ProductReview p"),
#NamedQuery(name = "ProductReview.findById", query = "SELECT p FROM ProductReview p WHERE p.id = :id"),
#NamedQuery(name = "ProductReview.findByName", query = "SELECT p FROM ProductReview p WHERE p.name = :name"),
#NamedQuery(name = "ProductReview.findByDateCreated", query = "SELECT p FROM ProductReview p WHERE p.dateCreated = :dateCreated"),
#NamedQuery(name = "ProductReview.findByCountry", query = "SELECT p FROM ProductReview p WHERE p.country = :country"),
#NamedQuery(name = "ProductReview.findByAge", query = "SELECT p FROM ProductReview p WHERE p.age = :age"),
#NamedQuery(name = "ProductReview.findByGender", query = "SELECT p FROM ProductReview p WHERE p.gender = :gender"),
#NamedQuery(name = "ProductReview.findByEmail", query = "SELECT p FROM ProductReview p WHERE p.email = :email")})
public class ProductReview implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Lob
#Size(max = 2147483647)
#Column(name = "review")
private String review;
#Size(max = 45)
#Column(name = "name")
private String name;
#Column(name = "date_created")
#Temporal(TemporalType.TIMESTAMP)
private Date dateCreated;
#Size(max = 45)
#Column(name = "country")
private String country;
#Size(max = 45)
#Column(name = "age")
private String age;
#Size(max = 45)
#Column(name = "gender")
private String gender;
// #Pattern(regexp="[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", message="Invalid email")//if the field contains email address consider using this annotation to enforce field validation
#Size(max = 45)
#Column(name = "email")
private String email;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "productReview")
private Collection<ProductHasReview> productHasReviewCollection;
public ProductReview() {
}
public ProductReview(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getReview() {
return review;
}
public void setReview(String review) {
this.review = review;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getDateCreated() {
return dateCreated;
}
public void setDateCreated(Date dateCreated) {
this.dateCreated = dateCreated;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#XmlTransient
public Collection<ProductHasReview> getProductHasReviewCollection() {
return productHasReviewCollection;
}
public void setProductHasReviewCollection(Collection<ProductHasReview> productHasReviewCollection) {
this.productHasReviewCollection = productHasReviewCollection;
}
#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 ProductReview)) {
return false;
}
ProductReview other = (ProductReview) 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 "entity.ProductReview[ id=" + id + " ]";
}
}
ProductHasReview.java
package entity;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* #author PC
*/
#Entity
#Table(name = "product_has_review")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "ProductHasReview.findAll", query = "SELECT p FROM ProductHasReview p"),
#NamedQuery(name = "ProductHasReview.findByProductId", query = "SELECT p FROM ProductHasReview p WHERE p.productHasReviewPK.productId = :productId"),
#NamedQuery(name = "ProductHasReview.findByProductReviewId", query = "SELECT p FROM ProductHasReview p WHERE p.productHasReviewPK.productReviewId = :productReviewId"),
#NamedQuery(name = "ProductHasReview.findByQuantity", query = "SELECT p FROM ProductHasReview p WHERE p.quantity = :quantity")})
public class ProductHasReview implements Serializable {
private static final long serialVersionUID = 1L;
#EmbeddedId
protected ProductHasReviewPK productHasReviewPK;
#Column(name = "quantity")
private Short quantity;
#JoinColumn(name = "product_id", referencedColumnName = "id", insertable = false, updatable = false)
#ManyToOne(optional = false)
private Product product;
#JoinColumn(name = "product_review_id", referencedColumnName = "id", insertable = false, updatable = false)
#ManyToOne(optional = false)
private ProductReview productReview;
public ProductHasReview() {
}
public ProductHasReview(ProductHasReviewPK productHasReviewPK) {
this.productHasReviewPK = productHasReviewPK;
}
public ProductHasReview(int productId, int productReviewId) {
this.productHasReviewPK = new ProductHasReviewPK(productId, productReviewId);
}
public ProductHasReviewPK getProductHasReviewPK() {
return productHasReviewPK;
}
public void setProductHasReviewPK(ProductHasReviewPK productHasReviewPK) {
this.productHasReviewPK = productHasReviewPK;
}
public Short getQuantity() {
return quantity;
}
public void setQuantity(Short quantity) {
this.quantity = quantity;
}
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public ProductReview getProductReview() {
return productReview;
}
public void setProductReview(ProductReview productReview) {
this.productReview = productReview;
}
#Override
public int hashCode() {
int hash = 0;
hash += (productHasReviewPK != null ? productHasReviewPK.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 ProductHasReview)) {
return false;
}
ProductHasReview other = (ProductHasReview) object;
if ((this.productHasReviewPK == null && other.productHasReviewPK != null) || (this.productHasReviewPK != null && !this.productHasReviewPK.equals(other.productHasReviewPK))) {
return false;
}
return true;
}
#Override
public String toString() {
return "entity.ProductHasReview[ productHasReviewPK=" + productHasReviewPK + " ]";
}
}

How to persist a many to one, bidirectional entity on the owning side in Java JPA?

I am getting a null value for persisting of a one to many bidirectional entity causing a constraint error.
I have two entities set up as follows below and I have an 'abstract facade' which handles the entity manager that simply persists, flushes, merges etc the entities to the database. I have a Restful backend to handle interaction between ejbs and web clients (mobile inc). All is working in order apart from when I try to persist a "token" in this example adding an existing user to it. The code below should explain what I am trying to achieve.
User
package ejb;
import java.io.Serializable;
import java.util.Collection;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import javax.persistence.PrePersist;
import java.util.UUID;
import javax.persistence.UniqueConstraint;
#Entity
#Table(name = "users", catalog = "test", schema = "public", uniqueConstraints = #UniqueConstraint(columnNames = {"username", "email"}))
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Users.findAll", query = "SELECT u FROM Users u")
})
public class Users implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 36)
#Column(name = "userid")
private String userid;
#Size(max = 100)
#Column(name = "username")
private String username;
#Size(max = 108)
#Column(name = "email")
private String email;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "users")
private Collection<Tokens> tokensCollection;
public Users() {
}
public Users(String userid) {
this.userid = userid;
}
public String getUserid() {
return userid;
}
public void serUserid(String userid) {
this.userid= userid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#XmlTransient
public Collection<Tokens> getTokensCollection() {
return tokensCollection;
}
public void setTokensCollection(Tokens token) {
token.setUser(this);
tokensCollection.add(token);
}
#Override
public String toString() {
return "ejb.Users[ userid =" + userid + " ]";
}
#PrePersist
protected void setUUID(){
String uuid = UUID.randomUUID().toString();
this.userid = uuid;
}
}
Tokens
package ejb;
import java.io.Serializable;
import java.sql.Timestamp;
import java.util.Date;
import java.util.UUID;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.PrePersist;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
#Entity
#Table(name = "tokens", catalog = "test", schema = "public")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Tokens.findAll", query = "SELECT t FROM Tokens t"),
#NamedQuery(name = "Tokens.findByTokenid", query = "SELECT t FROM Tokens t WHERE t.tokenid = :tokenid"),
#NamedQuery(name = "Tokens.findByDevice", query = "SELECT t FROM Tokens t WHERE t.device = :device"),
#NamedQuery(name = "Tokens.findByJWT", query = "SELECT t FROM Tokens t WHERE t.jwt = :jwt"),
#NamedQuery(name = "Tokens.findByCreatedTime", query = "SELECT t FROM Tokens t WHERE t.createdTime = :createdTime"),
#NamedQuery(name = "Tokens.findByExpires", query = "SELECT t FROM Tokens t WHERE t.expires = :expires")
})
public class Tokens implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 36)
#Column(name = "tokenid")
private String tokenid;
#Column(name = "device")
private String device;
#Basic(optional = false)
#NotNull
#Column(name = "jwt")
private String jwt;
#Basic(optional = false)
#NotNull
#Column(name = "createdTime")
#Temporal(TemporalType.TIMESTAMP)
private Date createdTime;
#Basic(optional = false)
#NotNull
#Column(name = "expires")
#Temporal(TemporalType.TIMESTAMP)
private Date expires;
#JoinColumn(name = "userid", referencedColumnName = "userid", insertable = false, updatable = false)
#ManyToOne(optional = false)
#NotNull
private Users users;
public String getTokenid() {
return tokenid;
}
public void setTokenid(String tokenid) {
this.tokenid = tokenid;
}
public String getDevice() {
return device;
}
public void setDevice(String device) {
this.device = device;
}
public String getJWT() {
return jwt;
}
public void setJWT(String JWT) {
this.jwt = JWT;
}
public Date getCreatedTime() {
return createdTime;
}
public void setCreatedTime(Date createdTime) {
this.createdTime = createdTime;
}
public Date getExpiryTime() {
return expires;
}
public void setExpiryTime(Date expires) {
this.expires = expires;
}
public Users getUsers() {
return users;
}
public void setUsers(Users users) {
this.users = users;
}
#Override
public int hashCode() {
int hash = 0;
hash += (tokenid != null ? tokenid.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 Tokens)) {
return false;
}
Tokens other = (Tokens) object;
if ((this.tokenid == null && other.tokenid != null) || (this.tokenid != null && !this.tokenid.equals(other.tokenid))) {
return false;
}
return true;
}
#Override
public String toString() {
return "ejb.tokens[ id=" + tokenid + " ]";
}
#PrePersist
protected void setUUID() {
String uuid = UUID.randomUUID().toString();
this.tokenid = uuid;
this.createdTime = new Timestamp(new Date().getTime());
long expTime = 60 * 60 * 24 * 30;
this.expires = new Timestamp(new Date().getTime() + expTime);
}
}
Abstract Facade
package ejb;
import java.util.List;
import javax.persistence.EntityManager;
public abstract class AbstractFacade<T> {
private Class<T> entityClass;
public AbstractFacade(Class<T> entityClass) {
this.entityClass = entityClass;
}
protected abstract EntityManager getEntityManager();
public void create(T entity) {
getEntityManager().persist(entity);
getEntityManager().flush();
}
public void edit(T entity) {
getEntityManager().merge(entity);
}
public void remove(T entity) {
getEntityManager().remove(getEntityManager().merge(entity));
}
public T find(Object id) {
return getEntityManager().find(entityClass, id);
}
public List<T> findAll() {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
return getEntityManager().createQuery(cq).getResultList();
}
public List<T> findRange(int[] range) {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
javax.persistence.Query q = getEntityManager().createQuery(cq);
q.setMaxResults(range[1] - range[0] + 1);
q.setFirstResult(range[0]);
return q.getResultList();
}
public int count() {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
javax.persistence.criteria.Root<T> rt = cq.from(entityClass);
cq.select(getEntityManager().getCriteriaBuilder().count(rt));
javax.persistence.Query q = getEntityManager().createQuery(cq);
return ((Long) q.getSingleResult()).intValue();
}
}
Chunk of code to create token
Users user = ufl.getUserByUsername(username);
//test the user isn't null => outputs expected result of username
System.out.println("===WHO? " + user.getUsername() + "===");
Tokens tkn = new Tokens();
tkn.setJWT(token);
tkn.setUsers(user);
tfl.create(tkn);
Error
Caused by: org.postgresql.util.PSQLException: ERROR: null value in column "userid" violates not-null constraint
Detail: Failing row contains (5aa5fefa-4744-4acf-a640-338ea9b35758, 2015-08-04 20:28:08.578, null, 2015-08-04 21:11:20.578, eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiJiNmY0N2ViMS1iMDdmLTQyNTctYWI0OS0..., null).
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2157)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1886)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:255)
at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:559)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:417)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeUpdate(AbstractJdbc2Statement.java:363)
at org.jboss.jca.adapters.jdbc.WrappedPreparedStatement.executeUpdate(WrappedPreparedStatement.java:493)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:208) [hibernate-core-4.3.7.Final.jar:4.3.7.Final]
... 98 more
Conclusion
It is trying to persist the entity but is inserting a null value for the userid even though in the chunk of code I have setUser to user. The user is being found by getting the user by username. Not sure what is causing the issue.

Issue with StoreController servlet in Spring MVC

I'm working through a tutorial on Spring MVC and I am getting an error in my StoreController that I cant seem to sort. The three code snippets I have added are StoreController.java (servlet), Album.java and Genre.java which are Entity classes. I am getting an error # line 76 of StoreController as follows: The method getName() is undefined for type Integer. I will add the code just below and I hope someone can help me understand my problem:
Thanks and regards
Gus
Code: storeController.java
package com.MVCMusicStore.Controllers;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import com.MVCMusicStore.Entities.Album;
import com.MVCMusicStore.Entities.Genre;
import com.MVCMusicStore.Models.AlbumModel;
import com.MVCMusicStore.Models.GenreModel;
import com.MVCMusicStore.Models.ArtistModel;
import com.MVCMusicStore.Entities.Artist;
#Controller
#RequestMapping("/Store")
public class StoreController {
#Resource(name = "genreService")
private GenreModel genreModel;
#Resource(name = "albumService")
private AlbumModel albumModel;
/**
* Map Root of Store Page
* #param model
* #return
*/
#RequestMapping(value = "/", method = RequestMethod.GET)
public String getStoreIndexPage(ModelMap model) {
// This is for the side menu
List<Genre> myGenreList = genreModel.findAllGenres();
model.put("genreList" , myGenreList);
model.put("genreCount", myGenreList.size());
// This is for the albums
//List<Genre> myGenreList = genreModel.findAllGenres();
//model.put("allAlbums", allAlbums);
return "storeindex";
}
/**
* Map the Browse page
*
* #param genreName
* #param model
* #return
*/
#RequestMapping(value = "/Browse", method = RequestMethod.GET)
public String getStoreBrowsePage(
#RequestParam(value = "genre", required = false) String genreName,
ModelMap model) {
// It's for albums
List<Album> foundAlbum = new ArrayList<Album>();
if (genreName == null) {
model.put("genre", "Empty");
} else {
List<Album> myAlbum = albumModel.findAllAlbums();
for (Album tempAlbum : myAlbum) {
if (tempAlbum.getGenreid().getName().equals(genreName))
{
foundAlbum.add(tempAlbum);
}
}
model.put("genre", genreName);
model.put("foundAlbum", foundAlbum);
}
// "genre" - should have the same name as value="genre"
//model.addAttribute("genre", genre);
return "Browse";
}
/**
* Map the Browse Page
* #param genre
* #param model
* #return
*/
//#RequestMapping(value = "/Browse", method = RequestMethod.GET)
//public String getStoreBrowsePage(#RequestParam(value="genre", required=false)
//String genre, ModelMap model) {
//model.addAttribute("genre",genre);
//return "Browse";
//}
}
Album.java
package com.MVCMusicStore.Entities;
/**
* #author Gus
*
*/
import java.io.Serializable;
import java.math.BigDecimal;
import java.math.BigInteger;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* #author Gus
*/
#Entity
#Table(name = "ALBUM")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Album.findAll", query = "SELECT a FROM Album a"),
#NamedQuery(name = "Album.findByAlbumid", query = "SELECT a FROM Album a WHERE a.albumid = :albumid"),
#NamedQuery(name = "Album.findByGenreid", query = "SELECT a FROM Album a WHERE a.genreid = :genreid"),
#NamedQuery(name = "Album.findByArtistid", query = "SELECT a FROM Album a WHERE a.artistid = :artistid"),
#NamedQuery(name = "Album.findByTitle", query = "SELECT a FROM Album a WHERE a.title = :title"),
#NamedQuery(name = "Album.findByPrice", query = "SELECT a FROM Album a WHERE a.price = :price"),
#NamedQuery(name = "Album.findByAlbumarturl", query = "SELECT a FROM Album a WHERE a.albumarturl = :albumarturl")})
public class Album implements Serializable {
private static final long serialVersionUID = 1L;
// #Max(value=?) #Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
#Id
#Basic(optional = false)
#Column(name = "ALBUMID")
private Integer albumid;
#Column(name = "GENREID")
private Integer genreid;
#Column(name = "ARTISTID")
private Integer artistid;
#Column(name = "TITLE")
private String title;
#Column(name = "PRICE")
private Integer price;
#Column(name = "ALBUMARTURL")
private String albumarturl;
public Album() {
}
public Album(Integer albumid) {
this.albumid = albumid;
}
public Integer getAlbumid() {
return albumid;
}
public void setAlbumid(Integer albumid) {
this.albumid = albumid;
}
public Integer getGenreid() {
return genreid;
}
public void setGenreid(Integer genreid) {
this.genreid = genreid;
}
public Integer getArtistid() {
return artistid;
}
public void setArtistid(Integer artistid) {
this.artistid = artistid;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Integer getPrice() {
return price;
}
public void setPrice(Integer price) {
this.price = price;
}
public String getAlbumarturl() {
return albumarturl;
}
public void setAlbumarturl(String albumarturl) {
this.albumarturl = albumarturl;
}
#Override
public int hashCode() {
int hash = 0;
hash += (albumid != null ? albumid.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 Album)) {
return false;
}
Album other = (Album) object;
if ((this.albumid == null && other.albumid != null) || (this.albumid != null && !this.albumid.equals(other.albumid))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.MVCMusicStore.Entities.Album[ albumid=" + albumid + " ]";
}
}
Genre.java
package com.MVCMusicStore.Entities;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
import com.MVCMusicStore.Entities.Artist;
import com.MVCMusicStore.Entities.Album;
/**
*
* #author Gus
*/
#Entity
#Table(name = "GENRE")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Genre.findAll", query = "SELECT g FROM Genre g"),
#NamedQuery(name = "Genre.findByGenreid", query = "SELECT g FROM Genre g WHERE g.genreid = :genreid"),
#NamedQuery(name = "Genre.findByName", query = "SELECT g FROM Genre g WHERE g.name = :name"),
#NamedQuery(name = "Genre.findByDescription", query = "SELECT g FROM Genre g WHERE g.description = :description")})
public class Genre implements Serializable {
private static final long serialVersionUID = 1L;
// #Max(value=?) #Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
#Id
#Basic(optional = false)
#Column(name = "GENREID")
private Integer genreid;
#Column(name = "NAME")
private String name;
#Column(name = "DESCRIPTION")
private String description;
public Genre() {
}
public Genre(Integer genreid) {
this.genreid = genreid;
}
public Integer getGenreid() {
return genreid;
}
public void setGenreid(Integer genreid) {
this.genreid = genreid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Override
public int hashCode() {
int hash = 0;
hash += (genreid != null ? genreid.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 Genre)) {
return false;
}
Genre other = (Genre) object;
if ((this.genreid == null && other.genreid != null) || (this.genreid != null && !this.genreid.equals(other.genreid))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.MVCMusicStore.Entities.Genre[ genreid=" + genreid + " ]";
}
}
The error is telling you exactly what's wrong here. When you run this:
tempAlbum.getGenreid().getName().equals(genreName)
The method getGenreid() is returning an Integer, you are then attempting to get the name of the integer when what you actually want to do is run the getName() method on an a genre object.
Album Entity
#Column(name = "GENREID")
private Integer genreid;
StoreController
for (Album tempAlbum : myAlbum) {
if (tempAlbum.getGenreid().getName().equals(genreName)) <- does it even compile ? Don't think so
If you want to make it works you need to change Album entity:
package com.MVCMusicStore.Entities;
/**
* #author Gus
*
*/
import java.io.Serializable;
import java.math.BigDecimal;
import java.math.BigInteger;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* #author Gus
*/
#Entity
#Table(name = "ALBUM")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Album.findAll", query = "SELECT a FROM Album a"),
#NamedQuery(name = "Album.findByAlbumid", query = "SELECT a FROM Album a WHERE a.albumid = :albumid"),
//#NamedQuery(name = "Album.findByGenreid", query = "SELECT a FROM Album a WHERE a.genreid = :genreid"),
#NamedQuery(name = "Album.findByArtistid", query = "SELECT a FROM Album a WHERE a.artistid = :artistid"),
#NamedQuery(name = "Album.findByTitle", query = "SELECT a FROM Album a WHERE a.title = :title"),
#NamedQuery(name = "Album.findByPrice", query = "SELECT a FROM Album a WHERE a.price = :price"),
#NamedQuery(name = "Album.findByAlbumarturl", query = "SELECT a FROM Album a WHERE a.albumarturl = :albumarturl")})
public class Album implements Serializable {
private static final long serialVersionUID = 1L;
// #Max(value=?) #Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
#Id
#Basic(optional = false)
#Column(name = "ALBUMID")
private Integer albumid;
//#Column(name = "GENREID")
//private Integer genreid;
#OneToOne(cascade=CascadeType.ALL,fetch = FetchType.EAGER)
#JoinColumn(name="genreId")
private Genre genre;//Added new field with mapping to Genre
#Column(name = "ARTISTID")
private Integer artistid;
#Column(name = "TITLE")
private String title;
#Column(name = "PRICE")
private Integer price;
#Column(name = "ALBUMARTURL")
private String albumarturl;
public Album() {
}
public Album(Integer albumid) {
this.albumid = albumid;
}
public Integer getAlbumid() {
return albumid;
}
public void setAlbumid(Integer albumid) {
this.albumid = albumid;
}
//public Integer getGenreid() {
// return genreid;
//}
//public void setGenreid(Integer genreid) {
// this.genreid = genreid;
//}
public Integer getArtistid() {
return artistid;
}
public void setArtistid(Integer artistid) {
this.artistid = artistid;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Integer getPrice() {
return price;
}
public void setPrice(Integer price) {
this.price = price;
}
public String getAlbumarturl() {
return albumarturl;
}
public void setAlbumarturl(String albumarturl) {
this.albumarturl = albumarturl;
}
public Genre getGenre() {
return genre;
}
public void setGenre(Genre genre) {
this.genre = genre;
}
#Override
public int hashCode() {
int hash = 0;
hash += (albumid != null ? albumid.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 Album)) {
return false;
}
Album other = (Album) object;
if ((this.albumid == null && other.albumid != null) || (this.albumid != null && !this.albumid.equals(other.albumid))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.MVCMusicStore.Entities.Album[ albumid=" + albumid + " ]";
}
}
And then in StoreController change these lines:
for (Album tempAlbum : myAlbum) {
if (tempAlbum.getGenre().getName().equals(genreName)) <- See the changes ?
{
foundAlbum.add(tempAlbum);
}
}
Your Album entity need to have "grip" to Genre entity. If you want to do this you need to make #OneToOne between these two entities.
One more thing. When this changes are up you dont need genreId in your Album entity.

Categories