The module has not been deployed [netbeans+glassfish] - java

i am developping a project base on J2EE EJB JSF, database is MYsql, the project works very well last week. but today, it can't be deployed when i run it. here are some exception:
Initial deploying ECOM to C:\Users\John624\Documents\NetBeansProjects\PromoCoupon\ECOM\dist\gfdeploy\ECOM
Completed initial distribution of ECOM
Initializing...
invalid header field name: Exception Description
C:\Users\John624\Documents\NetBeansProjects\PromoCoupon\ECOM\nbproject\build-impl.xml:307: The module has not been deployed.
See the server log for details.
BUILD FAILED (total time: 5 seconds)
Glassfish:
<code> SEVERE: Exception while invoking class org.glassfish.persistence.jpa.JPADeployer prepare method
SEVERE: Exception while invoking class org.glassfish.javaee.full.deployment.EarDeployer prepare method
SEVERE: org.glassfish.deployment.common.DeploymentException: Exception [EclipseLink-28018] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.EntityManagerSetupException
Exception Description: Predeployment of PersistenceUnit [ECOM-ejbPU] failed.
Internal Exception: Exception [EclipseLink-7158] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.ValidationException
Exception Description: Error encountered when building the #NamedQuery [Adresse.maxId] from entity class [class org.eclipse.persistence.internal.jpa.metadata.queries.NamedQueryMetadata].
Internal Exception: java.lang.ClassCastException: org.eclipse.persistence.jpa.jpql.parser.NullExpression cannot be cast to org.eclipse.persistence.jpa.jpql.parser.IdentificationVariable
at org.glassfish.javaee.full.deployment.EarDeployer.prepare(EarDeployer.java:180)
at com.sun.enterprise.v3.server.ApplicationLifecycle.prepareModule(ApplicationLifecycle.java:922)
at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:431)
at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:219)
at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:491)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:527)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:523)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:356)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$2.execute(CommandRunnerImpl.java:522)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:546)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1423)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1500(CommandRunnerImpl.java:108)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1762)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1674)
at com.sun.enterprise.v3.admin.AdminAdapter.doCommand(AdminAdapter.java:534)
at com.sun.enterprise.v3.admin.AdminAdapter.onMissingResource(AdminAdapter.java:224)
at org.glassfish.grizzly.http.server.StaticHttpHandler.service(StaticHttpHandler.java:297)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:246)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544)
at java.lang.Thread.run(Thread.java:724)
Caused by: javax.persistence.PersistenceException: Exception [EclipseLink-28018] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.EntityManagerSetupException
Exception Description: Predeployment of PersistenceUnit [ECOM-ejbPU] failed.
Internal Exception: Exception [EclipseLink-7158] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.ValidationException
Exception Description: Error encountered when building the #NamedQuery [Adresse.maxId] from entity class [class org.eclipse.persistence.internal.jpa.metadata.queries.NamedQueryMetadata].
Internal Exception: java.lang.ClassCastException: org.eclipse.persistence.jpa.jpql.parser.NullExpression cannot be cast to org.eclipse.persistence.jpa.jpql.parser.IdentificationVariable
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.createPredeployFailedPersistenceException(EntityManagerSetupImpl.java:1950)
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.predeploy(EntityManagerSetupImpl.java:1941)
at org.eclipse.persistence.jpa.PersistenceProvider.createContainerEntityManagerFactory(PersistenceProvider.java:322)
at org.glassfish.persistence.jpa.PersistenceUnitLoader.loadPU(PersistenceUnitLoader.java:199)
at org.glassfish.persistence.jpa.PersistenceUnitLoader.<init>(PersistenceUnitLoader.java:107)
at org.glassfish.persistence.jpa.JPADeployer$1.visitPUD(JPADeployer.java:223)
at org.glassfish.persistence.jpa.JPADeployer$PersistenceUnitDescriptorIterator.iteratePUDs(JPADeployer.java:510)
at org.glassfish.persistence.jpa.JPADeployer.createEMFs(JPADeployer.java:230)
at org.glassfish.persistence.jpa.JPADeployer.prepare(JPADeployer.java:168)
at com.sun.enterprise.v3.server.ApplicationLifecycle.prepareModule(ApplicationLifecycle.java:922)
at org.glassfish.javaee.full.deployment.EarDeployer.prepareBundle(EarDeployer.java:307)
at org.glassfish.javaee.full.deployment.EarDeployer.access$200(EarDeployer.java:88)
at org.glassfish.javaee.full.deployment.EarDeployer$1.doBundle(EarDeployer.java:153)
at org.glassfish.javaee.full.deployment.EarDeployer$1.doBundle(EarDeployer.java:150)
at org.glassfish.javaee.full.deployment.EarDeployer.doOnBundles(EarDeployer.java:230)
at org.glassfish.javaee.full.deployment.EarDeployer.doOnAllTypedBundles(EarDeployer.java:239)
at org.glassfish.javaee.full.deployment.EarDeployer.doOnAllBundles(EarDeployer.java:265)
at org.glassfish.javaee.full.deployment.EarDeployer.prepare(EarDeployer.java:150)
... 35 more
Caused by: Exception [EclipseLink-28018] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.EntityManagerSetupException
Exception Description: Predeployment of PersistenceUnit [ECOM-ejbPU] failed.
Internal Exception: Exception [EclipseLink-7158] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.ValidationException
Exception Description: Error encountered when building the #NamedQuery [Adresse.maxId] from entity class [class org.eclipse.persistence.internal.jpa.metadata.queries.NamedQueryMetadata].
Internal Exception: java.lang.ClassCastException: org.eclipse.persistence.jpa.jpql.parser.NullExpression cannot be cast to org.eclipse.persistence.jpa.jpql.parser.IdentificationVariable
at org.eclipse.persistence.exceptions.EntityManagerSetupException.predeployFailed(EntityManagerSetupException.java:230)
... 53 more
Caused by: Exception [EclipseLink-7158] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.ValidationException
Exception Description: Error encountered when building the #NamedQuery [Adresse.maxId] from entity class [class org.eclipse.persistence.internal.jpa.metadata.queries.NamedQueryMetadata].
Internal Exception: java.lang.ClassCastException: org.eclipse.persistence.jpa.jpql.parser.NullExpression cannot be cast to org.eclipse.persistence.jpa.jpql.parser.IdentificationVariable
at org.eclipse.persistence.exceptions.ValidationException.errorProcessingNamedQuery(ValidationException.java:824)
at org.
SEVERE: Exception while preparing the app
SEVERE: eclipse.persistence.internal.jpa.metadata.queries.NamedQueryMetadata.process(NamedQueryMetadata.java:194)
at org.eclipse.persistence.internal.jpa.metadata.MetadataProject.processQueries(MetadataProject.java:1628)
at org.eclipse.persistence.internal.jpa.metadata.MetadataProcessor.addNamedQueries(MetadataProcessor.java:148)
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.predeploy(EntityManagerSetupImpl.java:1894)
... 51 more
Caused by: java.lang.ClassCastException: org.eclipse.persistence.jpa.jpql.parser.NullExpression cannot be cast to org.eclipse.persistence.jpa.jpql.parser.IdentificationVariable
at org.eclipse.persistence.internal.jpa.jpql.DeclarationResolver$DeclarationVisitor.visit(DeclarationResolver.java:626)
at org.eclipse.persistence.jpa.jpql.parser.RangeVariableDeclaration.accept(RangeVariableDeclaration.java:98)
at org.eclipse.persistence.internal.jpa.jpql.DeclarationResolver$DeclarationVisitor.visit(DeclarationResolver.java:577)
at org.eclipse.persistence.jpa.jpql.parser.IdentificationVariableDeclaration.accept(IdentificationVariableDeclaration.java:71)
at org.eclipse.persistence.internal.jpa.jpql.DeclarationResolver$DeclarationVisitor.visit(DeclarationResolver.java:566)
at org.eclipse.persistence.jpa.jpql.parser.FromClause.accept(FromClause.java:48)
at org.eclipse.persistence.internal.jpa.jpql.DeclarationResolver.populateImp(DeclarationResolver.java:417)
at org.eclipse.persistence.internal.jpa.jpql.DeclarationResolver.populate(DeclarationResolver.java:407)
at org.eclipse.persistence.internal.jpa.jpql.JPQLQueryHelper$DescriptorCollector.collectDescriptors(JPQLQueryHelper.java:179)
at org.eclipse.persistence.internal.jpa.jpql.JPQLQueryHelper$DescriptorCollector.visit(JPQLQueryHelper.java:204)
at org.eclipse.persistence.jpa.jpql.parser.FromClause.accept(FromClause.java:48)
at org.eclipse.persistence.jpa.jpql.parser.AbstractSelectStatement.acceptChildren(AbstractSelectStatement.java:93)
at org.eclipse.persistence.jpa.jpql.parser.SelectStatement.acceptChildren(SelectStatement.java:110)
at org.eclipse.persistence.jpa.jpql.parser.AbstractTraverseChildrenVisitor.visit(AbstractTraverseChildrenVisitor.java:32)
at org.eclipse.persistence.jpa.jpql.parser.AnonymousExpressionVisitor.visit(AnonymousExpressionVisitor.java:470)
at org.eclipse.persistence.jpa.jpql.parser.SelectStatement.accept(SelectStatement.java:102)
at org.eclipse.persistence.jpa.jpql.parser.JPQLExpression.acceptChildren(JPQLExpression.java:143)
at org.eclipse.persistence.jpa.jpql.parser.AbstractTraverseChildrenVisitor.visit(AbstractTraverseChildrenVisitor.java:32)
at org.eclipse.persistence.jpa.jpql.parser.AnonymousExpressionVisitor.visit(AnonymousExpressionVisitor.java:302)
at org.eclipse.persistence.jpa.jpql.parser.JPQLExpression.accept(JPQLExpression.java:136)
at org.eclipse.persistence.internal.jpa.jpql.JPQLQueryHelper.getClassDescriptors(JPQLQueryHelper.java:87)
at org.eclipse.persistence.internal.jpa.metadata.queries.NamedQueryMetadata.addJPAQuery(NamedQueryMetadata.java:105)
at org.eclipse.persistence.internal.jpa.metadata.queries.NamedQueryMetadata.process(NamedQueryMetadata.java:192)
... 54 more
<code>
entity bean
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package entities;
import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* #author John624
*/
#Entity
#Table(name = "Adresse")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Adresse.maxId", query = "SELECT max(idAdresse) FROM Adresse"),
#NamedQuery(name = "Adresse.findAll", query = "SELECT a FROM Adresse a"),
#NamedQuery(name = "Adresse.findByIdAdresse", query = "SELECT a FROM Adresse a WHERE a.idAdresse = :idAdresse"),
#NamedQuery(name = "Adresse.findByNumEtRue", query = "SELECT a FROM Adresse a WHERE a.numEtRue = :numEtRue"),
#NamedQuery(name = "Adresse.findByComple", query = "SELECT a FROM Adresse a WHERE a.comple = :comple"),
#NamedQuery(name = "Adresse.findByCodePostale", query = "SELECT a FROM Adresse a WHERE a.codePostale = :codePostale"),
#NamedQuery(name = "Adresse.findByVille", query = "SELECT a FROM Adresse a WHERE a.ville = :ville"),
#NamedQuery(name = "Adresse.findByPays", query = "SELECT a FROM Adresse a WHERE a.pays = :pays"),
#NamedQuery(name = "Adresse.findByDateModif", query = "SELECT a FROM Adresse a WHERE a.dateModif = :dateModif")})
public class Adresse implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Column(name = "idAdresse")
private Long idAdresse;
#Size(max = 100)
#Column(name = "numEtRue")
private String numEtRue;
#Size(max = 100)
#Column(name = "comple")
private String comple;
#Size(max = 5)
#Column(name = "codePostale")
private String codePostale;
#Size(max = 35)
#Column(name = "ville")
private String ville;
#Size(max = 35)
#Column(name = "pays")
private String pays;
#Column(name = "dateModif")
#Temporal(TemporalType.DATE)
private Date dateModif;
#OneToMany(mappedBy = "adrU")
private Collection<Utilisateur> utilisateurCollection;
#OneToMany(mappedBy = "adrRecep")
private Collection<Livraison> livraisonCollection;
#OneToMany(mappedBy = "adrE")
private Collection<Entreprise> entrepriseCollection;
public Adresse() {
}
public Adresse(Long idAdresse) {
this.idAdresse = idAdresse;
}
public Long getIdAdresse() {
return idAdresse;
}
public void setIdAdresse(Long idAdresse) {
this.idAdresse = idAdresse;
}
public String getNumEtRue() {
return numEtRue;
}
public void setNumEtRue(String numEtRue) {
this.numEtRue = numEtRue;
}
public String getComple() {
return comple;
}
public void setComple(String comple) {
this.comple = comple;
}
public String getCodePostale() {
return codePostale;
}
public void setCodePostale(String codePostale) {
this.codePostale = codePostale;
}
public String getVille() {
return ville;
}
public void setVille(String ville) {
this.ville = ville;
}
public String getPays() {
return pays;
}
public void setPays(String pays) {
this.pays = pays;
}
public Date getDateModif() {
return dateModif;
}
public void setDateModif(Date dateModif) {
this.dateModif = dateModif;
}
#XmlTransient
public Collection<Utilisateur> getUtilisateurCollection() {
return utilisateurCollection;
}
public void setUtilisateurCollection(Collection<Utilisateur> utilisateurCollection) {
this.utilisateurCollection = utilisateurCollection;
}
#XmlTransient
public Collection<Livraison> getLivraisonCollection() {
return livraisonCollection;
}
public void setLivraisonCollection(Collection<Livraison> livraisonCollection) {
this.livraisonCollection = livraisonCollection;
}
#XmlTransient
public Collection<Entreprise> getEntrepriseCollection() {
return entrepriseCollection;
}
public void setEntrepriseCollection(Collection<Entreprise> entrepriseCollection) {
this.entrepriseCollection = entrepriseCollection;
}
#Override
public int hashCode() {
int hash = 0;
hash += (idAdresse != null ? idAdresse.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 Adresse)) {
return false;
}
Adresse other = (Adresse) object;
if ((this.idAdresse == null && other.idAdresse != null) || (this.idAdresse != null && !this.idAdresse.equals(other.idAdresse))) {
return false;
}
return true;
}
#Override
public String toString() {
return "entities.Adresse[ idAdresse=" + idAdresse + " ]";
}
}
session bean
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package session;
import entities.Adresse;
import java.util.List;
import javax.ejb.Stateless;
import javax.ejb.LocalBean;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
/**
*
* #author John624
*/
#Stateless
#LocalBean
public class AdresseManager {
#PersistenceContext(unitName = "ECOM-ejbPU")
private EntityManager em;
public List<Adresse> getAllAdresses() {
Query query=em.createNamedQuery("Adresse.findAll");
return query.getResultList();
}
public Adresse update(Adresse adresse) {
return em.merge(adresse);
}
public void persist(Object object) {
em.persist(object);
}
public Long nextId(){
Query query = em.createNamedQuery("Adresse.maxId");
long res;
res = query.getResultList().indexOf(0)+1;
return res;
}
}
JSF managedbean
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package managedbeans;
import entities.Adresse;
import java.io.Serializable;
import java.util.List;
import javax.ejb.EJB;
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;
import session.AdresseManager;
/**
*
* #author John624
*/
#Named(value="adresseMBean")
#SessionScoped
public class AdresseMBean implements Serializable{
private List<Adresse> adresses;
private Adresse adresse;
#EJB
private AdresseManager adresseManager;
public AdresseMBean() {
adresse=new Adresse();
adresseManager = new AdresseManager();
}
/**
* returns customer list for display in a datatable DataTable
* #return
*/
public List<Adresse> getAdresses() {
if((adresses == null) || (adresses.isEmpty()))
adresses = adresseManager.getAllAdresses();
return adresseManager.getAllAdresses();
}
// public void refresh() {
// tousLesComptes = compteBancaireFacade.findAll();
// }
/**
* returns details of a customer. Useful for displaying in a form a customer's details
* #return
*/
public Adresse getDetails() {
return adresse;
}
/**
* Action handler - Called when a line in the table is clicked
* #param adresse
* #return
*/
public String showDetails(Adresse adresse) {
this.adresse = adresse;
return "AdresseDetails"; // will display CustomerDetails.xml JSF page
}
/**
* Action handler - update the customer model in the database.
* called when one press the update button in the form
* #return
*/
public String update() {
System.out.println("###UPDATE###");
adresse = adresseManager.update(adresse);
return "AdresseList"; // will display the customer list in a table
}
/**
* Action handler - returns to the list of customers in the table
*/
public String list() {
System.out.println("###LIST###");
return "AdresseList";
}
public void update(Adresse adrU) {
System.out.println("###UPDATE###");
adresseManager.update(adrU);
}
}
Thanks in advance.

