I'm beginner Java programmer
I want to run a query with JPQL, but I give an error message
error message
Caused by: Exception [EclipseLink-0] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.JPQLException
Exception Description: Syntax error parsing [select u from user u where u.email = :pr1 and u.password = : pr2].
[27, 64] The expression is not a valid conditional expression.
at org.eclipse.persistence.internal.jpa.jpql.HermesParser.buildException(HermesParser.java:155)
at org.eclipse.persistence.internal.jpa.jpql.HermesParser.validate(HermesParser.java:334)
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.EJBQueryImpl.buildEJBQLDatabaseQuery(EJBQueryImpl.java:116)
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.<init>(EJBQueryImpl.java:102)
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.<init>(EJBQueryImpl.java:86)
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.createQuery(EntityManagerImpl.java:1583)
... 85 more
query
#EJB
private UserFacade usersfacede;
private String redirect;
public void dologin(){
String query1 ="select u from user u where u.email = :pr1 and u.password = : pr2";
List<User> loginuser = usersfacede.araStr(query1, email.trim(), password.trim(), "", "", "");
if(loginuser.size()>0){
Util.setSessionAttribute("name", loginuser.get(0).getName());
redirect="index.xhtml?faces-redirect=true";
}else{
redirect="";
FacesContext context = FacesContext.getCurrentInstance();
context.addMessage(null, new FacesMessage("error", "") );
}
}
make UserFacede extends AbstractFacade
arastr function in AbstractFacade.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 com.entity;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
/**
*
* #author seref
*/
public abstract class AbstractFacade<T> {
private Class<T> entityClass;
public AbstractFacade(Class<T> entityClass) {
this.entityClass = entityClass;
}
public List<T> araStr(String sorgu, String pr1, String pr2, String pr3, String pr4, String pr5) {
Query query = getEntityManager().createQuery(sorgu);
if (pr1 != null & !"".equals(pr1)) {
query.setParameter("pr1", pr1);
}
if (pr2 != null & !"".equals(pr2)) {
query.setParameter("pr2", pr2);
}
if (pr3 != null & !"".equals(pr3)) {
query.setParameter("pr3", pr3);
}
if (pr4 != null & !"".equals(pr4)) {
query.setParameter("pr4", pr4);
}
if (pr5 != null & !"".equals(pr5)) {
query.setParameter("pr5", pr5);
}
System.out.print(query.toString());
List<T> list = query.getResultList();
return (List<T>) list;
}
protected abstract EntityManager getEntityManager();
public void create(T entity) {
getEntityManager().persist(entity);
}
public void edit(T entity) {
getEntityManager().merge(entity);
}
public void remove(T entity) {
getEntityManager().remove(getEntityManager().merge(entity));
}
public T find(Object id) {
return getEntityManager().find(entityClass, id);
}
public List<T> findAll() {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
return getEntityManager().createQuery(cq).getResultList();
}
public List<T> findRange(int[] range) {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
cq.select(cq.from(entityClass));
javax.persistence.Query q = getEntityManager().createQuery(cq);
q.setMaxResults(range[1] - range[0] + 1);
q.setFirstResult(range[0]);
return q.getResultList();
}
public int count() {
javax.persistence.criteria.CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
javax.persistence.criteria.Root<T> rt = cq.from(entityClass);
cq.select(getEntityManager().getCriteriaBuilder().count(rt));
javax.persistence.Query q = getEntityManager().createQuery(cq);
return ((Long) q.getSingleResult()).intValue();
}
}
Does someone know where is error?
Change your query from
select u from user u where u.email = :pr1 and u.password = : pr2
to
select u from user u where u.email = :pr1 and u.password = :pr2
i.e. remove the space between : and pr2.
Related
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.
This is my DUsers class:
import org.hibernate.annotations.GenericGenerator;
import javax.persistence.*;
import java.util.Date;
import java.util.Objects;
#Entity
#Table(name = "d_users")
#NamedQueries({
#NamedQuery(name = "bonsai.dropwizard.dao.d.DUsers.findAll",
query = "select e from DUsers e"),
#NamedQuery(name = "bonsai.dropwizard.dao.d.DUsers.findById",
query = "select e from DUsers e "
+ "where e.oAuthId = :id "),
#NamedQuery(name = "bonsai.dropwizard.dao.d.DUsers.findByOAuthId",
query = "select e from DUsers e "
+ "where e.oAuthId = :oAuthId "),
#NamedQuery(name = "bonsai.dropwizard.dao.d.DUsers.findByEmail",
query = "select e from DUsers e "
+ "where e.email = :email "),
#NamedQuery(name="bonsai.dropwizard.dao.d.DUsers.confirm",
query = "update DUsers set status = 'HELLO' where oAuthId = :id")
})
public class DUsers implements IDdbPojo{
#Id
#GeneratedValue(generator="system-uuid")
#GenericGenerator(name="system-uuid", strategy = "uuid")
private String id;
private String oAuthId;
private String oAuthType;
private String firstName;
private String secondName;
private String city;
private String phone;
private String email;
private String profileLink;
private String profilePic;
private String status;
private String notificationToken;
private boolean confirmed;
private String password;
private String notes;
private java.util.Date created_timestamp;
private java.util.Date updated_timestamp;
.. getters and setters on-going
As you can see, I have defined a few #NamedQueries and they all work properly except the last one that needs to update my database. In order to run this query, I defined two functions:
private void confirmMailDAO(String id) {
namedQuery("bonsai.dropwizard.dao.d.DUsers.confirm").setParameter("id", id);
}
public void confirmMailInternal(String id) {
Session session = sessionFactory.openSession();
try{
ManagedSessionContext.bind(session);
Transaction transaction = session.beginTransaction();
try{
confirmMailDAO(id);
transaction.commit();
}catch (Exception e) {
transaction.rollback();
throw new RuntimeException(e);
}
} finally {
session.close();
ManagedSessionContext.unbind(sessionFactory);
}
}
After this I defined a path followed by a POST request that should update my database but sadly it doesn't.
#POST
#Path("/confirm/{id}")
public void confirmMail(#NotNull #PathParam("id") String id){
DUsers user = AppConfig.getInstance().getdUsersDAO().findByIdInternal(id);
if (user == null) {
throw new NotAuthorizedException("Error");
}
AppConfig.getInstance().getdUsersDAO().confirmMailInternal(id);
}
Does anyone know where am I getting wrong?
You have set param in named query but forgot to execute it.
Pass session to your method and execute like:
private void confirmMailDAO(Session session, String id) {
Query query = session.getNamedQuery("bonsai.dropwizard.dao.d.DUsers.confirm").setParameter("id", id);
query.executeUpdate();
}
I have the following problem, in my application I would like to have some kind of login. I have following code: (Inspiration here on the web)
public boolean login(String username, String password)
{
try{
EntityTransaction entr=em.getTransaction();
entr.begin();
TypedQuery<Users> query = em.createQuery("SELECT u FROM users u WHERE u.login = :login AND u.password = :pass", Users.class);
query.setParameter(1, username);
query.setParameter(2, password);
try{
Users u = query.getSingleResult();
return true;
}catch(javax.persistence.NoResultException e)
{
return false;
}
}
finally{
em.close();
}
}
When I run it and try to log in, the console will write the following message:
exception in thread "main" java.lang.IllegalArgumentException: An exception occurred while creating a query in EntityManager:
Exception Description: Problem compiling [SELECT u FROM users u WHERE u.login = :login AND u.password = :pass].
[14, 19] The abstract schema type 'users' is unknown.
[28, 35] The state field path 'u.login' cannot be resolved to a valid type.
[49, 59] The state field path 'u.password' cannot be resolved to a valid type.
This is my table:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.dke.ps.Tables;
import java.io.Serializable;
import java.util.Collection;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
/**
*
* #author michal
*/
#Entity
#Table(name = "users")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Users.findAll", query = "SELECT u FROM Users u")
, #NamedQuery(name = "Users.findByUserid", query = "SELECT u FROM Users u WHERE u.userid = :userid")
, #NamedQuery(name = "Users.findByLogin", query = "SELECT u FROM Users u WHERE u.login = :login")
, #NamedQuery(name = "Users.findByPassword", query = "SELECT u FROM Users u WHERE u.password = :password")
, #NamedQuery(name = "Users.findByEmail", query = "SELECT u FROM Users u WHERE u.email = :email")
, #NamedQuery(name = "Users.findByDate", query = "SELECT u FROM Users u WHERE u.date = :date")})
public class Users implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#Column(name = "userid")
private Integer userid;
#Column(name = "login")
private String login;
#Column(name = "password")
private String password;
#Column(name = "email")
private String email;
#Column(name = "date")
#Temporal(TemporalType.DATE)
private Date date;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "userid")
private Collection<Saves> savesCollection;
#JoinColumn(name = "saveid", referencedColumnName = "saveid")
#ManyToOne
private Saves saveid;
public Users() {
}
public Users(Integer userid) {
this.userid = userid;
}
public Integer getUserid() {
return userid;
}
public void setUserid(Integer userid) {
this.userid = userid;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
#XmlTransient
public Collection<Saves> getSavesCollection() {
return savesCollection;
}
public void setSavesCollection(Collection<Saves> savesCollection) {
this.savesCollection = savesCollection;
}
public Saves getSaveid() {
return saveid;
}
public void setSaveid(Saves saveid) {
this.saveid = saveid;
}
#Override
public int hashCode() {
int hash = 0;
hash += (userid != null ? userid.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Users)) {
return false;
}
Users other = (Users) object;
if ((this.userid == null && other.userid != null) || (this.userid != null && !this.userid.equals(other.userid))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.dke.ps.Tables.Users[ userid=" + userid + " ]";
}
}
As you can see, the "users" table really exists. I have no idea why it says to me, "The abstract schema type 'users' is unknown.".
Can you help me? I think the other two errors are caused by the first one.
This exception relates to JPQL query compiling, JPQL syntax expect entity names instead table names, try changing your query to the following:
SELECT u FROM **Users** u WHERE u.login = :login AND u.password = :pass
I'm trying to use JPA2 type-safe criteria queries with Hibernate 5.0.7.Final.
...
criteria.where( builder.equal( root.get(SingularAttribute.attr), value ));
//where parameters are
//criteria.where( builder.equal( root.get(Person_.name), "Can" ));
...
The root.get always throw NullPointerException.
The metamodel class Person_ for Person is generated by org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor.
A similar problem was asked in JPA/Hibernate Static Metamodel Attributes not Populated -- NullPointerException but this time both classes are in the same package.
Stack trace:
java.lang.NullPointerException
at org.hibernate.jpa.criteria.path.AbstractPathImpl.get(AbstractPathImpl.java:123)
My code:
Interface that i use to make sure they will have getId();.
package it.unibz.db.hibernate.model;
public interface ModelInterface<PK extends Serializable> extends Serializable {
PK getId();
}
Model class
package it.unibz.db.hibernate.model;
#Entity
#Table(name ="person")
public class Person implements ModelInterface<Integer> {
#Id
private Integer id;
private String name;
public Integer getId() {
return id;
}
//other getter and setters
}
Generated metamodel Person_ class
package it.unibz.db.hibernate.model;
#Generated(value = "org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor")
#StaticMetamodel(Person.class)
public abstract class Person_ {
public static volatile SingularAttribute<Person, String> name;
public static volatile SingularAttribute<Person, Integer> id;
}
Generic DAO class that i inherit with PersonDao
public class GenericDao<E extends ModelInterface<PK>, PK extends Serializable> implements DaoInterface<E, PK> {
private Class<E> type;
public GenericDao(Class<E> type) {
this.type = type;
//called as super(ClassName.class); eg. super(Person.class);
}
public List<E> readBy(SingularAttribute column, String value) throws Exception {
EntityManager em = HibernateUtil.getEntityManager();
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<E> criteria = builder.createQuery(type);
Root<E> root = criteria.from(type);
criteria.select(root);
criteria.where( builder.equal( root.get(column), value ));
List<E> entityList = em.createQuery(criteria).getResultList();
em.close();
return entityList;
}
}
Some of my dependencies
hibernate-c3p0 5.0.7.Final
hibernate-entitymanager 5.0.7.Final
postgresql 9.4.1207.jre7
hibernate-jpamodelgen 5.0.7.Final
EDIT:
Running this code in the main method works
EntityManager em = HibernateUtil.getEntityManager();
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<Person> criteria = builder.createQuery(Person.class);
Root<Person> root = criteria.from(Person.class);
criteria.select(root);
criteria.where( builder.equal( root.get(Person_.name), "Can" ));
List<Person> entityList = em.createQuery(criteria).getResultList();
//do stuff with entityList
but the same code covered in a method throws NullPointerException.
public List<Person> readBy(SingularAttribute column, String value) throws Exception {
log.debug("Reading entity by");
EntityManager em = HibernateUtil.getEntityManager();
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<Person> criteria = builder.createQuery(Person.class);
Root<Person> root = criteria.from(Person.class);
criteria.select(root);
criteria.where( builder.equal( root.get(column), value ));
List<Person> entityList = em.createQuery(criteria).getResultList();
em.close();
return entityList;
}
So it seems that the problem is passing SingularAttribute parameter to the method readBy(SingularAttribute column, String value).
I tested this code in main and this prints false
EntityManager em = HibernateUtil.getEntityManager();
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<Person> criteria = builder.createQuery(Person.class);
Root<Person> root = criteria.from(Person.class);
System.out.println(root.get(Person_.name) == null); //false
meanwhile this throws InvocationTargetException caused by NullPointerException at root.get(column).
//invoked as personDao.test(Person_.name) from main
public void test(SingularAttribute column) {
EntityManager em = HibernateUtil.getEntityManager();
CriteriaBuilder builder = em.getCriteriaBuilder();
CriteriaQuery<Person> criteria = builder.createQuery(Person.class);
Root<Person> root = criteria.from(Person.class);
System.out.println(root.get(column) == null); //InvocationTargetException
}
Is this what it's supposed to do? How can i pass SingularAttribute object to a method as a parameter?
Calling HibernateUtil.getEntityManager() in main before method call somehow works. It even works when i call literally a empty block of a method init().
It could be related with initialization of classes. Here's the code snippet.
public class HibernateUtil {
private static EntityManagerFactory emFactory;
private static EntityManager em;
private static final Logger log = LoggerFactory.getLogger(HibernateUtil.class);
private static final String PERSISTENCE_UNIT = "pt";
static{
log.info("Creating entity manager factory");
emFactory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT);
}
//calling this from main before PersonDao's method calls somehow works...
public void init(){} //does nothing
public static EntityManager getEntityManager(){
if(em != null && em.isOpen()){
closeEntityManager();
}
log.debug("Creating new entity manager");
em = emFactory.createEntityManager();
return em;
}
public static void close() throws Exception {
if(em != null && em.isOpen()){
closeEntityManager();
}
log.info("Closing entity manager factory");
emFactory.close();
}
private static void closeEntityManager(){
log.info("Closing last entity manager");
em.close();
}
}
I am facing a NullPointerException.
I'm trying to perform a JUnit test and receive NullPointerException somehow.
The Test I wrote is the following;
package edu.city.set.eia.citypress.unittest.beans;
import edu.city.set.eia.citypress.model.RegisUser;
import edu.city.set.eia.citypress.beans.RegisUserFacade;
import org.junit.Test;
import static org.junit.Assert.*;
public class RegisUserUTest {
private static final String EMAIL = "test_email";
private static final String INVALID_EMAIL = "test_email_invalid";
#Test
public void testValidEmail() throws Exception {
TestEmail bean = new TestEmail();
RegisUser user = bean.findByEmail(EMAIL);
assertNotNull(user);
assertEquals(EMAIL, user.getEmail());
}
#Test(expected = Exception.class)
public void testInValidUser() throws Exception {
TestEmail bean = new TestEmail();
bean.findByEmail(INVALID_EMAIL);
}
private static class TestEmail extends RegisUserFacade {
private RegisUser user;
public TestEmail() {
user = new RegisUser();
user.setEmail(EMAIL);
}
#Override
public RegisUser findUser(String email) {
if (email.equals(user.getEmail())) {
return user;
}
return null;
}
}
}
On the other hand,
the session bean is as follows;
package edu.city.set.eia.citypress.beans;
import edu.city.set.eia.citypress.model.RegisUser;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
#Stateless
public class RegisUserFacade extends AbstractFacade<RegisUser> implements RegisUserFacadeLocal {
#PersistenceContext(unitName = "citypress_PU")
private EntityManager em;
#Override
public EntityManager getEntityManager() {
return em;
}
public void setEntityManager(EntityManager em) {
this.em = em;
}
public RegisUserFacade() {
super(RegisUser.class);
}
#Override
public RegisUser findByUsername(String username) {
Query query = this.getEntityManager().createQuery("select r from RegisUser r where username=:username");
query.setParameter("username", username);
RegisUser regisuser;
try {
regisuser = (RegisUser) query.getSingleResult();
}
catch (Exception e){
regisuser = null;
}
return regisuser;
}
#Override
public RegisUser findByUserPass(String username, String password){
Query query = this.getEntityManager().createNamedQuery("RegisUser.findByUserPass");
query.setParameter("username", username);
query.setParameter("password", password);
RegisUser regisuser;
try { // To prevent javax.persistence.NoResultException
regisuser = (RegisUser) query.getSingleResult();
}
catch (Exception e){
regisuser = null;
}
return regisuser;
}
#Override
public RegisUser findByEmail(String email) {
Query query = em.createQuery("select r from RegisUser r where r.email = :email");
query.setParameter("email", email);
RegisUser regisuser;
try {
regisuser = (RegisUser) query.getSingleResult();
}
catch (Exception e){
regisuser = null;
}
return regisuser;
}
}
When I run the test, it says NullPointerException.
java.lang.NullPointerException
at edu.city.set.eia.citypress.beans.RegisUserFacade.findByEmail(RegisUserFacade.java:63)
at edu.city.set.eia.citypress.unittest.beans.RegisUserUTest.testValidEmail(RegisUserUTest.java:16)
Seems like em is null in
Query query = em.createQuery("select r from RegisUser r where r.email = :email");
if this line is 63 (the line Number can be seen in the Stacktrace: RegisUserFacade.java:63)
It seems to be failing at the below code. The EntityManager is null and I doesn't see it being set on it by the Junit. I'd suggest you use Ejb3Unit if you want to test it out of the container or use an embedded glassfish.
Query query = this.getEntityManager().createQuery("select r from RegisUser r where username=:username");