jpa named query using foreign key is not working - jpa

MY Entity class
#Entity
#Table(catalog = "", schema = "MYIS")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Answers.findAll", query = "SELECT a FROM Answers a"),
#NamedQuery(name = "Answers.findByAid", query = "SELECT a FROM Answers a WHERE a.aid = :aid"),
#NamedQuery(name ="Anaswers.findByqid", query ="SELECT a FROM Answers a WHERE a.answerQid.qid = :x"),
#NamedQuery(name = "Answers.findByAnsValue", query = "SELECT a FROM Answers a WHERE a.ansValue = :ansValue"),
#NamedQuery(name = "Answers.findByAnsDate", query = "SELECT a FROM Answers a WHERE a.ansDate = :ansDate")})
public class Answers implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Column(nullable = false)
private Integer aid;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 4000)
#Column(name = "ANS_VALUE", nullable = false, length = 4000)
private String ansValue;
#Basic(optional = false)
#NotNull
#Column(name = "ANS_DATE", nullable = false)
#Temporal(TemporalType.TIMESTAMP)
private Date ansDate;
#JoinColumn(name = "A_USERID", referencedColumnName = "USERID", nullable = false)
#ManyToOne(optional = false)
private Users aUserid;
#JoinColumn(name = "ANSWER_QID", referencedColumnName = "QID", nullable = false)
#ManyToOne(optional = false)
private Questions answerQid;
#JoinColumn(name = "A_GROUPID", referencedColumnName = "GID", nullable = false)
#ManyToOne(optional = false)
private Groups aGroupid;
public Answers() {
}
public Answers(Integer aid) {
this.aid = aid;
}
public Answers(Integer aid, String ansValue, Date ansDate) {
this.aid = aid;
this.ansValue = ansValue;
this.ansDate = ansDate;
}
public Integer getAid() {
return aid;
}
public void setAid(Integer aid) {
this.aid = aid;
}
public String getAnsValue() {
return ansValue;
}
public void setAnsValue(String ansValue) {
this.ansValue = ansValue;
}
public Date getAnsDate() {
return ansDate;
}
public void setAnsDate(Date ansDate) {
this.ansDate = ansDate;
}
public Users getAUserid() {
return aUserid;
}
public void setAUserid(Users aUserid) {
this.aUserid = aUserid;
}
public Questions getAnswerQid() {
return answerQid;
}
public void setAnswerQid(Questions answerQid) {
this.answerQid = answerQid;
}
public Groups getAGroupid() {
return aGroupid;
}
public void setAGroupid(Groups aGroupid) {
this.aGroupid = aGroupid;
}
#Override
public int hashCode() {
int hash = 0;
hash += (aid != null ? aid.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 Answers)) {
return false;
}
Answers other = (Answers) object;
if ((this.aid == null && other.aid != null) || (this.aid != null && !this.aid.equals(other.aid))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.entity.Answers[ aid=" + aid + " ]";
}
}
MY SESSION FACADE
import com.entity.Answers;
import com.entity.Groups;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
/**
*
* #author krishna teja
*/
#Stateless
public class AnswersFacade extends AbstractFacade<Answers> implements AnswersFacadeLocal {
#PersistenceContext(unitName = "My_communityPU")
private EntityManager em;
#Override
protected EntityManager getEntityManager() {
return em;
}
public AnswersFacade() {
super(Answers.class);
}
public List<Answers> getdataByQid(Long qid){
Query query=em.createNamedQuery("Answers.findByqid");
query.setParameter(1, qid);
List<Answers> a =query.getResultList();
return a;
}
}
My managed bean
#PostConstruct
public void init(){
questions = questionsFacade.findAll();
ansList = answersFacade.getdataByQid(g);
}
I am getting following exception
at com.ejb.AnswersFacade.getdataByQid(AnswersFacade.java:36)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
I have created named query for the foreign key attribute answerQid and and created method in the sessionfacade and tried to access it in the managed bean the default methods work perfectly but my method for query is not working please help me

Looks like a simple typo. Named query is defined as Anaswers.findByqid, but used as Answers.findByqid.

Related

JPA many to many relation: unable to insert into generated table

