How to recover a product entity with this query below? - java

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();

Related

JPQL query with left join

I'm trying to create a JPQL query that would join two tables together and I could set up data in them.
public void uploadSaveGame(User user, String saveData)
{
EntityTransaction entr=em.getTransaction();
entr.begin();
try{
Query query = em.createQuery("UPDATE Saves s SET s.save = :saveData" +
"WHERE s.login = :user in (select sa.saveid,sa.Users.login, sa.savedata from Saves sa "
+ "LEFT JOIN sa.Users m WHERE sa.saves = m.users.saveid)", Save.class);
query.setParameter("login", user);
query.setParameter("saveData", saveData);
query.executeUpdate();
entr.commit();
}catch(Exception e){
entr.rollback();
}
}
I have this entites:
/*
* 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.dke.ps.Tables;
import java.io.Serializable;
import java.util.Collection;
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.OneToMany;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* #author michal
*/
#Entity
#Table(name = "saves")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Saves.findAll", query = "SELECT s FROM Saves s")
, #NamedQuery(name = "Saves.findBySaveid", query = "SELECT s FROM Saves s WHERE s.saveid = :saveid")
, #NamedQuery(name = "Saves.findBySavedata", query = "SELECT s FROM Saves s WHERE s.savedata = :savedata")})
public class Saves implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "saveid")
private Integer saveid;
#Column(name = "savedata")
private String savedata;
#JoinColumn(name = "userid", referencedColumnName = "userid")
#ManyToOne(optional = false)
private Users userid;
#OneToMany(mappedBy = "saveid")
private Collection<Users> usersCollection;
public Saves() {
}
public Saves(Integer saveid) {
this.saveid = saveid;
}
public Integer getSaveid() {
return saveid;
}
public void setSaveid(Integer saveid) {
this.saveid = saveid;
}
public String getSavedata() {
return savedata;
}
public void setSavedata(String savedata) {
this.savedata = savedata;
}
public Users getUserid() {
return userid;
}
public void setUserid(Users userid) {
this.userid = userid;
}
#XmlTransient
public Collection<Users> getUsersCollection() {
return usersCollection;
}
public void setUsersCollection(Collection<Users> usersCollection) {
this.usersCollection = usersCollection;
}
#Override
public int hashCode() {
int hash = 0;
hash += (saveid != null ? saveid.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 Saves)) {
return false;
}
Saves other = (Saves) object;
if ((this.saveid == null && other.saveid != null) || (this.saveid != null && !this.saveid.equals(other.saveid))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.dke.ps.Tables.Saves[ saveid=" + saveid + " ]";
}
}
And Users 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 com.dke.ps.Tables;
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.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.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* #author michal
*/
#Entity
#Table(name = "users")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Users.findAll", query = "SELECT u FROM Users u")
, #NamedQuery(name = "Users.findByUserid", query = "SELECT u FROM Users u WHERE u.userid = :userid")
, #NamedQuery(name = "Users.findByLogin", query = "SELECT u FROM Users u WHERE u.login = :login")
, #NamedQuery(name = "Users.findByPassword", query = "SELECT u FROM Users u WHERE u.password = :password")
, #NamedQuery(name = "Users.findByEmail", query = "SELECT u FROM Users u WHERE u.email = :email")
, #NamedQuery(name = "Users.findByDate", query = "SELECT u FROM Users u WHERE u.date = :date")})
public class Users implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#Column(name = "userid")
private Integer userid;
#Column(name = "login")
private String login;
#Column(name = "password")
private String password;
#Column(name = "email")
private String email;
#Column(name = "date")
#Temporal(TemporalType.DATE)
private Date date;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "userid")
private Collection<Saves> savesCollection;
#JoinColumn(name = "saveid", referencedColumnName = "saveid")
#ManyToOne
private Saves saveid;
public Users() {
}
public Users(Integer userid) {
this.userid = userid;
}
public Integer getUserid() {
return userid;
}
public void setUserid(Integer userid) {
this.userid = userid;
}
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;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
#XmlTransient
public Collection<Saves> getSavesCollection() {
return savesCollection;
}
public void setSavesCollection(Collection<Saves> savesCollection) {
this.savesCollection = savesCollection;
}
public Saves getSaveid() {
return saveid;
}
public void setSaveid(Saves saveid) {
this.saveid = saveid;
}
#Override
public int hashCode() {
int hash = 0;
hash += (userid != null ? userid.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 Users)) {
return false;
}
Users other = (Users) object;
if ((this.userid == null && other.userid != null) || (this.userid != null && !this.userid.equals(other.userid))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.dke.ps.Tables.Users[ userid=" + userid + " ]";
}
}
These two classes were automatically generated by the database connection. So, in that query, I think I should work with them and not directly with the tables in the database. It is so?
Unfortunately, I do not edit any column data, and I do not know where the problem is
My Users entity has Many To Many relationship with Saves entity.
If you printed the exception you would have probably noticed that you have a :user parameter but you are instead trying to set a login parameter
query.setParameter("login", user);

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 + " ]";
}
}

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.