As indicated by the following exception stacktrace
Exception Description: Error encountered when building the #NamedQuery [Adresse.maxId] from entity class [class org.eclipse.persistence.internal.jpa.metadata.queries.NamedQueryMetadata].
the problem is here :
#NamedQuery(name = "Adresse.maxId", query = "SELECT max(idAdresse) FROM Adresse"),
To solve the problem, try this instead:
#NamedQuery(name = "Adresse.maxId", query = "SELECT max(a.idAdresse) FROM Adresse a"),

Try out these steps:
Undeploy the application from glassfish server.
Restart the glassfish server.
Restart netbeans.
Again deploy your application on the glassfish server.

Try to remove adresseManager = new AdresseManager(); from your AdresseMBean class.
#EJB injects and creates already the object.
Then try to redeploy the project and put a debug breakpoint in getAdresses method to see if adresseManager object isn't null or do a poor Sysout.
If you want to initialize services on starting of a managed bean, you'll need to use #PostConstruct annotation on a custom public method inside managed bean and code your initialisation there (eg. loading entity list from db).
Hope it will help you.
PS : Excuse my mistakes for english language, i'm French.
PS2 : I've not seen that it was working before, so it is perhaps a deployment problem !

Related

Problem in creating new instance using the default constructor. The default constructor triggered an exception