I have 2 entities "Entree" and "Emplacement":
#Entity
#Table(name = "ENTREE")
public class Entree {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "ID_ENTREE", updatable = false, nullable = false)
private long idEntree;
#Column(name = "NUM_DECLARATION", insertable=true, updatable=true, nullable=true)
private String numDeclaration;
#Column(name = "DATE_ENTREE", insertable=true, updatable=true, nullable=true)
private String dateEntree;
#Column(name = "TYPE_ENTREE", insertable=true, updatable=true, nullable=true)
private String typeEntree;
#Column(name = "NOM_ARTICLE", insertable=true, updatable=true, nullable=true)
private String nomArticle;
#Column(name = "TYPE_ARTICLE", insertable=true, updatable=true, nullable=true)
private String typeArticle;
#Column(name = "QUANTITE_ENTREE", insertable=true, updatable=true, nullable=true)
private int quantiteEntree;
#ManyToOne
#JoinColumn(name="idDossier", nullable=false)
private Dossier dossier;
#ManyToMany( fetch = FetchType.LAZY, cascade = CascadeType.PERSIST)
#JoinTable(name = "entree_emplacement",
joinColumns = {
#JoinColumn(name = "id_entree", referencedColumnName = "id_entree",
nullable = false, updatable = false)},
inverseJoinColumns = {
#JoinColumn(name = "id_emplacement", referencedColumnName = "id_emplacement",
nullable = false, updatable = false)})
private Set<Emplacement> emplacement = new HashSet<>();
public Entree() {
super();
}
public Entree( String numDeclaration, String dateEntree, String typeEntree, String nomArticle, String typeArticle, int quantiteEntree, boolean isDone) {
super();
this.numDeclaration = numDeclaration;
this.dateEntree = dateEntree;
this.typeEntree = typeEntree;
this.nomArticle = nomArticle;
this.typeArticle = typeArticle;
this.quantiteEntree = quantiteEntree;
}
public long getIdEntree() {
return idEntree;
}
public void setIdEntree(long idEntree) {
this.idEntree = idEntree;
}
public String getNumDeclaration() {
return numDeclaration;
}
public void setNumDeclaration(String numDeclaration) {
this.numDeclaration = numDeclaration;
}
public String getDateEntree() {
return dateEntree;
}
public void setDateEntree(String dateEntree) {
this.dateEntree = dateEntree;
}
public String getTypeEntree() {
return typeEntree;
}
public void setTypeEntree(String typeEntree) {
this.typeEntree = typeEntree;
}
public String getNomArticle() {
return nomArticle;
}
public void setNomArticle(String nomArticle) {
this.nomArticle = nomArticle;
}
public String getTypeArticle() {
return typeArticle;
}
public void setTypeArticle(String typeArticle) {
this.typeArticle = typeArticle;
}
public int getQuantiteEntree() {
return quantiteEntree;
}
public void setQuantiteEntree(int quantiteEntree) {
this.quantiteEntree = quantiteEntree;
}
public Dossier getDossier() {
return dossier;
}
public void setDossier(Dossier dossier) {
this.dossier = dossier;
}
public Set<Emplacement> getEmplacements() {
return emplacement;
}
public void addEmplacement(Emplacement emplacement) {
this.emplacement.add(emplacement);
emplacement.getEntrees().add(this);
}
public void removeEmplacement(Emplacement emplacement) {
this.emplacement.remove(emplacement);
emplacement.getEntrees().remove(this);
}
}
And here the second entity:
#Entity
#Table(name = "EMPLACEMENT")
public class Emplacement {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "ID_EMPLACEMENT", updatable = false, nullable = false)
private long idEmplacement;
#Column(name = "NUM_EMPLACEMENT", insertable=true, updatable=true, nullable=false)
private String numEmplacement;
#ManyToMany(mappedBy = "emplacement", fetch = FetchType.LAZY, cascade = {CascadeType.ALL})
private Set<Entree> entree = new HashSet<>();
public Emplacement() {
}
public Emplacement( String numEmplacement) {
this.numEmplacement = numEmplacement;
}
public long getIdEmplacement() {
return idEmplacement;
}
public void setIdEmplacement(long idEmplacement) {
this.idEmplacement = idEmplacement;
}
public String getNumEmplacement() {
return numEmplacement;
}
public void setNumEmplacement(String numEmplacement) {
this.numEmplacement = numEmplacement;
}
public Set<Entree> getEntrees() {
return entree;
}
}
Here is my inserting code:
#PostMapping("/ajouterEntree")
public ResponseEntity<String> addEntree(#Valid Entree entree, BindingResult result,ModelMap modelMap, #RequestParam(name = "numDossier") String numDossier, #RequestParam(name = "emplacement") String liste_emplacements) {
Emplacement e = new Emplacement(liste_emplacements);
entree.getEmplacements().add(e);
entreeService.saveEntree(entree);
return new ResponseEntity<String>("ok" + result, HttpStatus.OK);
}
I am able to insert datas into Entree and Emplacement tables, but the third generated table named entree-emplacement is empty.
So how can I insert datas into generated table in #ManyToMany relation?
Thanks
Ok it's resolved. Here is my code:
if(!liste_emplacements.equals(""))
{
List<String> list = new ArrayList<String>(Arrays.asList(liste_emplacements.split(",")));
Emplacement[] emp = new Emplacement[list.size()];
for (int i=0; i<list.size() ;i++)
{
emp[i] = new Emplacement(Long.parseLong(list.get(i)));
entree.getEmplacements().add(emp[i]);
emp[i].getEntrees().add(entree);
}
}
entreeService.saveEntree(entree);
return new ResponseEntity<String>("ok" + result, HttpStatus.OK);

