JUnit test; nullpointer exception - java

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");

Related

NullPointerException when Testing Service and DAO class JUnit

I am testing a DAO class using JUnit and I am getting a nullpointerexception which I am not sure why as I am initiating the service class. The following is the test class:
public class RegisterTest {
private UserDaoImpl userservice = new UserDaoImpl();
#Mock
JdbcTemplate jdbcTemplate;
User user;
#Before
public void setUp() {
user = new User();
}
#Test
public void testSetAddress() {
user.setAddress("A");
assertEquals(user.getAddress(), "A");
}
#Test
public void testSetEmail() {
user.setEmail("B");
assertEquals(user.getEmail(), "B");
}
#Test
public void testSetFirstname() {
user.setFirstname("C");
assertEquals(user.getFirstname(), "C");
}
#Test
public void testSetLastname() {
user.setLastname("D");
assertEquals(user.getLastname(), "D");
}
#Test
public void testSetPassword() {
user.setPassword("E");
assertEquals(user.getPassword(), "E");
}
#Test
public void testSetUsername() {
user.setUsername("F");
assertEquals(user.getUsername(), "F");
}
#Test
public void testRegister() {
userservice.register(user);
String username = user.getUsername();
assertEquals(userservice.findByUsername(username), 1);
}
}
The following is the UserDaoImpl
public class UserDaoImpl implements UserDao {
#Autowired
PasswordEncoder passwordEncoder;
#Autowired
DataSource datasource;
#Autowired
JdbcTemplate jdbcTemplate;
public List<User> findByUsername(String username) {
String sql = "select * from users where username='" + username +
"'";
List<User> users = jdbcTemplate.query(sql, new UserMapper());
return users;
}
public int register(User user) {
// If username is unique
String uniqueusername = "select * from users where username='" +
user.getUsername() + "'";
List<User> users = jdbcTemplate.query(uniqueusername, new
UserMapper());
if(users.size() == 0) {
// encode password
String encryptedPassword =
passwordEncoder.encode(user.getPassword());
// Updating database with new user
String sql = "insert into users values(?,?,?,?,?,?)";
return jdbcTemplate.update(sql, new Object[] {
user.getUsername(),
encryptedPassword,
user.getFirstname(),
user.getLastname(),
user.getEmail(),
user.getAddress() });
}
else {
return 0;
}
}
How can I inject the class in the test class? I guess the reason why the nullpointerxeception is because the dao class is not being injected properly in the test class
You should run your test with adequate runner
RunWith(MockitoJunitRunner.class)
public class RegisterTest {
Then you need to inject your mock inside the DAO
#InjectMocks
private UserDaoImpl userservice = new UserDaoImpl();

Hibernate Test - Exception in thread "main" java.lang.NullPointerException

I've got this error.. Could someone help me ?
run: Exception in thread "main" java.lang.NullPointerException at
cidade.CidadeJpaController.getEntityManager(CidadeJpaController.java:24)
at cidade.CidadeJpaController.create(CidadeJpaController.java:30) at
Main.Main.main(Main.java:10) Java Result: 1
Cidade
package cidade;
import java.io.Serializable;
import javax.persistence.*;
#Entity
public class Cidade implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE)
private long id;
private String nome;
private String uf;
public Cidade() {
}
public Cidade(String n, String u){
this.nome = n;
this.uf = u;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getUf() {
return uf;
}
public void setUf(String uf) {
this.uf = uf;
}
}
Persistence.xml
<?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="easyjavajpa" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>cidade.Cidade</class>
<validation-mode>NONE</validation-mode>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:postgresql://localhost:5432/thibernate"/>
<property name="javax.persistence.jdbc.password" value="1234"/>
<property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver"/>
<property name="javax.persistence.jdbc.user" value="postgres"/>
<property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider"/>
<property name="javax.persistence.schema-generation.database.action" value="create"/>
</properties>
</persistence-unit>
</persistence>
CidadeJpaController
package cidade;
import cidade.exceptions.NonexistentEntityException;
import java.io.Serializable;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
public class CidadeJpaController implements Serializable {
public CidadeJpaController(EntityManagerFactory emf) {
this.emf = emf;
}
private EntityManagerFactory emf = null;
public CidadeJpaController() {
}
public EntityManager getEntityManager() {
return emf.createEntityManager();
}
public void create(Cidade cidade) {
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
em.persist(cidade);
em.getTransaction().commit();
} finally {
if (em != null) {
em.close();
}
}
}
public void edit(Cidade cidade) throws NonexistentEntityException, Exception {
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
cidade = em.merge(cidade);
em.getTransaction().commit();
} catch (Exception ex) {
String msg = ex.getLocalizedMessage();
if (msg == null || msg.length() == 0) {
long id = cidade.getId();
if (findCidade(id) == null) {
throw new NonexistentEntityException("The cidade with id " + id + " no longer exists.");
}
}
throw ex;
} finally {
if (em != null) {
em.close();
}
}
}
public void destroy(long id) throws NonexistentEntityException {
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
Cidade cidade;
try {
cidade = em.getReference(Cidade.class, id);
cidade.getId();
} catch (EntityNotFoundException enfe) {
throw new NonexistentEntityException("The cidade with id " + id + " no longer exists.", enfe);
}
em.remove(cidade);
em.getTransaction().commit();
} finally {
if (em != null) {
em.close();
}
}
}
public List<Cidade> findCidadeEntities() {
return findCidadeEntities(true, -1, -1);
}
public List<Cidade> findCidadeEntities(int maxResults, int firstResult) {
return findCidadeEntities(false, maxResults, firstResult);
}
private List<Cidade> findCidadeEntities(boolean all, int maxResults, int firstResult) {
EntityManager em = getEntityManager();
try {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
cq.select(cq.from(Cidade.class));
Query q = em.createQuery(cq);
if (!all) {
q.setMaxResults(maxResults);
q.setFirstResult(firstResult);
}
return q.getResultList();
} finally {
em.close();
}
}
public Cidade findCidade(long id) {
EntityManager em = getEntityManager();
try {
return em.find(Cidade.class, id);
} finally {
em.close();
}
}
public int getCidadeCount() {
EntityManager em = getEntityManager();
try {
CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
Root<Cidade> rt = cq.from(Cidade.class);
cq.select(em.getCriteriaBuilder().count(rt));
Query q = em.createQuery(cq);
return ((Long) q.getSingleResult()).intValue();
} finally {
em.close();
}
}
}
Main
package Main;
import java.util.*;
import cidade.*;
public class Main {
public static void main(String[] args) {
CidadeJpaController em = new CidadeJpaController();
Cidade cidade = new Cidade("Santarém", "PA");
em.create(cidade);
List cidades = em.findCidadeEntities();
System.out.println( cidades.size() + " cidade(s) encontradas" );
for (Object c : cidades) {
Cidade cid = (Cidade) c;
System.out.println(cid.getNome());
}
}
}
It seems that you are not setting the entityManagerFactory while instantiating your controller. Hence it is throwing a null pointer exception. As per your code
em = getEntityManager();
the getEntityManagerMethod():
public EntityManager getEntityManager() {
return emf.createEntityManager();
}
Here emf is already null. As you used default constructor to initialize your code and I do not see any injection what so ever.
Regards
Himanshu
You have this constructor in CidadeJpaController which takes EntityManagerFactory object.
public CidadeJpaController(EntityManagerFactory emf) {
this.emf = emf;
}
private EntityManagerFactory emf = null;
While instantiating you're not providing EntityManagerFactory object resulting in null pointer error when trying to access. SO create an EntityManagerFactory object ans send it CidadeJpaController.Below is a sample solution change it in your Main class
public static void main(String[] args) {
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("easyjavajpa");
CidadeJpaController em = new CidadeJpaController(entityManagerFactory);
Cidade cidade = new Cidade("Santarém", "PA");
em.create(cidade);
List cidades = em.findCidadeEntities();

When I select a row in MySQL using hibernate classes, it makes an update automatically

I'm trying to develop a blacklist for my users including several variables. So when a user sign up in my application, I check if some parameters are blacklisted or not.
The problem is that when I perform a select and the database find something that fits with my search, it automatically perform an update an clean that row.
This is the MySQL log:
86 Query select * from blacklist where mobile_token = 'b'
86 Query SHOW WARNINGS
86 Query select ##session.tx_read_only
86 Query update mydatabase.blacklist set email=null, iban=null, mobile_token=null, nif=null where blacklist_id=1
86 Query SHOW WARNINGS
86 Query commit
86 Query SET autocommit=1
86 Query SET autocommit=1
86 Query set session transaction read write
This is my table:
My model:
package models.classes_hibernate;
import javax.persistence.*;
import static javax.persistence.GenerationType.IDENTITY;
#Entity
#Table(name="blacklist"
,catalog="mydatabase"
)
public class Blacklist implements java.io.Serializable {
private Integer blacklistId;
private String mobileToken;
private String iban;
private String nif;
private String email;
public Blacklist() {
}
#Id #GeneratedValue(strategy=IDENTITY)
#Column(name="blacklist_id", unique=true, nullable=false)
public Integer getBlacklistId() {
return this.blacklistId;
}
public void setBlacklistId(Integer blacklistId) {
this.blacklistId = blacklistId;
}
#Column(name="mobile_token", nullable = false)
public String getMobileToken() {
return this.mobileToken;
}
public void setMobileToken(String name) {
this.mobileToken = mobileToken;
}
#Column(name="iban", nullable = false)
public String getIban() {
return this.iban;
}
public void setIban(String name) {
this.iban = iban;
}
#Column(name="nif", nullable = false)
public String getNif() {
return this.nif;
}
public void setNif(String name) {
this.nif = nif;
}
#Column(name="email", nullable = false)
public String getEmail() {
return this.email;
}
public void setEmail(String name) {
this.email = email;
}
}
And my DAO:
package models.dao;
import com.google.common.collect.Lists;
import models.classes_hibernate.Blacklist;
import models.pages.Page;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;
import org.hibernate.type.StringType;
import play.Logger;
import play.db.jpa.JPA;
import play.db.jpa.Transactional;
import javax.persistence.NoResultException;
import javax.persistence.Query;
import java.util.List;
public class BlacklistDAOImpl implements MyAppCRUDDAOInterface<Blacklist> {
#Override
public void create(Blacklist entity) {
JPA.em().persist(entity);
}
#Override
public Blacklist read(Integer id) {
return JPA.em().find(Blacklist.class, id);
}
public Page<Blacklist> readAll(String orientation,int pageSize, int beginElementId)
{
Query query = null;
List<Blacklist> blacklists = null;
boolean areThereMore = false;
Page<Blacklist> allBlacklists = null;
int size = 0;
if(orientation.equals("all")) {
query = JPA.em().createNativeQuery("select * from blacklist",Blacklist.class);
}
if(orientation.equals("lt")) {
query = JPA.em().createNativeQuery("select * from blacklist where blacklist_id < ? ORDER BY blacklist_id DESC",Blacklist.class);
query.setParameter(1, beginElementId);
size =query.getResultList().size();
query.setMaxResults(pageSize);
}
if(orientation.equals("gt")) {
query = JPA.em().createNativeQuery("select * from blacklist blacklist_id > ? ORDER BY blacklist_id ASC",Blacklist.class);
query.setParameter(1, beginElementId);
size =query.getResultList().size();
query.setMaxResults(pageSize);
}
if (size>pageSize)
areThereMore = true;
try {
blacklists = query.getResultList();
if (orientation.equals("gt")) {
List<Blacklist> reverseList = Lists.reverse(blacklists);
blacklists = reverseList;
}
allBlacklists = new Page<Blacklist>(blacklists, areThereMore, "Blacklist");
return allBlacklists;
}
catch(NoResultException nre){
allBlacklists=null;
return allBlacklists;
}
}
#Override
public void update(Blacklist entity) {
JPA.em().merge(entity);
}
#Override
public void delete(Blacklist entity) {
JPA.em().remove(entity);
}
#Override
public boolean isManaged(Blacklist entity) {
return JPA.em().contains(entity);
}
#Override
public void close() {
JPA.em().close();
}
public Boolean isMobileTokenBlacklisted(String mobileToken) {
Query query = JPA.em().createNativeQuery("select * from blacklist where mobile_token = ?",Blacklist.class);
query.setParameter(1, mobileToken);
Blacklist blacklist;
try {
Logger.debug("Voy a comprobar");
blacklist = (Blacklist)query.getSingleResult();
} catch (NoResultException nre){
blacklist=null;
}
return blacklist != null;
}
isMobileTokenBlacklisted call:
#POST
#Path("/api/user")
#ApiOperation(position = 3, nickname ="user", value = "Sign up new user",notes = "Minimum JSON required: ",
response = AppUserJSON.class, httpMethod = "POST")
#BodyParser.Of(BodyParser.Json.class)
#Transactional
public static Result signup() {
AppUserDAOImpl appUserDAO = new AppUserDAOImpl();
AppUserJSON user = null;
AppUser appUser = null;
BlacklistDAOImpl blacklistDAO = new BlacklistDAOImpl();
try {
user = parse();
String encrypt_nif = user.nif;
String encrypt_authorization = user.parental_authorization;
String encrypt_password = user.password;
try {
encrypt_password= EncryptUtils.encrypt(config1.getString("key"),user.password);
if(user.nif!= null)
encrypt_nif = EncryptUtils.encrypt(config1.getString("key"),user.nif);
if(user.parental_authorization!= null)
encrypt_authorization = EncryptUtils.encrypt(config1.getString("key"),user.parental_authorization);
} catch (Exception e) {
e.printStackTrace();
}
appUser = new AppUser(new Date(), new Date(),user.email.toLowerCase(), encrypt_password, user.mobile_token,
user.mobile_device, 0, 0, 0, 0, encrypt_nif,
false,"NOT_LOCKED", encrypt_authorization, 0, false);
if (user.email == null) {
return status (200, "email missing");
} else if (blacklistDAO.isEmailBlacklisted(user.email)){
return status(401, "Email is blacklisted");
}
if (user.password == null)
return status(201, "password missing");
if (user.mobile_token == null) {
return status (206, "mobileToken missing");
} else if (blacklistDAO.isMobileTokenBlacklisted(user.mobile_token)){
Logger.debug("MobileToken blacklisted");
return status(401, "Mobile token is blacklisted");
}
if (user.mobile_device== null)
return status(207, "mobileDevice missing");
else{
appUserDAO.create(appUser);
user.app_user_id= appUser.getAppUserId();
return ok(Json.toJson(user));
}
} catch (IncompleteJSONException e) {
return badRequest("IncompleteJSONException");
} catch (DuplicateJSONException e) {
return badRequest("DuplicateJSONException");
}
}
Thanks!
I don't know where it comes from but we can find a way to correct some thing to improve your code and exclude definitely some queries.
Be sure to use bracket around your if. It's not compulsory but is a way to make the code clearer
In the signup method, the else is not logical. It only depends on the last if (mobiledevice test). You probably want to create your user if all test are wrong.
Here you just want to test if you have any blacklisted element corresponding to your research. You can use COUNT function or even EXISTS which can be more efficient maybe.
You can use Debug mode to see where your update is done too.