I'm having issues when trying to deploy my enterprise java bean application to GlassFish server 5.1.0. My errors are shown here:
Exception while deploying the app [ED-EMS-SLSB]|#]
Exception during lifecycle processing
org.glassfish.deployment.common.DeploymentException: Exception [EclipseLink-28019] (Eclipse Persistence Services - 2.7.4.v20190115-ad5b7c6b2a): org.eclipse.persistence.exceptions.EntityManagerSetupException
Exception Description: Deployment of PersistenceUnit [ED-EMS-SLSB-ejbPU] failed. Close all factories for this PersistenceUnit.
Internal Exception: Exception [EclipseLink-0] (Eclipse Persistence Services - 2.7.4.v20190115-ad5b7c6b2a): org.eclipse.persistence.exceptions.IntegrityException
Descriptor Exceptions:
---------------------------------------------------------
Exception [EclipseLink-168] (Eclipse Persistence Services - 2.7.4.v20190115-ad5b7c6b2a): org.eclipse.persistence.exceptions.DescriptorException
Exception Description: Problem in creating new instance using the default constructor. The default constructor triggered an exception.
Internal Exception: java.lang.reflect.InvocationTargetException
Target Invocation Exception: java.lang.RuntimeException:
Descriptor: RelationalDescriptor(entity.EmsEmployee --> [DatabaseTable(EMS_EMPLOYEE)])
Runtime Exceptions:
---------------------------------------------------------
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.createDeployFailedPersistenceException(EntityManagerSetupImpl.java:908)
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.deploy(EntityManagerSetupImpl.java:848)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryDelegate.getAbstractSession(EntityManagerFactoryDelegate.java:219)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryDelegate.createEntityManagerImpl(EntityManagerFactoryDelegate.java:327)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl.createEntityManagerImpl(EntityManagerFactoryImpl.java:350)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:313)
at org.glassfish.persistence.jpa.JPADeployer$2.visitPUD(JPADeployer.java:427)
at org.glassfish.persistence.jpa.JPADeployer$PersistenceUnitDescriptorIterator.iteratePUDs(JPADeployer.java:486)
at org.glassfish.persistence.jpa.JPADeployer.iterateInitializedPUsAtApplicationPrepare(JPADeployer.java:468)
at org.glassfish.persistence.jpa.JPADeployer.event(JPADeployer.java:371)
at org.glassfish.kernel.event.EventsImpl.send(EventsImpl.java:107)
at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:463)
at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:195)
at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:467)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:516)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$2$1.run(CommandRunnerImpl.java:512)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:360)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$2.execute(CommandRunnerImpl.java:511)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$3.run(CommandRunnerImpl.java:542)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$3.run(CommandRunnerImpl.java:534)
at java.security.AccessController.doPrivileged(Native Method)
at javax.security.auth.Subject.doAs(Subject.java:360)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:533)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1441)
at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1300(CommandRunnerImpl.java:86)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1823)
at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1699)
at com.sun.enterprise.v3.admin.AdminAdapter.doCommand(AdminAdapter.java:510)
at com.sun.enterprise.v3.admin.AdminAdapter.onMissingResource(AdminAdapter.java:200)
at org.glassfish.grizzly.http.server.StaticHttpHandlerBase.service(StaticHttpHandlerBase.java:166)
at com.sun.enterprise.v3.services.impl.ContainerMapper$HttpHandlerCallable.call(ContainerMapper.java:439)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:144)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:182)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:156)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:218)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:95)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:260)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:177)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:109)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:88)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:53)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:515)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:89)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:94)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:33)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:114)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:569)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:549)
at java.lang.Thread.run(Thread.java:748)
|#]
Exception while deploying the app [ED-EMS-SLSB] : Exception [EclipseLink-28019] (Eclipse Persistence Services - 2.7.4.v20190115-ad5b7c6b2a): org.eclipse.persistence.exceptions.EntityManagerSetupException
Exception Description: Deployment of PersistenceUnit [ED-EMS-SLSB-ejbPU] failed. Close all factories for this PersistenceUnit.
Internal Exception: Exception [EclipseLink-0] (Eclipse Persistence Services - 2.7.4.v20190115-ad5b7c6b2a): org.eclipse.persistence.exceptions.IntegrityException
Descriptor Exceptions:
---------------------------------------------------------
Exception [EclipseLink-168] (Eclipse Persistence Services - 2.7.4.v20190115-ad5b7c6b2a): org.eclipse.persistence.exceptions.DescriptorException
Exception Description: Problem in creating new instance using the default constructor. The default constructor triggered an exception.
Internal Exception: java.lang.reflect.InvocationTargetException
Target Invocation Exception: java.lang.RuntimeException:
Descriptor: RelationalDescriptor(entity.EmsEmployee --> [DatabaseTable(EMS_EMPLOYEE)])
Runtime Exceptions:
---------------------------------------------------------
|#]
I'm hoping someone could shed some light on this as this is my first time dealing with Enterprise Java Beans and I find it to be very difficult, considering that everything has to be setup a certain way. If anyone can recommend something or point me in the right direction, that'll be great.
Edit:
This is my entity class EmsEmployee.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package entity;
import java.io.Serializable;
import java.math.BigDecimal;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* #author jeremy
*/
#Entity
#Table(name = "EMS_EMPLOYEE")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "EmsEmployee.findAll", query = "SELECT e FROM EmsEmployee e"),
#NamedQuery(name = "EmsEmployee.findByEmpid", query = "SELECT e FROM EmsEmployee e WHERE e.empid = :empid"),
#NamedQuery(name = "EmsEmployee.findByName", query = "SELECT e FROM EmsEmployee e WHERE e.name = :name"),
#NamedQuery(name = "EmsEmployee.findByPassword", query = "SELECT e FROM EmsEmployee e WHERE e.password = :password"),
#NamedQuery(name = "EmsEmployee.findByEmail", query = "SELECT e FROM EmsEmployee e WHERE e.email = :email"),
#NamedQuery(name = "EmsEmployee.findByPhone", query = "SELECT e FROM EmsEmployee e WHERE e.phone = :phone"),
#NamedQuery(name = "EmsEmployee.findByAddress", query = "SELECT e FROM EmsEmployee e WHERE e.address = :address"),
#NamedQuery(name = "EmsEmployee.findBySecqn", query = "SELECT e FROM EmsEmployee e WHERE e.secqn = :secqn"),
#NamedQuery(name = "EmsEmployee.findBySecans", query = "SELECT e FROM EmsEmployee e WHERE e.secans = :secans"),
#NamedQuery(name = "EmsEmployee.findByBsbid", query = "SELECT e FROM EmsEmployee e WHERE e.bsbid = :bsbid"),
#NamedQuery(name = "EmsEmployee.findByAccid", query = "SELECT e FROM EmsEmployee e WHERE e.accid = :accid"),
#NamedQuery(name = "EmsEmployee.findBySalary", query = "SELECT e FROM EmsEmployee e WHERE e.salary = :salary"),
#NamedQuery(name = "EmsEmployee.findByAppgroup", query = "SELECT e FROM EmsEmployee e WHERE e.appgroup = :appgroup"),
#NamedQuery(name = "EmsEmployee.findByActive", query = "SELECT e FROM EmsEmployee e WHERE e.active = :active"),
#NamedQuery(name = "EmsEmployee.findByMemo", query = "SELECT e FROM EmsEmployee e WHERE e.memo = :memo")})
public class EmsEmployee implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 6)
#Column(name = "EMPID")
private String empid;
#Size(max = 50)
#Column(name = "NAME")
private String name;
#Size(max = 64)
#Column(name = "PASSWORD")
private String password;
// #Pattern(regexp="[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", message="Invalid email")//if the field contains email address consider using this annotation to enforce field validation
#Size(max = 50)
#Column(name = "EMAIL")
private String email;
// #Pattern(regexp="^\\(?(\\d{3})\\)?[- ]?(\\d{3})[- ]?(\\d{4})$", message="Invalid phone/fax format, should be as xxx-xxx-xxxx")//if the field contains phone or fax number consider using this annotation to enforce field validation
#Size(max = 10)
#Column(name = "PHONE")
private String phone;
#Size(max = 50)
#Column(name = "ADDRESS")
private String address;
#Size(max = 60)
#Column(name = "SECQN")
private String secqn;
#Size(max = 60)
#Column(name = "SECANS")
private String secans;
#Size(max = 6)
#Column(name = "BSBID")
private String bsbid;
#Size(max = 10)
#Column(name = "ACCID")
private String accid;
// #Max(value=?) #Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
#Column(name = "SALARY")
private BigDecimal salary;
#Size(max = 15)
#Column(name = "APPGROUP")
private String appgroup;
#Column(name = "ACTIVE")
private Boolean active;
#Size(max = 255)
#Column(name = "MEMO")
private String memo;
public EmsEmployee() {
}
public EmsEmployee(String empid) {
this.empid = empid;
}
public String getEmpid() {
return empid;
}
public void setEmpid(String empid) {
this.empid = empid;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getSecqn() {
return secqn;
}
public void setSecqn(String secqn) {
this.secqn = secqn;
}
public String getSecans() {
return secans;
}
public void setSecans(String secans) {
this.secans = secans;
}
public String getBsbid() {
return bsbid;
}
public void setBsbid(String bsbid) {
this.bsbid = bsbid;
}
public String getAccid() {
return accid;
}
public void setAccid(String accid) {
this.accid = accid;
}
public BigDecimal getSalary() {
return salary;
}
public void setSalary(BigDecimal salary) {
this.salary = salary;
}
public String getAppgroup() {
return appgroup;
}
public void setAppgroup(String appgroup) {
this.appgroup = appgroup;
}
public Boolean getActive() {
return active;
}
public void setActive(Boolean active) {
this.active = active;
}
public String getMemo() {
return memo;
}
public void setMemo(String memo) {
this.memo = memo;
}
#Override
public int hashCode() {
int hash = 0;
hash += (empid != null ? empid.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 EmsEmployee)) {
return false;
}
EmsEmployee other = (EmsEmployee) object;
if ((this.empid == null && other.empid != null) || (this.empid != null && !this.empid.equals(other.empid))) {
return false;
}
return true;
}
#Override
public String toString() {
return "entity.EmsEmployee[ empid=" + empid + " ]";
}
}
This is my stateless session bean class EmsEmployeeFacade.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package session;
import entity.EmsEmployee;
import entity.EmsEmployeeDTO;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
/**
*
* #author jeremy
*/
#Stateless
public class EmsEmployeeFacade implements EmsEmployeeFacadeRemote {
#PersistenceContext(unitName = "ED-EMS-SLSB-ejbPU")
private EntityManager em;
protected EntityManager getEntityManager() {
return em;
}
private void create(EmsEmployee emsEmployee) {
em.persist(emsEmployee);
}
private void edit(EmsEmployee emsEmployee) {
em.merge(emsEmployee);
}
private void remove(EmsEmployee emsEmployee) {
em.remove(em.merge(emsEmployee));
}
private EmsEmployee find(Object id) {
return em.find(EmsEmployee.class, id);
}
private EmsEmployee myDTO2DAO(EmsEmployeeDTO emsEmployeeDTO) {
EmsEmployee emsEmployee = new EmsEmployee();
emsEmployee.setEmpid(emsEmployeeDTO.getEmpid());
emsEmployee.setName(emsEmployeeDTO.getName());
emsEmployee.setPassword(emsEmployeeDTO.getPassword());
emsEmployee.setEmail(emsEmployeeDTO.getEmail());
emsEmployee.setPhone(emsEmployeeDTO.getPhone());
emsEmployee.setAddress(emsEmployeeDTO.getAddress());
emsEmployee.setSecqn(emsEmployeeDTO.getSecqn());
emsEmployee.setSecans(emsEmployeeDTO.getSecans());
emsEmployee.setBsbid(emsEmployeeDTO.getBsbid());
emsEmployee.setAccid(emsEmployeeDTO.getAccid());
emsEmployee.setSalary(emsEmployeeDTO.getSalary());
emsEmployee.setAppgroup(emsEmployeeDTO.getAppgroup());
emsEmployee.setActive(emsEmployeeDTO.getActive());
emsEmployee.setMemo(emsEmployeeDTO.getMemo());
return emsEmployee;
}
#Override
public boolean createRecord(EmsEmployeeDTO emsEmployeeDTO) {
// try to find the database record in the database first
EmsEmployee tmpEmployee = em.find(EmsEmployee.class, emsEmployeeDTO.getEmpid());
if (tmpEmployee != null) {
// employee whose empid can be found; should not add the record
return false;
}
// employee whose empid could not be found; add it to the database
try {
// convert a DTO to DAO
EmsEmployee emsEmployee = this.myDTO2DAO(emsEmployeeDTO);
// add to database via JPA
this.create(emsEmployee);
return true;
} catch (Exception ex) {
// something is wrong, should not be here though
return false;
}
}
}
You are using GlassFish 5.1.0 and this only supports Java 8.
I assume that you are using a newer Java version (probably 14) that causes this exception.

