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