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