Insert data using JPA one to one mapping along with mysql composite primary keys

i want to insert data using JPA one to one mapping along with composite primary key in mysql .Already lot of questions asked for the same topic in this forum, but that not helped for me.
But i got exceptions like "illegal argument exception is not a known entity type jpa" and "Table 'callredirect.callredirect_callredirectgroup' doesn't exist"
My mysql tables:
CREATE TABLE IF NOT EXISTS `CallRedirect` (
`redirect_id` varchar(20) NOT NULL,
`ric` varchar(20) NOT NULL,
`tgrp` varchar (20) NOT NULL,
`loop_ind` varchar(4) NOT NULL,
PRIMARY KEY (`redirect_id`));
CREATE TABLE IF NOT EXISTS `CallRedirectGroup` (
`msisdn` varchar(20) NOT NULL,
`redirect_id` varchar(20) NOT NULL ,
PRIMARY KEY (`msisdn`,`redirect_id`),
FOREIGN KEY (redirect_id) REFERENCES CallRedirect(redirect_id));
CallRedirect.java:
package com.sample.rest.dao.entity;
import java.io.Serializable;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.IdClass;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.QueryHint;
import javax.persistence.Table;
import org.codehaus.jackson.annotate.JsonProperty;
import org.eclipse.persistence.annotations.PrivateOwned;
#Entity
#NamedQueries({
#NamedQuery(name = "getCallRedirectById", query = "SELECT a FROM CallRedirect a WHERE a.redirect_id=:redirect_id", hints = #QueryHint(name = "eclipselink.refresh", value = "true")),
#NamedQuery(name = "getAllCallRedirect", query = "SELECT a FROM CallRedirect a order by a.redirect_id", hints = #QueryHint(name = "eclipselink.refresh", value = "true"))
//#NamedQuery(name = "deleteCallRedirectById", query = "DELETE a FROM CallRedirect a WHERE a.redirect_id=:redirect_id", hints = #QueryHint(name = "eclipselink.refresh", value = "true"))
})
#Table(name = "callRedirect")
public class CallRedirect implements Serializable{
#Id
#JsonProperty("redirect_id")
#Column(name = "redirect_id")
private String redirect_id;
#Column(name = "ric")
#JsonProperty("ric")
private String ric;
#Column(name = "tgrp")
#JsonProperty("tgrp")
private String tgrp;
#Column(name = "loop_ind")
#JsonProperty("loop_ind")
private String loop_ind;
#OneToOne(mappedBy = "callRedirect", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#PrivateOwned
private List<CallRedirectGroup> callRedirectGroupEntity;
public CallRedirect() {
super();
}
/**
* #return the redirect_id
*/
public String getRedirectId()
{
return redirect_id;
}
/**
* #param redirect_id
* the redirect_id to set
*/
public void setRedirectId(String redirect_id)
{
this.redirect_id = redirect_id;
}
/**
* #return the ric
*/
public String getRic()
{
return ric;
}
/**
* #param ric
* the ric to set
*/
public void setRic(String ric)
{
this.ric = ric;
}
/**
* #return the tgrp
*/
public String getTgrp()
{
return tgrp;
}
/**
* #param tgrp
* the tgrp to set
*/
public void setTgrp(String tgrp)
{
this.tgrp = tgrp;
}
/**
* #return the loop_ind
*/
public String getLoopInd()
{
return loop_ind;
}
/**
* #param loop_ind
* the loop_ind to set
*/
public void setLoopInd(String loop_ind)
{
this.loop_ind = loop_ind;
}
/**
* #return the callRedirectGroupEntity
*/
public List<CallRedirectGroup> getCallRedirectGroupEntity()
{
return callRedirectGroupEntity;
}
/**
* #param callRedirectGroupEntity
* the callRedirectGroupEntity to set
*/
public void setCallRedirectGroupEntity(List<CallRedirectGroup> callRedirectGroupEntity)
{
this.callRedirectGroupEntity = callRedirectGroupEntity;
}
#Override
public String toString()
{
return "CallRedirect :: redirect_id: " + redirect_id + ", Ric : " + ric + ", Tgrp : " + tgrp + ", loop_ind : "
+ loop_ind;
}
}
CallRedirectGroup.java:
package com.sample.rest.dao.entity;
import java.io.Serializable;
import java.util.*;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.IdClass;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedNativeQueries;
import javax.persistence.NamedNativeQuery;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToOne;
import javax.persistence.QueryHint;
import javax.persistence.Table;
import org.codehaus.jackson.annotate.JsonProperty;
import org.eclipse.persistence.annotations.PrivateOwned;
#Entity
#NamedQueries({
#NamedQuery(name = "getRedirectIdByMSISDN", query = "SELECT a FROM CallRedirectGroup a WHERE a.msisdn=:msisdn", hints = #QueryHint(name = "eclipselink.refresh", value = "true"))
//#NamedQuery(name = "getAllCallRedirect", query = "SELECT a FROM CallRedirectGroup a order by a.redirect_id", hints = #QueryHint(name = "eclipselink.refresh", value = "true")),
})
#NamedNativeQueries({
#NamedNativeQuery(
name = "createNewCallRedirectGroup",
query = "INSERT INTO CallRedirect(redirect_id,ric,tgrp,loop_ind) VALUES (?,?,?,?)"
,resultSetMapping = "updateResult"
)
})
#Table(name = "CallRedirectGroup")
public class CallRedirectGroup implements Serializable{
#Id
#Column(name = "msisdn")
#JsonProperty("msisdn")
private String msisdn;
#OneToOne
#JoinColumn(name = "redirect_id")
private CallRedirect callRedirect;
public CallRedirectGroup() {
super();
}
public String getMsisdn()
{
return msisdn;
}
public void setMsisdn(String msisdn)
{
this.msisdn = msisdn;
}
public CallRedirect getCallRedirect()
{
return callRedirect;
}
public void setCallRedirect(CallRedirect callRedirect)
{
this.callRedirect = callRedirect;
/*List<CallRedirectGroup> list = new ArrayList<CallRedirectGroup>();
list.add(this);
this.callRedirect.setCallRedirectGroupEntity(list);*/
}
#Override
public String toString()
{
return "CallRedirectGroup - " + callRedirect + ", Msisdn : " + msisdn;
}
}
CallRedirectDAO.java:
public class CallRedirectDaoImpl implements CallRedirectDao{
#PersistenceContext(unitName = "CALLREDIRECT_PERSISTENCE_READ")
private EntityManagerFactory entityManagerFactoryRead = Persistence.createEntityManagerFactory("CALLREDIRECT_PERSISTENCE_READ");
EntityManager entityManager = entityManagerFactoryRead.createEntityManager();
public boolean createNewRedirectGroup(CallRedirectGroup callredirectgroup) {
boolean result = false;
try
{
List<CallRedirectGroup> list = new ArrayList<CallRedirectGroup>();
list.add(callredirectgroup);
CallRedirect callredirect = callredirectgroup.getCallRedirect();
callredirect.setCallRedirectGroupEntity(list);
entityManager.getTransaction().begin();
entityManager.persist(callredirect);
entityManager.persist(callredirectgroup);
entityManager.getTransaction().commit();
entityManager.flush();
result = true;
}
catch (PersistenceException persistenceException)
{
result = false;
if(entityManager.getTransaction().isActive())
entityManager.getTransaction().rollback();
LOGGER.log(Level.SEVERE, "Unexpected error while creating new callRedirectGroup: " +callredirectgroup);
}
catch (Exception e)
{
result = false;
if(entityManager.getTransaction().isActive())
entityManager.getTransaction().rollback();
LOGGER.log(Level.SEVERE, " while creating new callRedirectGroup, Exception = ", e);
}
finally
{
entityManager.clear();
}
return result;
}
Persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="1.0">
<persistence-unit name="CALLREDIRECT_PERSISTENCE_READ" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>jdbc/callRedirectRead</jta-data-source>
<class>com.sample.rest.dao.entity.CallRedirect</class>
<class>com.sample.rest.dao.entity.CallRedirectGroup</class>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="eclipselink.jpa.uppercase-column-names" value="false"/>
</properties>
</persistence-unit>
</persistence>
INPUT as JSON:
{
"callRedirect": {
"redirect_id": "RED002",
"ric": "ric1",
"tgrp": "tgrp1",
"loop_ind": "TES"
},
"msisdn": "887055"
}
Exception:
1.javax.persistence.RollbackException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.0.2.v20100323-r6872): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.MySQLSyntaxErrorException: Table 'callredirect.callredirect_callredirectgroup' doesn't exist
Error Code: 1146
Call: INSERT INTO callRedirect_CallRedirectGroup (callRedirectGroupEntity_msisdn, CallRedirect_redirect_id) VALUES (?, ?)
bind => [887055, RED002]
Query: DataModifyQuery(sql="INSERT INTO callRedirect_CallRedirectGroup (callRedirectGroupEntity_msisdn, CallRedirect_redirect_id) VALUES (?, ?)")
2.java.lang.IllegalArgumentException: Object: CallRedirect :: redirect_id: RED003, Ric : ric1, Tgrp : tgrp1, loop_ind : TES is not a known entity type.
you are using OneToOne for list , you should be using OneToMany and ManyToOne
#OneToMany(mappedBy = "callRedirect", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#PrivateOwned
private List<CallRedirectGroup> callRedirectGroupEntity;
#ManyToOne
#JoinColumn(name = "redirect_id")
private CallRedirect callRedirect;