JPA exception: Object: null is not a known entity type

Hi I'm new in JPA and when I want to persist object I get these errors:
java.lang.IllegalArgumentException: Object: null is not a known entity type.
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.persist(EntityManagerImpl.java:437)
at database.TarpineManager.persist(TarpineManager.java:31)
at gijos.InsertToDB.insertLink(InsertToDB.java:34)
at gijos.VilpraParser.run(VilpraParser.java:77)
There is my firs object class, which I want to do relation with other XLinksMedia class, I think problem is in
#OneToMany(mappedBy = "xParserLink", targetEntity = XLinksMedia.class, fetch=FetchType.EAGER, cascade = CascadeType.ALL)
private List<XLinksMedia> fotos;
but I do not know what is wrong:
package database.entity;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.xml.bind.annotation.XmlRootElement;
#Entity
#Table(name = "x_parser_links")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "XParserLinks.findAll", query = "SELECT x FROM XParserLinks x"),
#NamedQuery(name = "XParserLinks.findByLinkId", query = "SELECT x FROM XParserLinks x WHERE x.linkId = :linkId"),
#NamedQuery(name = "XParserLinks.findByPageId", query = "SELECT x FROM XParserLinks x WHERE x.pageId = :pageId"),
#NamedQuery(name = "XParserLinks.findByLink", query = "SELECT x FROM XParserLinks x WHERE x.link = :link"),
#NamedQuery(name = "XParserLinks.findByLevel", query = "SELECT x FROM XParserLinks x WHERE x.level = :level"),
#NamedQuery(name = "XParserLinks.findByLinkType", query = "SELECT x FROM XParserLinks x WHERE x.linkType = :linkType"),
#NamedQuery(name = "XParserLinks.findByCreateDate", query = "SELECT x FROM XParserLinks x WHERE x.createDate = :createDate"),
#NamedQuery(name = "XParserLinks.findByDelDate", query = "SELECT x FROM XParserLinks x WHERE x.delDate = :delDate")})
public class XParserLinks implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "link_id")
private Integer linkId;
#Column(name = "page_id")
private Integer pageId;
#Column(name = "link")
private String link;
#Column(name = "level")
private Integer level;
#Column(name = "link_type")
private Short linkType;
#Column(name = "create_date")
#Temporal(TemporalType.TIMESTAMP)
private Date createDate;
#Column(name = "del_date")
#Temporal(TemporalType.TIMESTAMP)
private Date delDate;
#JoinColumn(name = "tev_link_id")
#OneToOne
private XParserLinks tevas;
#OneToMany(mappedBy = "xParserLink", targetEntity = XLinksMedia.class, fetch=FetchType.EAGER, cascade = CascadeType.ALL)
private List<XLinksMedia> fotos;
public XParserLinks() {
}
public XParserLinks(Integer linkId) {
this.linkId = linkId;
}
public Integer getLinkId() {
return linkId;
}
public void setLinkId(Integer linkId) {
this.linkId = linkId;
}
public Integer getPageId() {
return pageId;
}
public void setPageId(Integer pageId) {
this.pageId = pageId;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public Integer getLevel() {
return level;
}
public void setLevel(Integer level) {
this.level = level;
}
public Short getLinkType() {
return linkType;
}
public void setLinkType(Short linkType) {
this.linkType = linkType;
}
public Date getCreateDate() {
return createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public Date getDelDate() {
return delDate;
}
public void setDelDate(Date delDate) {
this.delDate = delDate;
}
public XParserLinks getTevas() {
return tevas;
}
public void setTevas(XParserLinks tevas) {
this.tevas = tevas;
}
public List<XLinksMedia> getFotos() {
return fotos;
}
public void setFotos(List<XLinksMedia> fotos) {
this.fotos = fotos;
}
#Override
public int hashCode() {
int hash = 0;
hash += (linkId != null ? linkId.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 XParserLinks)) {
return false;
}
XParserLinks other = (XParserLinks) object;
if ((this.linkId == null && other.linkId != null) || (this.linkId != null && !this.linkId.equals(other.linkId))) {
return false;
}
return true;
}
#Override
public String toString() {
return "database.entity.XParserLinks[ linkId=" + linkId + " ]";
}
}
Second class for fotos object
package database.entity;
import java.io.Serializable;
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;
#Entity
#Table(name = "x_links_media")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "XLinksMedia.findAll", query = "SELECT x FROM XLinksMedia x"),
#NamedQuery(name = "XLinksMedia.findByLinkId", query = "SELECT x FROM XLinksMedia x WHERE x.xLinksMediaPK.linkId = :linkId"),
#NamedQuery(name = "XLinksMedia.findByImage", query = "SELECT x FROM XLinksMedia x WHERE x.xLinksMediaPK.image = :image")})
public class XLinksMedia implements Serializable {
private static final long serialVersionUID = 1L;
#EmbeddedId
protected XLinksMediaPK xLinksMediaPK;
#ManyToOne
#JoinColumn(name = "link_id")
private XParserLinks xParserLink;
public XLinksMedia() {
}
public XLinksMedia(XLinksMediaPK xLinksMediaPK) {
this.xLinksMediaPK = xLinksMediaPK;
}
public XLinksMedia(int linkId, String image) {
this.xLinksMediaPK = new XLinksMediaPK(linkId, image);
}
public XLinksMediaPK getXLinksMediaPK() {
return xLinksMediaPK;
}
public void setXLinksMediaPK(XLinksMediaPK xLinksMediaPK) {
this.xLinksMediaPK = xLinksMediaPK;
}
public XParserLinks getxParserLink() {
return xParserLink;
}
public void setxParserLink(XParserLinks xParserLink) {
this.xParserLink = xParserLink;
}
#Override
public int hashCode() {
int hash = 0;
hash += (xLinksMediaPK != null ? xLinksMediaPK.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 XLinksMedia)) {
return false;
}
XLinksMedia other = (XLinksMedia) object;
if ((this.xLinksMediaPK == null && other.xLinksMediaPK != null) || (this.xLinksMediaPK != null && !this.xLinksMediaPK.equals(other.xLinksMediaPK))) {
return false;
}
return true;
}
#Override
public String toString() {
return "database.entity.XLinksMedia[ xLinksMediaPK=" + xLinksMediaPK + " ]";
}
}
And to persist object is this method:
obj= new XParserLinks();
obj.setCreateDate(new Date());
obj.setLevel(1);
obj.setPageId(2);
obj.setLink(link);
obj.setLinkType((short) 2);
TarpineManager.startTransaction();
TarpineManager.persist(obj);
System.out.println("NAUJAS LINKAS");
TarpineManager.commitTransaction();
Just a wild guess: fotos instance variable of the entity you're trying to persist named obj is never set and therefore null. Null pointers do not seem to be a legal entity for one-to-many relations.

Categories