Rest API order by name

I'm trying to create my own REST API and I'm having trouble trying to order my data by name. currently, I am able to display all the data from the styles table, however, I wish to sort them alphabetically.
I was able to do a filter by extracting the year from the date and checking if that was in the database, this is shown in
public List<Beers> getAllBeersByYear(int year) {
EntityManager em = DBUtil.getEMF().createEntityManager();
List<Beers> list = null;
List<Beers> beersToRemove = new ArrayList<>();
try {
list = em.createNamedQuery("Beers.findAll", Beers.class)
.getResultList();
if (list == null || list.isEmpty()) {
list = null;
}
} finally {
em.close();
}
Calendar cal = Calendar.getInstance();
for (Beers beer : list) {
cal.setTime(beer.getLastMod());
if (cal.get(Calendar.YEAR) != year) {
beersToRemove.add(beer);
}
}
list.removeAll(beersToRemove);
return list;
}
the controller is
#GetMapping(produces=MediaType.APPLICATION_JSON_VALUE)
public List<Styles> GetAllStyles() {
return service.getAllStyles();
}
would it be possible to do something similar to the service and controller where instead of filtering the data, it can sort by the name of a column
the service is
public List<Styles> getAllStyles() {
EntityManager em = DBUtil.getEMF().createEntityManager();
List<Styles> list = null;
try {
list = em.createNamedQuery("Styles.findAll", Styles.class)
.getResultList();
if (list == null || list.isEmpty()) {
list = null;
}
} finally {
em.close();
}
return list;
}
the JPA I am using is
#Entity
#Table(name = "styles")
#NamedQueries({
#NamedQuery(name = "Styles.findAll", query = "SELECT s FROM Styles s"),
#NamedQuery(name = "Styles.findById", query = "SELECT s FROM Styles s WHERE s.id = :id"),
#NamedQuery(name = "Styles.findByCatId", query = "SELECT s FROM Styles s WHERE s.catId = :catId"),
#NamedQuery(name = "Styles.findByStyleName", query = "SELECT s FROM Styles s WHERE s.styleName = :styleName"),
#NamedQuery(name = "Styles.findByLastMod", query = "SELECT s FROM Styles s WHERE s.lastMod = :lastMod")})
public class Styles implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Basic(optional = false)
#NotNull
#Column(name = "cat_id")
private int catId;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 255)
#Column(name = "style_name")
private String styleName;
#Basic(optional = false)
#NotNull
#Column(name = "last_mod")
#Temporal(TemporalType.TIMESTAMP)
private Date lastMod;
public Styles() {
}
public Styles(Integer id) {
this.id = id;
}
public Styles(Integer id, int catId, String styleName, Date lastMod) {
this.id = id;
this.catId = catId;
this.styleName = styleName;
this.lastMod = lastMod;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public int getCatId() {
return catId;
}
public void setCatId(int catId) {
this.catId = catId;
}
public String getStyleName() {
return styleName;
}
public void setStyleName(String styleName) {
this.styleName = styleName;
}
public Date getLastMod() {
return lastMod;
}
public void setLastMod(Date lastMod) {
this.lastMod = lastMod;
}
#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 Styles)) {
return false;
}
Styles other = (Styles) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "Service.Styles[ id=" + id + " ]";
}
}
You can use #OrderBy annotation
https://www.logicbig.com/tutorials/java-ee-tutorial/jpa/order-by-annotation.html
Just create another query:
#NamedQuery(name = "Styles.findAll", query = "SELECT s FROM Styles s ORDER BY s.name")
And why are you filtering in the code when you can add a query with a where condition?

Why JPA doesnt generate a join junction table in this case