QueryException in Hibernate

I am using the following bean class
package com.hibernatemappingfile;
import java.io.Serializable;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;
#Entity
#Table(name="SKILL_SET")
public class SkillSet implements Serializable{
#Id
#Column(name="ID")
#GeneratedValue(strategy=GenerationType.AUTO)
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#Column(name="COMPUTER_SKILLS")
private String computer_skills;
#Column(name="TRAININGS_ATTENDED")
private String trainings_attended;
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "USER_ID")
private EmployeeMaster employee;
public EmployeeMaster getEmployee() {
return employee;
}
public void setEmployee(EmployeeMaster employee) {
this.employee = employee;
}
public String getComputer_skills() {
return computer_skills;
}
public void setComputer_skills(String computer_skills) {
this.computer_skills = computer_skills;
}
public String getTrainings_attended() {
return trainings_attended;
}
public void setTrainings_attended(String trainings_attended) {
this.trainings_attended = trainings_attended;
}
}
and my hql query is
SELECT t1.trainings_attended,t2.workingstatus
FROM SkillSet t1, EmployeeStatus t2,EmployeeMaster em
WHERE t1.trainings_attended=:trainings_attended AND t1.USER_ID = t2.USER_ID
but i am getting the following exception
SEVERE: Servlet.service() for servlet [sdnext] in context with path [/sdnext] threw exception [Request processing failed; nested exception is org.hibernate.QueryException: could not resolve property: USER_ID of: com.vrnda.hibernatemappingfile.SkillSet [SELECT t1.trainings_attended,t2.workingstatus FROM com.vrnda.hibernatemappingfile.SkillSet t1, com.vrnda.hibernatemappingfile.EmployeeStatus t2,com.vrnda.hibernatemappingfile.EmployeeMaster em WHERE t1.trainings_attended=:trainings_attended AND t1.USER_ID = t2.USER_ID]] with root cause
org.hibernate.QueryException: could not resolve property: USER_ID of: com.vrnda.hibernatemappingfile.SkillSet [SELECT t1.trainings_attended,t2.workingstatus FROM com.vrnda.hibernatemappingfile.SkillSet t1, com.vrnda.hibernatemappingfile.EmployeeStatus t2,com.vrnda.hibernatemappingfile.EmployeeMaster em WHERE t1.trainings_attended=:trainings_attended AND t1.USER_ID = t2.USER_ID]
How to get the user_id of skillset table in select statement.i have tried with t1.em.USER_ID but not working.
try JOIN t1.employee employee and then you will have access to employee.user_id

