I have a problem. I made a dynamic web project using JPA, named queries and a Web Servlet. Here is how the project is organized:
enter image description here
Here are the classes:
Auto.java:
package it.ecipar.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class Auto {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String marca, modello;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getMarca() {
return marca;
}
public void setMarca(String marca) {
this.marca = marca;
}
public String getModello() {
return modello;
}
public void setModello(String modello) {
this.modello = modello;
}
}
Hobby.java:
package it.ecipar.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class Hobby {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String nome;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
}
Luogo.java:
package it.ecipar.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class Luogo {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String nome;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
}
Persona.java:
package it.ecipar.model;
import java.util.Date;
import java.util.List;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
#NamedQueries({
#NamedQuery(name="persona.lista", query="SELECT o from it.ecipar.model.Persona o ORDER by p.cognome, p.nome")
})
#Entity
public class Persona {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String nome, cognome;
private Date dataDiNascita;
#OneToMany
private List<Auto> auto;
#ManyToMany
private List<Hobby> hobby;
#ManyToOne
private Luogo luogoDiNascita;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getCognome() {
return cognome;
}
public void setCognome(String cognome) {
this.cognome = cognome;
}
public List<Auto> getAuto() {
return auto;
}
public void setAuto(List<Auto> auto) {
this.auto = auto;
}
public List<Hobby> getHobby() {
return hobby;
}
public void setHobby(List<Hobby> hobby) {
this.hobby = hobby;
}
public Luogo getLuogoDiNascita() {
return luogoDiNascita;
}
public void setLuogoDiNascita(Luogo luogoDiNascita) {
this.luogoDiNascita = luogoDiNascita;
}
public Date getDataDiNascita() {
return dataDiNascita;
}
public void setDataDiNascita(Date dataDiNascita) {
this.dataDiNascita = dataDiNascita;
}
}
JPAUtil.java:
package it.ecipar.common;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
public class JPAUtil {
private static EntityManagerFactory emf;
private EntityManager em;
public JPAUtil() {
if (emf == null) {
emf = Persistence.createEntityManagerFactory("MyProject");
}
em = emf.createEntityManager();
}
public Object insert(Object o) {
em.getTransaction().begin();
em.persist(o);
em.getTransaction().commit();
return o;
}
public Object update(Object o) {
em.getTransaction().begin();
Object res = em.merge(o);
em.getTransaction().commit();
return res;
}
public void delete(Object o) {
em.getTransaction().begin();
em.remove(em.contains(o) ? o : em.merge(o));
em.getTransaction().commit();
}
public Object load(Class<?> c, Integer id) {
return em.find(c, id);
}
public List<?> runNamedQuery(String name, HashMap<String, Object> params) {
Query query = em.createNamedQuery(name);
if (params != null) {
Set<String> keys = params.keySet();
for (String k : keys) {
query.setParameter(k, params.get(k));
}
}
return query.getResultList();
}
public Query createQuery(String q) {
return em.createQuery(q);
}
public void close() {
em.close();
}
public void closeFactory() {
emf.close();
}
}
Demo.java:
package it.ecipar.common;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;
import it.ecipar.model.Auto;
import it.ecipar.model.Hobby;
import it.ecipar.model.Luogo;
import it.ecipar.model.Persona;
public class Demo {
public static void main(String[] args) {
JPAUtil u = new JPAUtil();
for(int i = 0; i < 10; i++) {
save(u, i, i + 1);
}
u.close();
u.closeFactory();
}
public static void save(JPAUtil u, int i, int numAuto) {
Luogo l = new Luogo();
l.setNome("nome luogo " + i);
u.insert(l);
List<Hobby> listaHobby = new ArrayList<>();
Hobby h = new Hobby();
h.setNome("nome hobby " + i);
u.insert(h);
listaHobby.add(h);
List<Auto> listaAuto = new ArrayList<>();
for (int j = i; j < i + numAuto; j++) {
Auto a = new Auto();
a.setMarca("marca " + j);
a.setModello("modello " + j);
u.insert(a);
listaAuto.add(a);
}
Calendar cal = GregorianCalendar.getInstance();
cal.add(Calendar.YEAR, -20 * i);
Persona p = new Persona();
p.setNome("nome " + i);
p.setCognome("cognome " + i);
p.setDataDiNascita(cal.getTime());
p.setHobby(listaHobby);
p.setLuogoDiNascita(l);
p.setAuto(listaAuto);
u.insert(p);
}
}
Here is the persistence.xml file:
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"
version="2.1">
<persistence-unit name="MyProject" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>it.ecipar.model.Auto</class>
<class>it.ecipar.model.Hobby</class>
<class>it.ecipar.model.Luogo</class>
<class>it.ecipar.model.Persona</class>
<properties>
<property name="hibernate.connection.driver_class" value="org.postgresql.Driver" />
<property name="hibernate.connection.url" value="jdbc:postgresql://localhost:5432/persone"/>
<property name="hibernate.connection.username" value="postgres" />
<property name="hibernate.connection.password" value="postgres" />
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/>
<property name="hibernate.show_sql" value="true" /> <!-- Show SQL in console -->
<property name="hibernate.format_sql" value="true" />
</properties>
</persistence-unit>
</persistence>
Here is the PersonaServlet.java:
package it.ecipar.web;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import flexjson.JSONSerializer;
import it.ecipar.common.JPAUtil;
import it.ecipar.model.Persona;
#SuppressWarnings("serial")
#WebServlet(urlPatterns = { "/persone" })
public class PersonaServlet extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String id = req.getParameter("id");
String json = null;
if (id == null) {
System.out.println("Ciao");
#SuppressWarnings("unchecked")
List<Persona> list = (List<Persona>) new JPAUtil().runNamedQuery("personalista",null);
JSONSerializer js = new JSONSerializer();
json = js.include("auto").include("hobby").serialize(list);
} else {
Persona p = (Persona) new JPAUtil().load(Persona.class, Integer.valueOf(id));
JSONSerializer js = new JSONSerializer();
json = js.include("auto").include("hobby").serialize(p);
}
resp.setContentType("application/json");
PrintWriter w = resp.getWriter();
w.print(json);
w.flush();
}
}
When I run the program it give me the sequent error:
Exception in thread "main" javax.persistence.PersistenceException: Unable to build entity manager factory
at org.hibernate.jpa.HibernatePersistenceProvider.createEntityManagerFactory(HibernatePersistenceProvider.java:83)
at org.hibernate.ejb.HibernatePersistence.createEntityManagerFactory(HibernatePersistence.java:54)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:55)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:39)
at it.ecipar.common.JPAUtil.<init>(JPAUtil.java:19)
at it.ecipar.common.Demo.main(Demo.java:16)
Caused by: org.hibernate.HibernateException: Errors in named queries: persona.lista
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:545)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1857)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:850)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$4.perform(EntityManagerFactoryBuilderImpl.java:843)
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.withTccl(ClassLoaderServiceImpl.java:398)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:842)
at org.hibernate.jpa.HibernatePersistenceProvider.createEntityManagerFactory(HibernatePersistenceProvider.java:75)
... 5 more
Could anyone help me please? Thanks.
Your query
#NamedQuery(name="persona.lista", query="SELECT o from it.ecipar.model.Persona o ORDER by p.cognome, p.nome")
has an error in it. You have Persona o but are then ordering by p.cognome.... You need to use the same table reference so:
#NamedQuery(name="persona.lista", query="SELECT o from it.ecipar.model.Persona o ORDER by o.cognome, o.nome")
Related
I'm trying to understand annotations better with JPA / Hibernate and SQL Server.
I created a simple project: an abstract class named "Articles". Two classes inherit it: Ramette which adds a weight and Pen which adds a color. The code below is not working and I am unable to correct the errors. Do you have an idea? Thank you!
package fr.eni.hibernate.entities;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.DiscriminatorType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.Table;
#Entity
#Table(name = "Articles")
#Inheritance( strategy = InheritanceType.SINGLE_TABLE )
#DiscriminatorColumn( name="type", discriminatorType = DiscriminatorType.STRING)
public abstract class Articles implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "idarticle")
private Integer idarticle;
#Column(name = "reference")
private String reference;
#Column(name = "marque")
private String marque ;
#Column(name = "designation")
private String designation;
#Column(name = "prixUnitaire")
private float prixUnitaire ;
#Column(name = "qteStock")
private int qteStock ;
public Articles() {
}
public Integer getIdArticle() {
return idarticle;
}
public String getReference() {
return reference;
}
public void setReference(String reference) {
this.reference = reference;
}
public String getMarque() {
return marque;
}
public void setMarque(String marque) {
this.marque = marque;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public float getPrixUnitaire() {
return prixUnitaire;
}
public void setPrixUnitaire(float prixUnitaire) {
this.prixUnitaire = prixUnitaire;
}
public int getQteStock() {
return qteStock;
}
public void setQteStock(int qteStock) {
this.qteStock = qteStock;
}
#Override
public String toString() {
return "Article [idArticle=" + idarticle + ", reference=" + reference + ", marque=" + marque + ", designation="
+ designation + ", prixUnitaire=" + prixUnitaire + ", qteStock=" + qteStock + "]";
}
}
package fr.eni.hibernate.entities;
import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
#Entity
#DiscriminatorValue("Ramette")
public class Ramette extends Articles {
private static final long serialVersionUID = 1L;
private int grammage;
public Ramette() {
}
#Column(name = "grammage")
public int getGrammage() {
return grammage;
}
public void setGrammage(int grammage) {
this.grammage = grammage;
}
#Override
public String toString() {
return super.toString() + " Ramette [grammage=" + grammage + "]";
}
}
package fr.eni.hibernate.entities;
import javax.persistence.Column;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
#Entity
#DiscriminatorValue("Stylo")
public class Stylo extends Articles {
private static final long serialVersionUID = 1L;
private String couleur;
public Stylo() {
}
#Column(name = "couleur")
public String getCouleur() {
return couleur;
}
public void setCouleur(String couleur) {
this.couleur = couleur;
}
#Override
public String toString() {
return super.toString() + " Stylo [couleur=" + couleur + "]";
}
}
package fr.eni.hibernate.entities;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.TypedQuery;
public class Main {
public static void main(String[] args) throws Exception {
EntityManagerFactory entityManagerFactory = null;
EntityManager entityManager = null;
try {
entityManagerFactory = Persistence.createEntityManagerFactory("WebStore");
entityManager = entityManagerFactory.createEntityManager();
TypedQuery<Articles> query = entityManager.createQuery("from Articles", Articles.class);
List<Articles> art = query.getResultList();
for (Articles article : art) {
System.out.println(art.getClass().getName());
System.out.println("\t" + article);
}
} finally {
if (entityManager != null)
entityManager.close();
if (entityManagerFactory != null)
entityManagerFactory.close();
}
}
}
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns<img src="images/smilies/icon_mad.gif" border="0" alt="" title=":x" class="inlineimg" />si="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="WebStore">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>fr.eni.hibernate.entities.Articles</class>
<class>fr.eni.hibernate.entities.Stylo</class>
<class>fr.eni.hibernate.entities.Ramette</class>
<properties>
<property name="javax.persistence.jdbc.driver"
value="com.microsoft.sqlserver.jdbc.SQLServerDriver" />
<property name="javax.persistence.jdbc.url"
value="jdbc:sqlserver://localhost;database=PAPETERIE_TEST" />
<property name="javax.persistence.jdbc.user" value="xx" />
<property name="javax.persistence.jdbc.password" value="x" />
<property name="hibernate.dialect"
value="org.hibernate.dialect.SQLServerDialect" />
<property name="hibernate.format_sql" value="false" />
</properties>
</persistence-unit>
</persistence>
CREATE TABLE Articles
(
idarticle INT IDENTITY(1,1),
reference varchar(10) NOT NULL,
marque nvarchar(200) NOT NULL,
designation nvarchar(250) NOT NULL,
prixUnitaire float NOT NULL,
qteStock int NOT NULL,
grammage int NULL,
couleur nvarchar(50) NULL,
type nchar(10) NOT NULL,
CONSTRAINT PK_Articles PRIMARY KEY (idarticle)
)
INSERT INTO Articles (reference, marque, designation, prixUnitaire, qteStock, grammage, couleur, type)
VALUES ('Bic', 'BBOrange', 'Bic bille Orange', 1.2, 20, 0, 'Bleu', 'Stylo'),
('Bic', 'BBOrange', 'Bic bille Orange', 1.2, 20, 0,'noir', 'Stylo'),
('Clairef', 'CRA4S', 'Ramette A4 Sup', 9, 20, 80, null, 'Ramette');
This makes not much sense. This exception is only thrown when you have a discriminator in the table that has no match in the entity model. Maybe you have trailing spaces in the table?
I went to develop an application to manage students in a university, I am looking for how to find students in relation to a date entered for that I have developed the following code lines:
1- Model student.java
package com.avatar.model;
import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.JoinColumn;
#Entity
#Table(name = "Students")
public class Student{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String nom;
private String prenom;
private String numTel;
private String mail;
#Temporal(TemporalType.DATE)
private Date dateCurrent;
#ManyToMany(fetch = FetchType.LAZY,
cascade = {
CascadeType.PERSIST,
CascadeType.MERGE
})
#JoinTable(name = "student_techno",
joinColumns = { #JoinColumn(name = "student_id") },
inverseJoinColumns = { #JoinColumn(name = "techno_id") })
private Set<Techno> techno = new HashSet<>();
public Student() {
}
#SuppressWarnings("unchecked")
public Student(String nom, String prenom,String numTel, String mail, Date dateCurrent,
) {
super();
this.nom = nom;
this.prenom = prenom;
this.numTel = numTel;
this.mail = mail;
this.dateCurrent = dateCurrent;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getPrenom() {
return prenom;
}
public void setPrenom(String prenom) {
this.prenom = prenom;
}
public String getNumTel() {
return numTel;
}
public void setNumTel(String numTel) {
this.numTel = numTel;
}
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Date getdateCurrent() {
return dateCurrent;
}
public void setdateCurrent(Date dateCurrent) {
this.dateCurrent = dateCurrent;
}
#Override
public String toString() {
return "Student[nom=" + nom + ", prenom=" + prenom + ", numTel=" + numTel + ", mail="
+ mail + ", dateCurrent=" + dateCurrent+ "]";
}
}
2- Controller
package com.avatar.web;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.avatar.dao.StudentDao;
import com.avatar.model.Student;
#CrossOrigin(origins = "http://localhost:4200")
#RestController
#RequestMapping("/avatar")
public class StudentController {
#Autowired
StudentDao studentdao;
#GetMapping(value = "/all-students")
public List<Student> listeDesStudent() {
List<Student> students= studentdao.findAll();
if (students.isEmpty())
throw new ProductNotFoundException("No student is registered in the database");
return students;
}
#GetMapping(value = "/all-students/dateCurrent/{dateCurrent}")
public List<Student> viewStudent(#PathVariable("dateCurrent") #DateTimeFormat(pattern = "yyyy-MM-dd") Date dateCurrent) {
Calendar c = Calendar.getInstance();
c.setTime(dateCurrent);
c.add(Calendar.DATE, 1);
dateCurrent = c.getTime();
return studentdao.findByDate(dateCurrent);
}
#GetMapping(value = "/all-students /techno/{nomTechno}")
List<Student > viewStudent(#PathVariable("nomTechno") String nomTechno) {
return studentdao.findDistinctByTechnoNomTechno(nomTechno);
}
#PostMapping(value = "/add-student")
public Student addStudent(#RequestBody Student student) {
Student studentAdded= studentdao.save(Student);
return studentAdded;
}
}
3- DAO
package com.avatar.dao;
import java.util.Date;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.avatar.model.Student;
#Repository
public interface StudentDao extends JpaRepository<Student, String> {
List<Student> findByDate(Date dateCurrent);
List<> findDistinctByTechnoNomTechno(String nomTechno);
}
4- applications.properties
server.port= 8080
# MySQL Properties
spring.jpa.show-sql = true
spring.datasource.url= jdbc:mysql://localhost:3306/avatar?serverTimezone=UTC&useLegacyDatetimeCode=false
spring.datasource.username=*****
spring.datasource.password=*****
# Hibernate Properties
spring.jpa.hibernate.ddl-auto=update
in my console i have:
Failed to create query for method public abstract java.util.List com.avatar.dao.StudentDao.findByDate(java.util.Date)! No property date found for type Student!
Please update DAO as per for below mentioned changes
If the field name is dateCurrent then findByDateCurrent.
package com.avatar.dao;
import java.util.Date;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.avatar.model.Student;
#Repository
public interface StudentDao extends JpaRepository<Student, String> {
List<Student> findByDateCurrent(Date dateCurrent);
List<> findDistinctByTechnoNomTechno(String nomTechno);
}
You are missing field name, in Entity class it is not the date by dateCurrent, thus your JPA should be findByDateCurrent
Today I did some experiments with hibernate. Unfortunately it seems if I’m misunderstanding something about the sessions.
I have three entities (book “buch”, user “benutzer” and rent “leihstellung”).
Each book knows about the rents, it’s concerned by. Each rent knows about the associated book. Furthermore each rent knows about the fitting user and of course each user knows the associated rents.
I explicitly want to have this two way mappings.
Now I wrote a small tester which inserts some data. The insert progress works as expected. After inserting some data I would like to delete a user.
If I do this before the commit, hibernate gives me an error, because the user will be reinserted be the rents it belongs to (that even happens, if I manually delete the user from this rents). Here I don’t really understand why that happens.
Everything works fine, if I do a session.close and open a new session for deleting the user.
I guess, that there is a smarter way to do this within one session. But unfortunately I don’t know how this can be done.
Any explanation is welcome.
public class Worker implements Iworker{
private Sessiongetter sg;
private MainMenu mm;
public void work(File datei)
{
sg = new Sessiongetter();
Session session = sg.getSesseion();
WlBuchart wlBuchart = new WlBuchart(1, "Sachbuch");
Buch buch = new Buch("test", "ich", 1);
buch.setWlBuchart(wlBuchart);
Buch buch2 = new Buch("versuch", "du",2);
buch2.setWlBuchart(wlBuchart);
session.beginTransaction();
session.save(wlBuchart);
session.save(buch);
session.save(buch2);
Benutzer benutzer = new Benutzer("hans", "dampf", "Lehrer", "versuch");
session.save(benutzer);
Leihstellung leihstellung = new Leihstellung(benutzer, buch);
Leihstellung leihstellung2 = new Leihstellung(benutzer, buch2);
session.save(leihstellung);
session.save(leihstellung2);
benutzer.addLeihstellung(leihstellung);
benutzer.addLeihstellung(leihstellung2);
session.update(benutzer);
buch.addLeihstellung(leihstellung);
buch2.addLeihstellung(leihstellung2);
session.update(buch);
session.update(buch2);
session.remove(benutzer);
session.flush();
session.getTransaction().commit();
session.close();
System.out.println("fertig");
}
package code.logik;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.Session;
#Entity
#Table(name="benutzer")
public class Benutzer {
#Column(nullable=false)
private String vorname, nachname, gruppe;
#Id
private String kennung;
private boolean admin;
#Column(nullable=true)
private String kennwort;
#OneToMany(cascade=CascadeType.ALL, mappedBy="benutzer")
private List<Leihstellung>leihstellungs;
public String getKennwort() {
return kennwort;
}
public void setKennwort(String kennwort) {
this.kennwort = kennwort;
}
public Benutzer(String vorname, String nachname, String gruppe, String kennung) {
this.vorname=vorname;
this.nachname=nachname;
this.gruppe=gruppe;
this.kennung=kennung;
this.leihstellungs= new ArrayList<>();
}
public Benutzer() {
// TODO Auto-generated constructor stub
}
public String getVorname() {
return vorname;
}
public String getNachname() {
return nachname;
}
public String getGruppe() {
return gruppe;
}
public String getKennung() {
return kennung;
}
public boolean isAdmin() {
return admin;
}
public void setAdmin(boolean admin) {
this.admin = admin;
}
public List<Leihstellung> getLeihstellungs() {
return leihstellungs;
}
public void addLeihstellung(Leihstellung leihstellung)
{
leihstellungs.add(leihstellung);
}
public int compare(Benutzer other)
{
if (this.getNachname().compareTo(other.getNachname())!=0)
{
return this.getNachname().compareTo(other.getNachname());
}
return this.getVorname().compareTo(other.getVorname());
}
}
package code.logik;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.annotations.ManyToAny;
#Entity
#Table(name="buch")
public class Buch {
#Column(nullable=false)
private String titel;
private String autor;
#ManyToOne
private WlBuchart wlBuchart;
#OneToMany(cascade=CascadeType.ALL, mappedBy="buch")
private List<Leihstellung>leihstellungs;
public WlBuchart getWlBuchart() {
return wlBuchart;
}
public void setWlBuchart(WlBuchart wlBuchart) {
this.wlBuchart = wlBuchart;
}
#Id
private int nummer;
public Buch(String titel, String autor,int nummer) {
this.titel=titel;
this.autor=autor;
this.nummer=nummer;
leihstellungs = new ArrayList<>();
}
public Buch() {
// TODO Auto-generated constructor stub
}
public String getTitel() {
return titel;
}
public String getAutor() {
return autor;
}
public int getNummer() {
return nummer;
}
public List<Leihstellung> getLeihstellungs() {
return leihstellungs;
}
public void addLeihstellung(Leihstellung leihstellung)
{
leihstellungs.add(leihstellung);
}
}
package code.logik;
import java.time.LocalDate;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name="leihstellung")
public class Leihstellung {
#ManyToOne
private Benutzer benutzer;
#Id #GeneratedValue
private int id;
#Column(nullable=false)
private LocalDate von;
private LocalDate bis;
#ManyToOne
private Buch buch;
public Leihstellung(Benutzer benutzer, Buch buch) {
this.benutzer=benutzer;
this.buch=buch;
this.von = LocalDate.now();
}
public Leihstellung() {
// TODO Auto-generated constructor stub
}
public void setAbgegeben()
{
bis = LocalDate.now();
}
public Benutzer getBenutzer() {
return benutzer;
}
public int getId() {
return id;
}
public LocalDate getVon() {
return von;
}
public LocalDate getBis() {
return bis;
}
public Buch getBuch() {
return buch;
}
}
Found the solution myself. I had to delete the references from the connected rents and books.
Now everything works find.
I am working on hibernate. I have two entities: Project and Contact. These two entities have a one-to-many relationship. But, when I save a Project class, hibernate does not insert any record in Contact table(class) and just updates the Project table.
The business is;
There are lots of Projects. User select a project with double click which opens new jsp(got project id on that) and entering contact info and push Add button. What I am trying to do is the project that user selected is on db already. There is ok but I want to insert contact table with my contact info which include project_id. I am expecting from hibernate is update project table also insert contact table. But now reality is just updating project table only.
Here is structure of my classes: the main controller is Contact Controller.
Project.java:
package Model;
import java.util.ArrayList;
import java.util.List;
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.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name="xxer_Projects_t")
public class Project {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int project_id;
#Column(name = "Project_number")
private String Project_number;
#Column(name = "Project_name")
private String Project_name;
#ManyToOne(fetch=FetchType.EAGER,cascade= {CascadeType.PERSIST,
CascadeType.MERGE,
CascadeType.DETACH,
CascadeType.REFRESH})
#JoinColumn(name = "constructor_id")
private Constructor constructor;
#OneToMany(fetch=FetchType.EAGER,mappedBy = "project",
cascade= {CascadeType.PERSIST,
CascadeType.MERGE,
CascadeType.DETACH,
CascadeType.REFRESH})
private List<Contact> contacts;
#OneToMany(fetch=FetchType.EAGER,mappedBy = "project",
cascade= {CascadeType.PERSIST,
CascadeType.MERGE,
CascadeType.DETACH,
CascadeType.REFRESH})
public List<Contact> getContacts() {
return contacts;
}
#OneToMany(fetch=FetchType.EAGER,mappedBy = "project",
cascade= {CascadeType.PERSIST,
CascadeType.MERGE,
CascadeType.DETACH,
CascadeType.REFRESH})
public void setContacts(List<Contact> contacts) {
this.contacts = contacts;
}
public Project() {
// TODO Auto-generated constructor stub
}
public Project(String project_number, String project_name) {
Project_number = project_number;
Project_name = project_name;
}
public int getProject_id() {
return project_id;
}
public void setProject_id(int project_id) {
this.project_id = project_id;
}
public String getProject_number() {
return Project_number;
}
public void setProject_number(String project_number) {
Project_number = project_number;
}
public String getProject_name() {
return Project_name;
}
public void setProject_name(String project_name) {
Project_name = project_name;
}
public Constructor getConstructor() {
return constructor;
}
public void setConstructor(Constructor constructor) {
this.constructor = constructor;
}
}
Contact.java:
package Model;
import javax.persistence.CascadeType;
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.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name="xxer_contacts_t")
public class Contact {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String name_surname;
private String email;
private String phone;
#ManyToOne(fetch=FetchType.EAGER,cascade= {CascadeType.PERSIST,
CascadeType.MERGE,
CascadeType.DETACH,
CascadeType.REFRESH})
#JoinColumn(name = "project_id")
private Project project;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName_surname() {
return name_surname;
}
public void setName_surname(String name_surname) {
this.name_surname = name_surname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public Project getProject_id() {
return project;
}
public void setProject_id(Project project_id) {
this.project = project_id;
}
public Contact() {
}
}
ContactController.java:
package Controller;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import Dao.ConstructorDao;
import Dao.ContactDao;
import Dao.ProjectDao;
import Model.Constructor;
import Model.Contact;
import Model.Project;
/**
* Servlet implementation class ContactController
*/
#WebServlet("/ContactController")
public class ContactController extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public ContactController() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int projectid = Integer.parseInt(request.getParameter("id"));
if (request.getParameter("Operation").equals("add")) {
String name = request.getParameter("NameSurname");
String email = request.getParameter("Email");
String phone = request.getParameter("Phone");
Project p = ProjectDao.getProjectById (projectid);
List <Contact> loc = new ArrayList<>();
Contact cont = new Contact();
cont.setName_surname(name);
cont.setEmail(email);
cont.setPhone(phone);
cont.setProject_id(p);
loc.add(cont);
p.setContacts(loc);
ProjectDao.insert(p);
/*
cont.setName_surname(name);
cont.setEmail(email);
cont.setPhone(phone);
cont.setProject_id(p);
ContactDao.Insert(cont);
*/
}
// List
List<Contact> ListOfContacts =ContactDao.getListofContacts(projectid);
request.setAttribute("ListOfContacts", ListOfContacts);
request.setAttribute("id", projectid);
RequestDispatcher dispacher = request.getRequestDispatcher("/ProjectContacts.jsp");
dispacher.forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
ProjectDao.java:
package Dao;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import Model.Constructor;
import Model.OfferType;
import Model.Project;
import _JSP.HibernateUtil;
public class ProjectDao {
public ProjectDao() {
// TODO Auto-generated constructor stub
}
/*
public static void main(String[] args) {
int id = 1;
Project p = new Project ("Proje3","TRIA Projesi");
insert(p);
}
*/
public static void insert(Project p) {
SessionFactory sf =HibernateUtil.getSessionFactory();
//SessionFactory sf = new Configuration().configure().buildSessionFactory();
Session session = sf.openSession();
try {
session.beginTransaction();
//Constructor con = session.get(Constructor.class, consid);
//p.setConstructor(con);
//session.save(p);
//session.persist(p);
session.saveOrUpdate(p);
session.getTransaction().commit();
}
finally {
session.close();
System.out.println("Project Session Closed!!!!");
}
}
public static List<Project> getListofProjects() {
//SessionFactory sf = new Configuration().configure().buildSessionFactory();
SessionFactory sf =HibernateUtil.getSessionFactory();
Session session = sf.openSession();
//List <OfferType> ol = session.createCriteria(OfferType.class).list();
List <Project> ol =session.createQuery("from Project order by 1 desc").list();
session.close();
return ol;
}
public static Project getProjectById(int id) {
SessionFactory sf = new Configuration().configure().buildSessionFactory();
Session session = sf.openSession();
//List <OfferType> ol = session.createCriteria(OfferType.class).list();
Project p =session.get(Project.class,id);
session.close();
return p;
}
public static List<Constructor> LoadConsDropDown() {
SessionFactory sf = new Configuration().configure().buildSessionFactory();
Session session = sf.openSession();
session.beginTransaction();
List <Constructor> listofcons = new ArrayList<Constructor>();
listofcons = session.createQuery("from Constructor order by name asc").list();
session.close();
return listofcons;
}
}
ContactDao.java:
package Dao;
import java.sql.SQLException;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Restrictions;
import Model.Contact;
import Model.Project;
import _JSP.HibernateUtil;
public class ContactDao {
public ContactDao() {
// TODO Auto-generated constructor stub
}
public static void Insert(Contact c) throws SQLException {
//SessionFactory sf = new Configuration().configure().buildSessionFactory();
SessionFactory sf =HibernateUtil.getSessionFactory();
Session session = sf.openSession();
try {
session.beginTransaction();
//Constructor con = session.get(Constructor.class, consid);
//p.setConstructor(con);
session.save(c);
session.getTransaction().commit();
}
finally {
session.close();
System.out.println("Contact Session Closed!!!!");
}
}
public static List<Contact> getListofContacts(int id) {
//SessionFactory sf = new Configuration().configure().buildSessionFactory();
SessionFactory sf =HibernateUtil.getSessionFactory();
Session session = sf.openSession();
//List <OfferType> ol = session.createCriteria(OfferType.class).list();
//List <Contact> ol =session.createCriteria(Contact.class).list();
List <Contact> ol = session.createCriteria(Contact.class).createAlias("project", "p").add(Restrictions.eq("p.project_id", id)).list();
session.close();
return ol;
}
}
I have the following simple spring mvc 4 application with JPA 2.0 using java config
package com.somecompany.class;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
#Configuration
#EnableWebMvc
#Import({JPAConfig.class, BeanConfig.class})
#ComponentScan("com.*")
public class AppConfig {
public InternalResourceViewResolver setupInternalResourceViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
return resolver;
}
}
The AppConfig.java class contains the application configuration logic
package com.somecompany.class;
import javax.sql.DataSource;
import org.apache.commons.dbcp.BasicDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver;
import org.springframework.instrument.classloading.LoadTimeWeaver;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(basePackages="com.somecompany.model.*")
public class JPAConfig {
#Bean
public JpaTransactionManager jpaTransactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager(getEntityManagerFactoryBean().getObject());
return transactionManager;
}
#Bean
public LocalContainerEntityManagerFactoryBean getEntityManagerFactoryBean() {
LocalContainerEntityManagerFactoryBean containerEntityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
containerEntityManagerFactoryBean.setDataSource(getDataSource());
containerEntityManagerFactoryBean.setPersistenceUnitName("pmd-web");
LoadTimeWeaver loadTimeWeaver = new InstrumentationLoadTimeWeaver();
containerEntityManagerFactoryBean.setLoadTimeWeaver(loadTimeWeaver);
return containerEntityManagerFactoryBean;
}
#Bean
public DataSource getDataSource() {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/somedatabase");
dataSource.setUsername("someuser");
dataSource.setPassword("somepassword");
return dataSource;
}
}
The JPAConfig.java contains the JPA configuration details
package com.somecompany.class;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration.Dynamic;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
public class WebAppInitializer implements WebApplicationInitializer{
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext webApplicationContext = new AnnotationConfigWebApplicationContext();
webApplicationContext.register(AppConfig.class);
webApplicationContext.setServletContext(servletContext);
webApplicationContext.refresh();
Dynamic dynamic = servletContext.addServlet("dispatcher", new DispatcherServlet(webApplicationContext));
dynamic.addMapping("/");
dynamic.setLoadOnStartup(1);
}
}
WebAppInitializer.java contains the logic for initializing the web app
<?xml version="1.0" encoding="UTF-8" ?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="pmd-web">
<description>project metrics dashboard</description>
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
</properties>
</persistence-unit>
</persistence>
persistence.xml is as above.
package com.somecompany.Controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.somecompany.VO.LoginVO;
import com.somecompany.loginService.LoginService;
#RestController
public class LoginController {
#Autowired
LoginService loginService;
#RequestMapping(value = "/login", method = RequestMethod.POST)
public ResponseEntity<LoginVO> authenticateUser(#RequestBody LoginVO loginVO) {
loginVO = loginService.authenticateUser(loginVO);
if (loginVO.getStatus()) {
return new ResponseEntity<LoginVO>(loginVO, HttpStatus.OK);
} else {
return new ResponseEntity<LoginVO>(loginVO, HttpStatus.FORBIDDEN);
}
}
}
The Restful controller class is as above
package com.somecompany.loginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import somecompany.VO.LoginVO;
import somecompany.mapper.LoginMapper;
import somecompany.model.PmdUser;
import com.somecompany.LoginDAO;
#Service
public class LoginService {
#Autowired
LoginDAO loginDAO;
#Autowired
LoginMapper loginMapper;
#Transactional
public LoginVO authenticateUser(LoginVO loginVO) {
PmdUser pmdUser = loginMapper.getpmdUserFromLoginVO(loginVO);
LoginVO loginVOFromDB = loginDAO.authenticateUser(pmdUser);
if (loginVO.getUserName().equalsIgnoreCase(loginVOFromDB.getUserName())) {
loginVO.setStatus(true);
}
return loginVO;
}
}
The service class is as above
package com.somecompany.loginDAO;
import java.util.List;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Restrictions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.somecompany.VO.LoginVO;
import com.somecompany.baseDAO.BaseDao;
import com.somecompany.mapper.LoginMapper;
import com.somecompany.model.PmdUser;
#Repository
public class LoginDAO extends BaseDao {
#Autowired
LoginMapper loginMapper;
public LoginVO authenticateUser(PmdUser pmdUser) {
PmdUser user = null;
LoginVO loginVO = null;
List<PmdUser> pmdUsers = findByNamedQuery("findByUsername", pmdUser.getUserName());
if (pmdUsers.size() > 0) {
user = pmdUsers.get(0);
loginVO = loginMapper.getLoginVOFromPmdUser(user);
}
return loginVO;
}
}
The loginDAO.java class is as above
package com.somecompany.baseDAO;
import java.lang.reflect.ParameterizedType;
import java.util.List;
import java.util.Map;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.PersistenceException;
import javax.persistence.Query;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.ProjectionList;
import org.hibernate.criterion.Projections;
import org.springframework.stereotype.Repository;
#Repository
public abstract class BaseDao<E, K> {
/** The entity manager. */
#PersistenceContext(unitName = "pmd-web")
protected EntityManager entityManager;
/**
* Gets the entity manager.
*
* #return the entity manager
*/
public EntityManager getEntityManager() {
return entityManager;
}
/** The entity class. */
protected Class<E> entityClass;
/**
* Instantiates a new base DAO.
*/
#SuppressWarnings("unchecked")
public BaseDao() {
ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass();
this.entityClass = (Class<E>) genericSuperclass.getActualTypeArguments()[0];
}
public List<E> findByNamedQuery(final String name, Object... params) {
javax.persistence.Query query = getEntityManager().createNamedQuery(name);
for (int i = 0; i < params.length; i++) {
query.setParameter(i + 1, params[i]);
}
final List<E> result = (List<E>) query.getResultList();
return result;
}
}
On deploying the application war and execution the REST service i get the exception
Caused by: java.lang.IllegalArgumentException: No query defined for that name [findByUsername]
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.buildQueryFromName(AbstractEntityManagerImpl.java:788) [hibernate-entitymanager-4.3.7.Final.jar:4.3.7.Final]
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.createNamedQuery(AbstractEntityManagerImpl.java:767) [hibernate-entitymanager-4.3.7.Final.jar:4.3.7.Final]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.8.0_65]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) [rt.jar:1.8.0_65]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) [rt.jar:1.8.0_65]
at java.lang.reflect.Method.invoke(Method.java:497) [rt.jar:1.8.0_65]
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:294) [spring-orm-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at com.sun.proxy.$Proxy92.createNamedQuery(Unknown Source)
at com.somecompany.baseDAO.BaseDao.findByNamedQuery(BaseDao.java:184) [classes:]
at com.somecompany.loginDAO.LoginDAO.authenticateUser(LoginDAO.java:26) [classes:]
at com.somecompany.loginDAO.LoginDAO$$FastClassBySpringCGLIB$$1909bedd.invoke(<generated>) [classes:]
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) [spring-core-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:651) [spring-aop-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at com.somecompany.loginDAO.LoginDAO$$EnhancerBySpringCGLIB$$45d26c87.authenticateUser(<generated>) [classes:]
at com.somecompany.loginService.LoginService.authenticateUser(LoginService.java:25) [classes:]
at com.somecompany.loginService.LoginService$$FastClassBySpringCGLIB$$3de2163d.invoke(<generated>) [classes:]
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204) [spring-core-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:720) [spring-aop-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157) [spring-aop-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99) [spring-tx-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281) [spring-tx-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96) [spring-tx-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179) [spring-aop-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:655) [spring-aop-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at com.somecompany.loginService.LoginService$$EnhancerBySpringCGLIB$$912637e7.authenticateUser(<generated>) [classes:]
at com.somecompany.loginController.LoginController.authenticateUser(LoginController.java:22) [classes:]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.8.0_65]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) [rt.jar:1.8.0_65]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) [rt.jar:1.8.0_65]
at java.lang.reflect.Method.invoke(Method.java:497) [rt.jar:1.8.0_65]
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221) [spring-web-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136) [spring-web-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110) [spring-webmvc-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:817) [spring-webmvc-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:731) [spring-webmvc-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) [spring-webmvc-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:959) [spring-webmvc-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:893) [spring-webmvc-4.2.5.RELEASE.jar:4.2.5.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:968) [spring-webmvc-4.2.5.RELEASE.jar:4.2.5.RELEASE]
... 30 more
But i have the named query on the entity as below
package com.somecompany.model;
import static javax.persistence.GenerationType.IDENTITY;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.UniqueConstraint;
import org.springframework.stereotype.Component;
#Entity
#Table(name = "pmd_user", catalog = "pmd", uniqueConstraints = {
#UniqueConstraint(columnNames = { "CUSTOMER_ID", "USER_NAME" }),
#UniqueConstraint(columnNames = "EMAIL_ADDRESS") })
#Component
#NamedQuery(name="findByUsername", query="SELECT u FROM PmdUser u WHERE u.userName = ?1")
public class PmdUser implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private Long userId;
private PmdCustomer pmdCustomer;
private String userName;
private String emailAddress;
private Long phone;
private String firstName;
private String lastName;
private String password;
private Boolean passwordChangeRequired;
private Date lastPasswordChange;
private Long challengeQuestionId;
private String challengeAnswer;
private Boolean deactivated;
private Boolean deleted;
private Boolean isPreview;
private Boolean receiveEmail;
private Boolean isGuest;
private Boolean newsletter;
private String emailFormat;
private Date dateOfLastLogon;
private Long visits;
private String note;
private Long createdIp;
private Long updatedIp;
private Date dateCreated;
private Date dateUpdated;
private Long createdBy;
private Long updatedBy;
private List<PmdUserRole> pmdUserRoles = new ArrayList<PmdUserRole>(0);
public PmdUser() {
}
public PmdUser(String userName, String emailAddress) {
this.userName = userName;
this.emailAddress = emailAddress;
}
public PmdUser(PmdCustomer pmdCustomer, String userName, String emailAddress, Long phone, String firstName,
String lastName, String password, Boolean passwordChangeRequired, Date lastPasswordChange,
Long challengeQuestionId, String challengeAnswer, Boolean deactivated, Boolean deleted, Boolean isPreview,
Boolean receiveEmail, Boolean isGuest, Boolean newsletter, String emailFormat, Date dateOfLastLogon,
Long visits, String note, Long createdIp, Long updatedIp, Date dateCreated, Date dateUpdated,
Long createdBy, Long updatedBy, List<PmdUserRole> pmdUserRoles) {
this.pmdCustomer = pmdCustomer;
this.userName = userName;
this.emailAddress = emailAddress;
this.phone = phone;
this.firstName = firstName;
this.lastName = lastName;
this.password = password;
this.passwordChangeRequired = passwordChangeRequired;
this.lastPasswordChange = lastPasswordChange;
this.challengeQuestionId = challengeQuestionId;
this.challengeAnswer = challengeAnswer;
this.deactivated = deactivated;
this.deleted = deleted;
this.isPreview = isPreview;
this.receiveEmail = receiveEmail;
this.isGuest = isGuest;
this.newsletter = newsletter;
this.emailFormat = emailFormat;
this.dateOfLastLogon = dateOfLastLogon;
this.visits = visits;
this.note = note;
this.createdIp = createdIp;
this.updatedIp = updatedIp;
this.dateCreated = dateCreated;
this.dateUpdated = dateUpdated;
this.createdBy = createdBy;
this.updatedBy = updatedBy;
this.pmdUserRoles = pmdUserRoles;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "USER_ID", unique = true, nullable = false)
public Long getUserId() {
return this.userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "CUSTOMER_ID")
public PmdCustomer getPmdCustomer() {
return this.pmdCustomer;
}
public void setPmdCustomer(PmdCustomer pmdCustomer) {
this.pmdCustomer = pmdCustomer;
}
#Column(name = "USER_NAME", nullable = false, length = 32)
public String getUserName() {
return this.userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
#Column(name = "EMAIL_ADDRESS", unique = true, nullable = false, length = 128)
public String getEmailAddress() {
return this.emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
#Column(name = "PHONE")
public Long getPhone() {
return this.phone;
}
public void setPhone(Long phone) {
this.phone = phone;
}
#Column(name = "FIRST_NAME", length = 32)
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
#Column(name = "LAST_NAME", length = 32)
public String getLastName() {
return this.lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#Column(name = "PASSWORD", length = 128)
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
#Column(name = "PASSWORD_CHANGE_REQUIRED")
public Boolean getPasswordChangeRequired() {
return this.passwordChangeRequired;
}
public void setPasswordChangeRequired(Boolean passwordChangeRequired) {
this.passwordChangeRequired = passwordChangeRequired;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "LAST_PASSWORD_CHANGE", length = 19)
public Date getLastPasswordChange() {
return this.lastPasswordChange;
}
public void setLastPasswordChange(Date lastPasswordChange) {
this.lastPasswordChange = lastPasswordChange;
}
#Column(name = "CHALLENGE_QUESTION_ID")
public Long getChallengeQuestionId() {
return this.challengeQuestionId;
}
public void setChallengeQuestionId(Long challengeQuestionId) {
this.challengeQuestionId = challengeQuestionId;
}
#Column(name = "CHALLENGE_ANSWER", length = 128)
public String getChallengeAnswer() {
return this.challengeAnswer;
}
public void setChallengeAnswer(String challengeAnswer) {
this.challengeAnswer = challengeAnswer;
}
#Column(name = "DEACTIVATED")
public Boolean getDeactivated() {
return this.deactivated;
}
public void setDeactivated(Boolean deactivated) {
this.deactivated = deactivated;
}
#Column(name = "DELETED")
public Boolean getDeleted() {
return this.deleted;
}
public void setDeleted(Boolean deleted) {
this.deleted = deleted;
}
#Column(name = "IS_PREVIEW")
public Boolean getIsPreview() {
return this.isPreview;
}
public void setIsPreview(Boolean isPreview) {
this.isPreview = isPreview;
}
#Column(name = "RECEIVE_EMAIL")
public Boolean getReceiveEmail() {
return this.receiveEmail;
}
public void setReceiveEmail(Boolean receiveEmail) {
this.receiveEmail = receiveEmail;
}
#Column(name = "IS_GUEST")
public Boolean getIsGuest() {
return this.isGuest;
}
public void setIsGuest(Boolean isGuest) {
this.isGuest = isGuest;
}
#Column(name = "NEWSLETTER")
public Boolean getNewsletter() {
return this.newsletter;
}
public void setNewsletter(Boolean newsletter) {
this.newsletter = newsletter;
}
#Column(name = "EMAIL_FORMAT", length = 4)
public String getEmailFormat() {
return this.emailFormat;
}
public void setEmailFormat(String emailFormat) {
this.emailFormat = emailFormat;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "DATE_OF_LAST_LOGON", length = 19)
public Date getDateOfLastLogon() {
return this.dateOfLastLogon;
}
public void setDateOfLastLogon(Date dateOfLastLogon) {
this.dateOfLastLogon = dateOfLastLogon;
}
#Column(name = "VISITS")
public Long getVisits() {
return this.visits;
}
public void setVisits(Long visits) {
this.visits = visits;
}
#Column(name = "NOTE", length = 65535)
public String getNote() {
return this.note;
}
public void setNote(String note) {
this.note = note;
}
#Column(name = "CREATED_IP")
public Long getCreatedIp() {
return this.createdIp;
}
public void setCreatedIp(Long createdIp) {
this.createdIp = createdIp;
}
#Column(name = "UPDATED_IP")
public Long getUpdatedIp() {
return this.updatedIp;
}
public void setUpdatedIp(Long updatedIp) {
this.updatedIp = updatedIp;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "DATE_CREATED", length = 19)
public Date getDateCreated() {
return this.dateCreated;
}
public void setDateCreated(Date dateCreated) {
this.dateCreated = dateCreated;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "DATE_UPDATED", length = 19)
public Date getDateUpdated() {
return this.dateUpdated;
}
public void setDateUpdated(Date dateUpdated) {
this.dateUpdated = dateUpdated;
}
#Column(name = "CREATED_BY")
public Long getCreatedBy() {
return this.createdBy;
}
public void setCreatedBy(Long createdBy) {
this.createdBy = createdBy;
}
#Column(name = "UPDATED_BY")
public Long getUpdatedBy() {
return this.updatedBy;
}
public void setUpdatedBy(Long updatedBy) {
this.updatedBy = updatedBy;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "pmdUser")
public List<PmdUserRole> getPmdUserRoles() {
return this.pmdUserRoles;
}
public void setPmdUserRoles(List<PmdUserRole> pmdUserRoles) {
this.pmdUserRoles = pmdUserRoles;
}
#Override
public String toString() {
return "PmdUser [userId=" + userId + ", userName=" + userName + ", emailAddress=" + emailAddress
+ ", firstName=" + firstName + ", lastName=" + lastName + "]";
}
}
I suspect this is due to an integration issue with spring and JPA as the same query works fine in a unit test.
Has anybody faced this issue before ? or Is my JPA configuration not complete ?
Refer to your persistence xml location :
containerEntityManagerFactoryBean.setPersistenceXmlLocation("classpath:...");
Refer to your entities either from persistence xml OR
containerEntityManagerFactoryBean.setPackagesToScan("com.somecomany.model");
And you are configuring repositories from the wrong location, change :
#EnableJpaRepositories(basePackages="com.somecompany.model.*")
to :
#EnableJpaRepositories(basePackages="com.somecompany")
The issue was with the class deceleration in the Persistence.xml file previously the deceleration was as below
<?xml version="1.0" encoding="UTF-8" ?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0">
<persistence-unit name="pmd-web">
<description>project metrics dashboard</description>
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
</properties>
</persistence-unit>
and had to change it to have the class declarations
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="pmd-web">
<class>com.somecompany.model.PmdCustomer</class>
<class>com.somecompany.model.CustomerModule</class>
<class>com.somecompany.model.Modules</class>
<class>com.somecompany.model.Project</class>
<class>com.somecompany.model.ProjectRelease</class>
<class>com.somecompany.model.ProjectSprint</class>
<class>com.somecompany.model.Role</class>
<class>com.somecompany.model.User</class>
<class>com.somecompany.model.UserRole</class>
</persistence-unit>