I have two tables Students and Books , with a many to many relationship. The code of both are given below. Now when I try to run the code I get the error.
Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'acme.book_stud' doesn't exist
Error Code: 1146
Call: INSERT INTO book_stud (idStudents, idBooks) VALUES (?, ?)
bind => [2 parameters bound]
It seems like JPA is trying to write to a juction table which does not exist (in this case it assumes a junction table books_students is already created so it doesnt create one.). It works if I create a books_students but I dont want to do that since its JPA responsibility to create it. Is there a way in which I could explicitly tell it to create one. ? (I am taking a wild guess here - but I guess when creating a persitance unit I specified "none" I think thats why it didnt create that table . Am I correct ? Anyways here are my Student and Books Classes
BOOKS CLASS
#Entity
#Table(name = "books")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Books.findAll", query = "SELECT b FROM Books b"),
#NamedQuery(name = "Books.findByIdBooks", query = "SELECT b FROM Books b WHERE b.idBooks = :idBooks"),
#NamedQuery(name = "Books.findByBookName", query = "SELECT b FROM Books b WHERE b.bookName = :bookName"),
#NamedQuery(name = "Books.findByBookType", query = "SELECT b FROM Books b WHERE b.bookType = :bookType")})
public class Books implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 45)
#Column(name = "idBooks")
private String idBooks;
#Size(max = 45)
#Column(name = "BookName")
private String bookName;
#Size(max = 45)
#Column(name = "BookType")
private String bookType;
/******************************************ADDED **********************/
#ManyToMany
#JoinTable(name = "book_stud",
joinColumns = { #JoinColumn(name = "idStudents") },
inverseJoinColumns = { #JoinColumn(name = "idBooks") })
/**************************************ENDED*****************************/
public Books() {
}
public Books(String idBooks) {
this.idBooks = idBooks;
}
public String getIdBooks() {
return idBooks;
}
public void setIdBooks(String idBooks) {
this.idBooks = idBooks;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public String getBookType() {
return bookType;
}
public void setBookType(String bookType) {
this.bookType = bookType;
}
#Override
public int hashCode() {
int hash = 0;
hash += (idBooks != null ? idBooks.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 Books)) {
return false;
}
Books other = (Books) object;
if ((this.idBooks == null && other.idBooks != null) || (this.idBooks != null && !this.idBooks.equals(other.idBooks))) {
return false;
}
return true;
}
#Override
public String toString() {
return "domain.Books[ idBooks=" + idBooks + " ]";
}
}
STUDENT CLASS
#Entity
#Table(name = "students")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "StudentEnroll.findAll", query = "SELECT s FROM StudentEnroll s"),
#NamedQuery(name = "StudentEnroll.findByIdStudents", query = "SELECT s FROM StudentEnroll s WHERE s.idStudents = :idStudents"),
#NamedQuery(name = "StudentEnroll.findByName", query = "SELECT s FROM StudentEnroll s WHERE s.name = :name"),
#NamedQuery(name = "StudentEnroll.findByRoll", query = "SELECT s FROM StudentEnroll s WHERE s.roll = :roll"),
#NamedQuery(name = "StudentEnroll.findBySsn", query = "SELECT s FROM StudentEnroll s WHERE s.ssn = :ssn"),
#NamedQuery(name = "StudentEnroll.findByProgram", query = "SELECT s FROM StudentEnroll s WHERE s.program = :program")})
public class StudentEnroll implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 40)
#Column(name = "idStudents")
private String idStudents;
#Size(max = 45)
#Column(name = "Name")
private String name;
#Column(name = "Roll")
private Integer roll;
#Column(name = "SSN")
private Integer ssn;
#Size(max = 45)
#Column(name = "Program")
private String program;
#JoinColumn(name = "CustomerID", referencedColumnName = "UserID")
#ManyToOne
private Customer customerID;
//#OneToMany(mappedBy = "studentRoll")
#OneToMany(mappedBy = "studentRoll",cascade = CascadeType.REMOVE)//added REMOVE
private Collection<Subject> subjectCollection;
/**************************ADDED*****************************/
#ManyToMany
#JoinTable(name = "book_stud",
joinColumns = { #JoinColumn(name = "idBooks") },
inverseJoinColumns = { #JoinColumn(name = "idStudents") })
/**********************************END**********************/
public StudentEnroll() {
}
public StudentEnroll(String idStudents) {
this.idStudents = idStudents;
}
public String getIdStudents() {
return idStudents;
}
public void setIdStudents(String idStudents) {
this.idStudents = idStudents;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getRoll() {
return roll;
}
public void setRoll(Integer roll) {
this.roll = roll;
}
public Integer getSsn() {
return ssn;
}
public void setSsn(Integer ssn) {
this.ssn = ssn;
}
public String getProgram() {
return program;
}
public void setProgram(String program) {
this.program = program;
}
public Customer getCustomerID() {
return customerID;
}
public void setCustomerID(Customer customerID) {
this.customerID = customerID;
}
#XmlTransient
public Collection<Subject> getSubjectCollection() {
return subjectCollection;
}
public void setSubjectCollection(Collection<Subject> subjectCollection) {
this.subjectCollection = subjectCollection;
}
#Override
public int hashCode() {
int hash = 0;
hash += (idStudents != null ? idStudents.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 StudentEnroll)) {
return false;
}
StudentEnroll other = (StudentEnroll) object;
if ((this.idStudents == null && other.idStudents != null) || (this.idStudents != null && !this.idStudents.equals(other.idStudents))) {
return false;
}
return true;
}
#Override
public String toString() {
return "domain.StudentEnroll[ idStudents=" + idStudents + " ]";
}
}

how to start from "0" an UNSIGNED AUTO_INCREMENT field?

I have the following tables :
wherein idclient is unsigned auto_increment.
code of the Client entity:
import java.io.Serializable;
import java.util.List;
import javax.persistence.*;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
#Entity
#Table(name = "CLIENT", catalog = "TEST", schema = "PUBLIC")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Client.findAll", query = "SELECT c FROM Client c"),
#NamedQuery(name = "Client.findByIdclient", query = "SELECT c FROM Client c WHERE c.idclient = :idclient"),
#NamedQuery(name = "Client.findByLibel", query = "SELECT c FROM Client c WHERE c.libel = :libel"),
#NamedQuery(name = "Client.findByAdresse", query = "SELECT c FROM Client c WHERE c.adresse = :adresse"),
#NamedQuery(name = "Client.findByNomResp", query = "SELECT c FROM Client c WHERE c.nomResp = :nomResp"),
#NamedQuery(name = "Client.findByTelPortable", query = "SELECT c FROM Client c WHERE c.telPortable = :telPortable"),
#NamedQuery(name = "Client.findByTelFixe", query = "SELECT c FROM Client c WHERE c.telFixe = :telFixe"),
#NamedQuery(name = "Client.findByFax", query = "SELECT c FROM Client c WHERE c.fax = :fax"),
#NamedQuery(name = "Client.findByCodeTva", query = "SELECT c FROM Client c WHERE c.codeTva = :codeTva"),
#NamedQuery(name = "Client.findByCodeExo", query = "SELECT c FROM Client c WHERE c.codeExo = :codeExo"),
#NamedQuery(name = "Client.findByBanque", query = "SELECT c FROM Client c WHERE c.banque = :banque"),
#NamedQuery(name = "Client.findByRib", query = "SELECT c FROM Client c WHERE c.rib = :rib"),
#NamedQuery(name = "Client.findByCredit", query = "SELECT c FROM Client c WHERE c.credit = :credit"),
#NamedQuery(name = "Client.findByEchance", query = "SELECT c FROM Client c WHERE c.echance = :echance"),
#NamedQuery(name = "Client.findByMail", query = "SELECT c FROM Client c WHERE c.mail = :mail"),
#NamedQuery(name = "Client.findByEtat", query = "SELECT c FROM Client c WHERE c.etat = :etat")})
public class Client implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "IDCLIENT", nullable = false)
private Integer idclient;
#Basic(optional = false)
#Column(name = "LIBEL", nullable = false, length = 100)
private String libel;
#Basic(optional = false)
#Column(name = "ADRESSE", nullable = false, length = 100)
private String adresse;
#Basic(optional = false)
#Column(name = "NOM_RESP", nullable = false, length = 60)
private String nomResp;
#Basic(optional = false)
#Column(name = "TEL_PORTABLE", nullable = false, length = 16)
private String telPortable;
#Basic(optional = false)
#Column(name = "TEL_FIXE", nullable = false, length = 16)
private String telFixe;
#Basic(optional = false)
#Column(name = "FAX", nullable = false, length = 16)
private String fax;
#Basic(optional = false)
#Column(name = "CODE_TVA", nullable = false, length = 30)
private String codeTva;
#Basic(optional = false)
#Column(name = "CODE_EXO", nullable = false, length = 30)
private String codeExo;
#Basic(optional = false)
#Column(name = "BANQUE", nullable = false, length = 60)
private String banque;
#Basic(optional = false)
#Column(name = "RIB", nullable = false, length = 22)
private String rib;
#Basic(optional = false)
#Column(name = "CREDIT", nullable = false)
private double credit;
#Basic(optional = false)
#Column(name = "ECHANCE", nullable = false)
private int echance;
#Basic(optional = false)
#Column(name = "MAIL", nullable = false, length = 70)
private String mail;
#Basic(optional = false)
#Column(name = "ETAT", nullable = false)
private char etat;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "clientIdclient")
private List<Facture> factureList;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "clientIdclient")
private List<FactProforma> factProformaList;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "clientIdclient")
private List<Bl> blList;
public Client() {
}
public Client(Integer idclient) {
this.idclient = idclient;
}
public Client(Integer idclient, String libel, String adresse, String nomResp, String telPortable, String telFixe, String fax, String codeTva, String codeExo, String banque, String rib, double credit, int echance, String mail, char etat) {
this.idclient = idclient;
this.libel = libel;
this.adresse = adresse;
this.nomResp = nomResp;
this.telPortable = telPortable;
this.telFixe = telFixe;
this.fax = fax;
this.codeTva = codeTva;
this.codeExo = codeExo;
this.banque = banque;
this.rib = rib;
this.credit = credit;
this.echance = echance;
this.mail = mail;
this.etat = etat;
}
public Integer getIdclient() {
return idclient;
}
public void setIdclient(Integer idclient) {
this.idclient = idclient;
}
public String getLibel() {
return libel;
}
public void setLibel(String libel) {
this.libel = libel;
}
public String getAdresse() {
return adresse;
}
public void setAdresse(String adresse) {
this.adresse = adresse;
}
public String getNomResp() {
return nomResp;
}
public void setNomResp(String nomResp) {
this.nomResp = nomResp;
}
public String getTelPortable() {
return telPortable;
}
public void setTelPortable(String telPortable) {
this.telPortable = telPortable;
}
public String getTelFixe() {
return telFixe;
}
public void setTelFixe(String telFixe) {
this.telFixe = telFixe;
}
public String getFax() {
return fax;
}
public void setFax(String fax) {
this.fax = fax;
}
public String getCodeTva() {
return codeTva;
}
public void setCodeTva(String codeTva) {
this.codeTva = codeTva;
}
public String getCodeExo() {
return codeExo;
}
public void setCodeExo(String codeExo) {
this.codeExo = codeExo;
}
public String getBanque() {
return banque;
}
public void setBanque(String banque) {
this.banque = banque;
}
public String getRib() {
return rib;
}
public void setRib(String rib) {
this.rib = rib;
}
public double getCredit() {
return credit;
}
public void setCredit(double credit) {
this.credit = credit;
}
public int getEchance() {
return echance;
}
public void setEchance(int echance) {
this.echance = echance;
}
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
public char getEtat() {
return etat;
}
public void setEtat(char etat) {
this.etat = etat;
}
#XmlTransient
public List<Facture> getFactureList() {
return factureList;
}
public void setFactureList(List<Facture> factureList) {
this.factureList = factureList;
}
#XmlTransient
public List<FactProforma> getFactProformaList() {
return factProformaList;
}
public void setFactProformaList(List<FactProforma> factProformaList) {
this.factProformaList = factProformaList;
}
#XmlTransient
public List<Bl> getBlList() {
return blList;
}
public void setBlList(List<Bl> blList) {
this.blList = blList;
}
#Override
public int hashCode() {
int hash = 0;
hash += (idclient != null ? idclient.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 Client)) {
return false;
}
Client other = (Client) object;
if ((this.idclient == null && other.idclient != null) || (this.idclient != null && !this.idclient.equals(other.idclient))) {
return false;
}
return true;
}
#Override
public String toString() {
return "glob.entitys.Client[ idclient=" + idclient + " ]";
}
}
when I try to insert a row into the data base :
Utilisateur user=new Utilisateur(loginActuel);
Client client=new Client(0);// the error comes from here
Facture fact=new Facture(null,new Date());
fact.setClientIdclient(client);
fact.setUtilisateurLogin(user);
FactureJpaController fjc=new FactureJpaController(emf);
fjc.create(fact);
I get this ugly error(but when i set new Client(1) it works well):
Exception in thread "AWT-EventQueue-0" javax.persistence.RollbackException: Exception [EclipseLink-7197] (Eclipse Persistence Services - 2.3.0.v20110604-r9504): org.eclipse.persistence.exceptions.ValidationException
Exception Description: Null or zero primary key encountered in unit of work clone [glob.entitys.Client[ idclient=0 ]], primary key [0]. Set descriptors IdValidation or the "eclipselink.id-validation" property.
how to solve this problem ?
remark: the client idclient = 0 is already inserted in the Database(but manually)
I'd like once and for all overcome this "problem" , how to prevent JPA or H2 Database to start from 0 ?
H2 does allow to use 0 as the primary key. The error message doesn't come from H2.
However, it seems to me that some (older?) version of EclipseLink doesn't allow to use 0.
the client idclient = 0 is already inserted in the Database
It seems this is not supported by this version of EclipseLink. It looks like to work around this problem, you should not use the value 0.
There are two ways how to allow zeroes in primary keys in Eclipselink:
Parameter in persistence.xml:
<property name="eclipselink.id-validation" value="NULL"/>
PrimaryKey annotation on concerned entity class:
#PrimaryKey(validation = IdValidation.NULL)
For JPA (specification 2.0) having (or negative) value for id is fine. And also as primary key value for H2.
Older versions of EclipseLink do consider value 0 or smaller as invalid primary key. See for example following:Bug 249948. So updating EclipseLink can help.
By the way, why you do set in constructor value for idclient that is supposed to be generated?
I had this error and adding the following annotations to my jpa identity resolved it:
#Column(name = "ID_SEARCH_LOG", nullable = false, insertable = true, updatable = true, length = 10, precision = 0)
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int idSearchLog;
The docs say
By default, EclipseLink interprets zero as null for primitive types that cannot be null (such as int and long) causing zero to be an invalid value for primary keys.
but also that that it is possible to change this behaviour in either the persistence.xml or on a particular entity.
http://wiki.eclipse.org/EclipseLink/UserGuide/JPA/Basic_JPA_Development/Entities/Ids/Id#Allowing_Zero_Value_Primary_Keys