Getting java.lang.ExceptionInInitializerError

I am creating a small program for a school exercise. I have no clue where I could have done anything wrong. Could someone please help me with this?
I get this error when I run my test. I get the error at the this.emf = TestUtil.getEMF(); line.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package herkansing;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
#Entity
#NamedQueries({
#NamedQuery(name = "Account.getAll", query = "select a from Account as a"),
#NamedQuery(name = "Account.count", query = "select count(a) from Account as a"),
#NamedQuery(name = "Account.findByAccountNr", query = "select a from Account as a where a.accountNr = :accountNr")
})
public class Player implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long Id;
private Long accountNr;
private String email;
private Long money;
private Long points;
public Player() {
}
public Player(Long accountNr){
money = 0L;
points = 0L;
this.accountNr = accountNr;
}
//<editor-fold defaultstate="collapsed" desc="getters and setters ....">
public Boolean add(Long amount) {
if (money + amount >= points) {
money += amount;
return true;
} else {
return false;
}
}
public Long getId() {
return Id;
}
public void setId(Long id) {
this.Id = id;
}
public Long getAccountNr() {
return accountNr;
}
public void setAccountNr(Long nr) {
this.accountNr = nr;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Long getMoney() {
return money;
}
public void setMoney(Long money) {
this.money = money;
}
public Long getPoints() {
return points;
}
public void setPoints(Long points) {
this.points = points;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Player other = (Player) obj;
if (this.accountNr != other.accountNr && (this.accountNr == null || !this.accountNr.equals(other.accountNr))) {
return false;
}
if (this.money != other.money && (this.money == null || !this.money.equals(other.money))) {
return false;
}
if (this.points != other.points && (this.points == null || !this.points.equals(other.points))) {
return false;
}
return true;
}
}
Player class
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" 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">
<persistence-unit name="playerPU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>herkansing.Player</class>
<shared-cache-mode>NONE</shared-cache-mode>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/?user=root"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.password" value="root"/>
<property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
<!--adds logging-->
<property name="eclipselink.logging.logger" value="DefaultLogger"/>
<property name="eclipselink.logging.level" value="FINE"/>
</properties>
</persistence-unit>
</persistence>
persistence.xml
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package herkansing;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
/**
*
* #author Bart
*/
public class TestUtil {
static final EntityManagerFactory emf = Persistence.createEntityManagerFactory("playerPU");
/**
*
* #return the number of Accounts stored in the database
*/
static public int getNrOfAccountRecordsInDB() {
EntityManager em = getEMF().createEntityManager();
return ((Number) em.createNamedQuery("Player.count").getSingleResult()).intValue();
}
/**
* Search for an entity of the specified class and primary key.
*
* #param id
* #return the found Account instance or null if the entity does not exist
*/
static public Player getAccountById(Long id) {
EntityManager em = getEMF().createEntityManager();
return em.find(Player.class, id);
}
static public EntityManagerFactory getEMF() {
return emf;
}
}
TestUtil class
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package herkansingTest;
import herkansing.TestUtil;
import herkansing.DatabaseCleaner;
import herkansing.Player;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* #author Bart
*/
public class PlayerTest {
final EntityManagerFactory emf;
EntityManager em, em1, em2;
private static final Logger LOG = Logger.getLogger(PlayerTest.class.getName());
public PlayerTest() {
this.emf = TestUtil.getEMF();
}
#Before
public void setUp() {
em = emf.createEntityManager();
em1 = emf.createEntityManager();
em2 = emf.createEntityManager();
new DatabaseCleaner().resetDatabase();
}
}
PlayerTest
java.lang.ExceptionInInitializerError
at herkansingTest.PlayerTest.<init>(PlayerTest.java:34)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
at org.junit.runners.BlockJUnit4ClassRunner.createTest(BlockJUnit4ClassRunner.java:217)
at org.junit.runners.BlockJUnit4ClassRunner$1.runReflectiveCall(BlockJUnit4ClassRunner.java:266)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.BlockJUnit4ClassRunner.methodBlock(BlockJUnit4ClassRunner.java:263)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:53)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:123)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:104)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:164)
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:110)
at org.apache.maven.surefire.booter.SurefireStarter.invokeProvider(SurefireStarter.java:175)
at org.apache.maven.surefire.booter.SurefireStarter.runSuitesInProcessWhenForked(SurefireStarter.java:107)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:68)
Caused by: javax.persistence.PersistenceException: Exception [EclipseLink-28019] (Eclipse Persistence Services - 2.6.0.v20150309-bf26070): org.eclipse.persistence.exceptions.EntityManagerSetupException
Exception Description: Deployment of PersistenceUnit [playerPU] failed. Close all factories for this PersistenceUnit.
Internal Exception: Exception [EclipseLink-0] (Eclipse Persistence Services - 2.6.0.v20150309-bf26070): org.eclipse.persistence.exceptions.JPQLException
Exception Description: Problem compiling [select a from Account as a].
[14, 21] The abstract schema type 'Account' is unknown.
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.createDeployFailedPersistenceException(EntityManagerSetupImpl.java:866)
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.deploy(EntityManagerSetupImpl.java:806)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryDelegate.getAbstractSession(EntityManagerFactoryDelegate.java:205)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryDelegate.getDatabaseSession(EntityManagerFactoryDelegate.java:183)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryImpl.getDatabaseSession(EntityManagerFactoryImpl.java:528)
at org.eclipse.persistence.jpa.PersistenceProvider.createEntityManagerFactoryImpl(PersistenceProvider.java:146)
at org.eclipse.persistence.jpa.PersistenceProvider.createEntityManagerFactory(PersistenceProvider.java:183)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:79)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:54)
at herkansing.TestUtil.<clinit>(TestUtil.java:18)
... 31 more
Caused by: Exception [EclipseLink-28019] (Eclipse Persistence Services - 2.6.0.v20150309-bf26070): org.eclipse.persistence.exceptions.EntityManagerSetupException
Exception Description: Deployment of PersistenceUnit [playerPU] failed. Close all factories for this PersistenceUnit.
Internal Exception: Exception [EclipseLink-0] (Eclipse Persistence Services - 2.6.0.v20150309-bf26070): org.eclipse.persistence.exceptions.JPQLException
Exception Description: Problem compiling [select a from Account as a].
[14, 21] The abstract schema type 'Account' is unknown.
at org.eclipse.persistence.exceptions.EntityManagerSetupException.deployFailed(EntityManagerSetupException.java:239)
... 41 more
Caused by: Exception [EclipseLink-0] (Eclipse Persistence Services - 2.6.0.v20150309-bf26070): org.eclipse.persistence.exceptions.JPQLException
Exception Description: Problem compiling [select a from Account as a].
[14, 21] The abstract schema type 'Account' is unknown.
at org.eclipse.persistence.internal.jpa.jpql.HermesParser.buildException(HermesParser.java:155)
at org.eclipse.persistence.internal.jpa.jpql.HermesParser.validate(HermesParser.java:347)
at org.eclipse.persistence.internal.jpa.jpql.HermesParser.populateQueryImp(HermesParser.java:278)
at org.eclipse.persistence.internal.jpa.jpql.HermesParser.buildQuery(HermesParser.java:163)
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.buildEJBQLDatabaseQuery(EJBQueryImpl.java:142)
at org.eclipse.persistence.internal.jpa.JPAQuery.processJPQLQuery(JPAQuery.java:223)
at org.eclipse.persistence.internal.jpa.JPAQuery.prepare(JPAQuery.java:184)
at org.eclipse.persistence.queries.DatabaseQuery.prepareInternal(DatabaseQuery.java:624)
at org.eclipse.persistence.internal.sessions.AbstractSession.processJPAQuery(AbstractSession.java:4363)
at org.eclipse.persistence.internal.sessions.AbstractSession.processJPAQueries(AbstractSession.java:4323)
at org.eclipse.persistence.internal.sessions.DatabaseSessionImpl.initializeDescriptors(DatabaseSessionImpl.java:584)
at org.eclipse.persistence.internal.sessions.DatabaseSessionImpl.postConnectDatasource(DatabaseSessionImpl.java:804)
at org.eclipse.persistence.internal.sessions.DatabaseSessionImpl.loginAndDetectDatasource(DatabaseSessionImpl.java:748)
at org.eclipse.persistence.internal.jpa.EntityManagerFactoryProvider.login(EntityManagerFactoryProvider.java:253)
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.deploy(EntityManagerSetupImpl.java:728)
... 39 more
The Stacktrace
You can see the cause in the stacktrace here:
Exception Description: Problem compiling [select a from Account as a].
[14, 21] The abstract schema type 'Account' is unknown.
JPA was unable to locate the Account entity and could not create the EntityManagerFactory.
You have to list all the entities in persistence.xml like you listed the Playerclass:
<class>herkansing.Player</class>
<class>herkansing.Account</class>
...
Even if you are not using the Account entity explicitly in your code, there is a named query that references it and JPA tries to validate this query and gives you the exception:
#NamedQueries({
#NamedQuery(name = "Account.getAll", query = "select a from Account as a"),
#NamedQuery(name = "Account.count", query = "select count(a) from Account as a"),
#NamedQuery(name = "Account.findByAccountNr", query = "select a from Account as a where a.accountNr = :accountNr")
})
Alternatively, you could delete the #NamedQueries declaration.