Exception Description: Syntax error parsing

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.

Why is my JPQL not working?

This JPQL used to work but then it broke for no reason. I now get this strange exception:
java.lang.IllegalArgumentException: Parameter "Parameter<LandKod>('landKod')" declared in "SELECT r FROM Region r WHERE r.landKod = :landKod" is set to value of "US" of type "java.lang.String", but this parameter is bound to a field of type "se.prv.pandora.arendeprocess.entity.LandKod".
which seems to indicate that there is some kind of name conflict of what is named landKod in my code. Here is the source:
import java.io.Serializable;
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.Table;
#Entity(name = "Region")
#Table(name="TP197_REGION")
#NamedQueries({
#NamedQuery(name = "getAllValidRegions", query = "SELECT r FROM Region r WHERE r.histKod = 'A'"),
#NamedQuery(name = "getRegionsByLandkod", query = "SELECT r FROM Region r WHERE r.landKod = :landKod")
})
public class Region implements Serializable {
#Id
private int regionId;
#ManyToOne
#JoinColumn(name="landKod", referencedColumnName="landKod")
private LandKod landKod ;
private String histKod ;
private String regionForkort;
private String regionRubrik;
private String regionBeskr;
public Region() {
super();
}
public int getRegionId() {
return regionId;
}
public void setRegionId(int regionId) {
this.regionId = regionId;
}
public String getRegionForkort() {
return regionForkort;
}
public void setRegionForkort(String regionForkort) {
this.regionForkort = regionForkort;
}
public String getRegionRubrik() {
return regionRubrik;
}
public void setRegionRubrik(String regionRubrik) {
this.regionRubrik = regionRubrik;
}
public String getRegionBeskr() {
return regionBeskr;
}
public void setRegionBeskr(String regionBeskr) {
this.regionBeskr = regionBeskr;
}
public String getHistKod() {
return histKod;
}
public void setHistKod(String histKod) {
this.histKod = histKod;
}
public String getRegionFormatted() {
if(regionForkort!=null && regionForkort.length()>0) {
return regionForkort + " " + regionRubrik;
} else {
return regionRubrik;
}
}
public LandKod getLandKod() {
return landKod;
}
public void setLandKod(LandKod landKod) {
this.landKod = landKod;
}
}
Here's the method implementation where it allows a string as a parameter:
#Override
public List<Region> getRegionsByLandkod(String landKod) {
List<Region> regionsList = null;
try {
Query query = em.createNamedQuery("getRegionsByLandkod");
query.setParameter("landKod", landKod);
regionsList = (List<Region>) query.getResultList();
} catch(Exception e){
logger.info("Kunde inte hitta någon region med landkod: "+landKod, e);
}
return regionsList;
}
Could you help me fix this error?
The problem is this line:
public List<Region> getRegionsByLandkod(String landKod) {
It should either be this:
public List<Region> getRegionsByLandkod(LandKod landKod) {
or you should be converting the String to a LandKod and using that as the query parameter.
(Or you could change the Region class to make the landKod attribute's type String.)
It seems you're calling getRegionsByLandkod with a String instead of a LandKod object.
Verify where you use this query if the parameter is correct.

Categories

Resources