EclipseLink GeneratedValue null on postgres only on one entity

I have a rather weird case. I have some entities generated with netbeans and i can persist all except one. I see no difference in the database nor in the entity class. Can someone help me, here is my entity class , database, and error that i am receiving
CREATE TABLE objekat
(
id_objekat bigserial NOT NULL,
id_opstina serial NOT NULL,
naziv character varying(50) NOT NULL,
kapacitet character varying(50),
adresa character varying(100),
lokacija_sirina double precision,
lokacija_duzina double precision,
opis character varying(500),
korisnicko_ime character varying(50),
sifra character varying(50),
maks_broj_slike integer,
absolute_path_logo character varying(255),
CONSTRAINT objekat_pkey PRIMARY KEY (id_objekat),
CONSTRAINT fkobjekat924176 FOREIGN KEY (id_opstina)
REFERENCES opstina (id_opstina) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
)
WITH (
OIDS=FALSE
);
and this is my entity bean.
#Entity
#Table(name = "objekat")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Objekat.findAll", query = "SELECT o FROM Objekat o"),
#NamedQuery(name = "Objekat.findByIdObjekat", query = "SELECT o FROM Objekat o WHERE o.idObjekat = :idObjekat"),
#NamedQuery(name = "Objekat.findByNaziv", query = "SELECT o FROM Objekat o WHERE upper (o.naziv) like upper(:naziv)"),
#NamedQuery(name = "Objekat.findByNazivAndOpstina", query = "SELECT o FROM Objekat o inner join o.idOpstina op WHERE upper (o.naziv) like upper(:naziv) and op.idOpstina = :idOpstina"),
#NamedQuery(name = "Objekat.findByKapacitet", query = "SELECT o FROM Objekat o WHERE o.kapacitet = :kapacitet"),
#NamedQuery(name = "Objekat.findByAdresa", query = "SELECT o FROM Objekat o WHERE o.adresa = :adresa"),
#NamedQuery(name = "Objekat.findByLokacijaSirina", query = "SELECT o FROM Objekat o WHERE o.lokacijaSirina = :lokacijaSirina"),
#NamedQuery(name = "Objekat.findByLokacijaDuzina", query = "SELECT o FROM Objekat o WHERE o.lokacijaDuzina = :lokacijaDuzina")})
public class Objekat implements Serializable {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id_objekat",columnDefinition = "BIGSERIAL")
private Long idObjekat;
#Size(max = 255)
#Column(name = "absolute_path_logo")
private String absolutePathLogo;
#OneToMany( mappedBy = "objekatidObjekat")
private List<DogadjajObjekat> dogadjajObjekatList;
#OneToMany( mappedBy = "objekatidObjekat")
private List<SlikeLokacijaObjekat> slikeLokacijaObjekatList;
#OneToMany( mappedBy = "idObjekat")
private List<RasporedObjekat> rasporedObjekatList;
#Column(name = "maks_broj_slike")
private Integer maksBrojSlike;
#Size(max = 50)
#Column(name = "korisnicko_ime")
private String korisnickoIme;
#Size(max = 50)
#Column(name = "sifra")
private String sifra;
#Size(max = 500)
#Column(name = "opis")
private String opis;
// #Max(value=?) #Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
#Column(name = "lokacija_sirina")
private Double lokacijaSirina;
#Column(name = "lokacija_duzina")
private Double lokacijaDuzina;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 50)
#Column(name = "naziv")
private String naziv;
#Size(max = 50)
#Column(name = "kapacitet")
private String kapacitet;
#Size(max = 100)
#Column(name = "adresa")
private String adresa;
#JoinTable(name = "tip_objekta_objekat", joinColumns = {
#JoinColumn(name = "objekatid_objekat", referencedColumnName = "id_objekat")}, inverseJoinColumns = {
#JoinColumn(name = "tip_objektaid_tip_objekta", referencedColumnName = "id_tip_objekta")})
#ManyToMany
private List<TipObjekta> tipObjektaList;
#JoinColumn(name = "id_opstina", referencedColumnName = "id_opstina")
#ManyToOne(optional = false)
private Opstina idOpstina;
public Objekat() {
}
public Objekat(Long idObjekat) {
this.idObjekat = idObjekat;
}
public Objekat(Long idObjekat, String naziv) {
this.idObjekat = idObjekat;
this.naziv = naziv;
}
public Long getIdObjekat() {
return idObjekat;
}
public void setIdObjekat(Long idObjekat) {
this.idObjekat = idObjekat;
}
public String getNaziv() {
return naziv;
}
public void setNaziv(String naziv) {
this.naziv = naziv;
}
public String getKapacitet() {
return kapacitet;
}
public void setKapacitet(String kapacitet) {
this.kapacitet = kapacitet;
}
public String getAdresa() {
return adresa;
}
public void setAdresa(String adresa) {
this.adresa = adresa;
}
#XmlTransient
public List<TipObjekta> getTipObjektaList() {
return tipObjektaList;
}
public void setTipObjektaList(List<TipObjekta> tipObjektaList) {
this.tipObjektaList = tipObjektaList;
}
public Opstina getIdOpstina() {
return idOpstina;
}
public void setIdOpstina(Opstina idOpstina) {
this.idOpstina = idOpstina;
}
#Override
public int hashCode() {
int hash = 0;
hash += (idObjekat != null ? idObjekat.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 Objekat)) {
return false;
}
Objekat other = (Objekat) object;
if ((this.idObjekat == null && other.idObjekat != null) || (this.idObjekat != null && !this.idObjekat.equals(other.idObjekat))) {
return false;
}
return true;
}
#Override
public String toString() {
return "rs.dzetSet.entiteti.Objekat[ idObjekat=" + idObjekat + " ]";
}
public String getOpis() {
return opis;
}
public void setOpis(String opis) {
this.opis = opis;
}
public Double getLokacijaSirina() {
return lokacijaSirina;
}
public void setLokacijaSirina(Double lokacijaSirina) {
this.lokacijaSirina = lokacijaSirina;
}
public Double getLokacijaDuzina() {
return lokacijaDuzina;
}
public void setLokacijaDuzina(Double lokacijaDuzina) {
this.lokacijaDuzina = lokacijaDuzina;
}
public String getKorisnickoIme() {
return korisnickoIme;
}
public void setKorisnickoIme(String korisnickoIme) {
this.korisnickoIme = korisnickoIme;
}
public String getSifra() {
return sifra;
}
public void setSifra(String sifra) {
this.sifra = sifra;
}
public Integer getMaksBrojSlike() {
return maksBrojSlike;
}
public void setMaksBrojSlike(Integer maksBrojSlike) {
this.maksBrojSlike = maksBrojSlike;
}
public void pocevajMaksBrojSlike(){
this.maksBrojSlike++;
}
public String getAbsolutePathLogo() {
return absolutePathLogo;
}
public void setAbsolutePathLogo(String absolutePathLogo) {
this.absolutePathLogo = absolutePathLogo;
}
#XmlTransient
public List<RasporedObjekat> rasporedObjekatListPrePodne(){
List<RasporedObjekat> rez = new ArrayList<RasporedObjekat>();
if(rasporedObjekatList==null){
rasporedObjekatList = new ArrayList<RasporedObjekat>();
}
for(RasporedObjekat ro:rasporedObjekatList){
if(!ro.getVecernjiProgram()){
rez.add(ro);
}
}
return rez;
}
#XmlTransient
public List<RasporedObjekat> rasporedObjekatListPoslePodne(){
List<RasporedObjekat> rez = new ArrayList<RasporedObjekat>();
if(rasporedObjekatList==null){
rasporedObjekatList = new ArrayList<RasporedObjekat>();
}
for(RasporedObjekat ro:rasporedObjekatList){
if(ro.getVecernjiProgram()){
rez.add(ro);
}
}
return rez;
}
#XmlTransient
public List<DogadjajObjekat> getDogadjajObjekatList() {
return dogadjajObjekatList;
}
public void setDogadjajObjekatList(List<DogadjajObjekat> dogadjajObjekatList) {
this.dogadjajObjekatList = dogadjajObjekatList;
}
#XmlTransient
public List<SlikeLokacijaObjekat> getSlikeLokacijaObjekatList() {
return slikeLokacijaObjekatList;
}
public void setSlikeLokacijaObjekatList(List<SlikeLokacijaObjekat> slikeLokacijaObjekatList) {
this.slikeLokacijaObjekatList = slikeLokacijaObjekatList;
}
#XmlTransient
public List<RasporedObjekat> getRasporedObjekatList() {
return rasporedObjekatList;
}
public void setRasporedObjekatList(List<RasporedObjekat> rasporedObjekatList) {
this.rasporedObjekatList = rasporedObjekatList;
}
and i persist it in a rather normal way, or i just think so.
utx.begin();
if(noviObjekat.getIdObjekat() == null){
em.persist(noviObjekat);
}else{
em.merge(noviObjekat);
}
utx.commit();
and i get a pretty weird error
Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.3.0.v20110604-r9504): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: org.postgresql.util.PSQLException: ERROR: null value in column "id_opstina" violates not-null constraint
Error Code: 0
Call: INSERT INTO objekat (absolute_path_logo, adresa, kapacitet, korisnicko_ime, lokacija_duzina, lokacija_sirina, maks_broj_slike, naziv, opis, sifra, id_opstina) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
bind => [11 parameters bound]
Query: InsertObjectQuery(rs.dzetSet.entiteti.Objekat[ idObjekat=null ])
}
You set a generator on the field for "id_objekat" but the exception is for the not-null constraint on "id_opstina". You will need to set this field yourself or use a returning policy to get it instead:
http://wiki.eclipse.org/Using_EclipseLink_JPA_Extensions_(ELUG)#Using_EclipseLink_JPA_Extensions_for_Returning_Policy