Hibernate + Spring exception: Unknown Entity

i am getting exception while the server starts. (Server is started using Intelij IDE).
i have no idea how to fix it. i am new to hibernate and spring. thanks in advance.
SEVERE: Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'authenticationMgr' defined in URL [jar:file:/C:/Program%20Files%20(x86)/Apache%20Software%20Foundation/Tomcat%207.0/webapps/ROOT/WEB-INF/lib/dbservice-1.0-SNAPSHOT.jar!/ApplicationContext-Service.xml]: Error setting property values; nested exception is org.springframework.beans.PropertyBatchUpdateException; nested PropertyAccessExceptions (1) are:
PropertyAccessException 1: org.springframework.beans.MethodInvocationException: Property 'authenticationDao' threw exception; nested exception is org.springframework.orm.hibernate3.HibernateSystemException: Unknown entity: com.jsi.core.dbservice.model.Authentication; nested exception is org.hibernate.MappingException: Unknown entity: com.jsi.core.dbservice.model.Authentication
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1361)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1086)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:580)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:871)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:423)
at org.springframework.web.context.ContextLoader.createWebApplicationContext(ContextLoader.java:276)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:197)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:47)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:4681)
at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5184)
at org.apache.catalina.core.StandardContext$1.call(StandardContext.java:5179)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
at java.util.concurrent.FutureTask.run(FutureTask.java:138)
at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:885)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:907)
at java.lang.Thread.run(Thread.java:619)
Caused by: org.springframework.beans.PropertyBatchUpdateException; nested PropertyAccessExceptions (1) are:
PropertyAccessException 1: org.springframework.beans.MethodInvocationException: Property 'authenticationDao' threw exception; nested exception is org.springframework.orm.hibernate3.HibernateSystemException: Unknown entity: com.jsi.core.dbservice.model.Authentication; nested exception is org.hibernate.MappingException: Unknown entity: com.jsi.core.dbservice.model.Authentication
at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:102)
at org.springframework.beans.AbstractPropertyAccessor.setPropertyValues(AbstractPropertyAccessor.java:58)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1358)
... 21 more
Authentication entity
/**
* Authentication Entity - Representation of the db table
*/
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
#Entity
#Table(name = "t_authentication")
public class Authentication extends LongBaseEntity implements Serializable{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "auth_id")
private Long mAuthId;
#Column(name = "authentication_id")
private Long mAuthenticationId;
#Column(name = "tcn")
private Long mTcn;
#Column(name = "audit_comment")
private String mAuditComment;
#Column(name = "last_timestamp")
private Date mLastTimeStamp;
#Column(name = "user_id")
private Long mUserId;
#Column(name = "authentication_date")
private Date mAuthenticationDate;
#Column(name = "hostname")
private String mHostname;
#Column(name = "ip_address")
private String mIpAddress;
#Column(name = "referrer_url")
private String mReferrerURL;
#Column(name = "session_id")
private String mSessionId;
public Long getAuthId() {
return mAuthId;
}
public void setAuthId(Long pAuthId) {
this.mAuthId = pAuthId;
mId = pAuthId;
}
public Long getAuthenticationId() {
return mAuthenticationId;
}
public void setAuthenticationId(Long pAuthenticationId) {
this.mAuthenticationId = pAuthenticationId;
}
public Long getTcn() {
return mTcn;
}
public void setTcn(Long pTcn) {
this.mTcn = pTcn;
}
public String getAuditComment() {
return mAuditComment;
}
public void setAuditComment(String pAuditComment) {
this.mAuditComment = pAuditComment;
}
public Date getLastTimeStamp() {
return mLastTimeStamp;
}
public void setLastTimeStamp(Date pLastTimeStamp) {
this.mLastTimeStamp = pLastTimeStamp;
}
public Long getUserId() {
return mUserId;
}
public void setUserId(Long pUserId) {
this.mUserId = pUserId;
}
public Date getAuthenticationDate() {
return mAuthenticationDate;
}
public void setAuthenticationDate(Date pAuthenticationDate) {
this.mAuthenticationDate = pAuthenticationDate;
}
public String getHostname() {
return mHostname;
}
public void setHostname(String pHostname) {
this.mHostname = pHostname;
}
public String getIpAddress() {
return mIpAddress;
}
public void setIpAddress(String pIpAddress) {
this.mIpAddress = pIpAddress;
}
public String getReferrerURL() {
return mReferrerURL;
}
public void setReferrerURL(String pReferrerURL) {
this.mReferrerURL = pReferrerURL;
}
public String getSessionId() {
return mSessionId;
}
public void setSessionId(String pSessionId) {
this.mSessionId = pSessionId;
}
public String toString() {
return "Payment{" +
"mId=" + getId() +
", mIpaddress=" + mIpAddress +
'}';
}
}
DAO class:
/**
* Implementation for AuthenticationMgr DAO layer.
*
*/
import com.jsi.core.dbservice.model.Authentication;
import com.jsi.core.dbservice.model.JSIException;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import java.sql.SQLException;
import java.util.List;
public class AuthenticationDao extends HibernateDaoSupport implements IAuthenticationDao {
#Override
public List<Authentication> list() {
final String query = "Select a from Authentication a order by a.id desc";
return (List<Authentication>) getHibernateTemplate().executeFind(new HibernateCallback() {
public Object doInHibernate(Session session) throws HibernateException, SQLException {
return session.createQuery(query).list();
}
});
}
#Override
public void save(Authentication authentication) throws JSIException {
getHibernateTemplate().save(authentication);
}
#Override
public Authentication load(Long id) {
return getHibernateTemplate().load(Authentication.class, id);
}
#Override
public void update(Authentication authentication) throws JSIException {
getHibernateTemplate().update(authentication);
}
#Override
public void delete(Long id) {
getHibernateTemplate().delete(load(id));
}
}
If you are happened to use HibernateUtil to manipulate the data, you need to add annotated class to your configuration.
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
sessionFactory = new AnnotationConfiguration().addAnnotatedClass(Authentication.class)
.configure()
.buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
http://docs.jboss.org/hibernate/stable/annotations/reference/en/html/ch01.html
thanks everyone for your reply. i managed to solve it. it was my mistake. i forgot to add the mapping tag in xml.
<hibernate-configuration>
<session-factory>
<mapping class="com.model.Authentication"/> // i missed this line. after i added it. it worked fine.
</session-factory>
</hibernate-configuration>
thanks again.

Categories

Resources