I am trying to create a remote service containing JPQL but I am getting this error for the simplest query.
In my authentication service:
#Override
public Users checkDatabase(String email) {
Query query = entityManager.createQuery("SELECT u from Users u WHERE u.nom = :email", Users.class)
.setParameter("email", email);
Users user = (Users) query.getSingleResult();
return user;
}
and my client code looks like:
String jndiName = "Petroca-ear/Petroca-ejb/AuthenticationServices!com.esprit.services.AuthenticationServicesRemote";
Context context = new InitialContext();
AuthenticationServicesRemote proxy = (AuthenticationServicesRemote) context.lookup(jndiName);
System.out.println(proxy.checkEmail("test#s"));
Users user = (Users) proxy.checkDatabase("peter");
while executing this, I am getting this error:
false
Exception in thread "main" java.lang.ClassCastException: java.lang.Class cannot be cast to java.lang.String
at org.jboss.ejb.client.remoting.ProtocolMessageHandler.readAttachments(ProtocolMessageHandler.java:55)
at org.jboss.ejb.client.remoting.InvocationExceptionResponseHandler$MethodInvocationExceptionResultProducer.getResult(InvocationExceptionResponseHandler.java:82)
at org.jboss.ejb.client.EJBClientInvocationContext.getResult(EJBClientInvocationContext.java:276)
at org.jboss.ejb.client.EJBObjectInterceptor.handleInvocationResult(EJBObjectInterceptor.java:64)
at org.jboss.ejb.client.EJBClientInvocationContext.getResult(EJBClientInvocationContext.java:290)
at org.jboss.ejb.client.EJBHomeInterceptor.handleInvocationResult(EJBHomeInterceptor.java:88)
at org.jboss.ejb.client.EJBClientInvocationContext.getResult(EJBClientInvocationContext.java:290)
at org.jboss.ejb.client.TransactionInterceptor.handleInvocationResult(TransactionInterceptor.java:46)
at org.jboss.ejb.client.EJBClientInvocationContext.getResult(EJBClientInvocationContext.java:290)
at org.jboss.ejb.client.ReceiverInterceptor.handleInvocationResult(ReceiverInterceptor.java:129)
at org.jboss.ejb.client.EJBClientInvocationContext.getResult(EJBClientInvocationContext.java:265)
at org.jboss.ejb.client.EJBClientInvocationContext.awaitResponse(EJBClientInvocationContext.java:453)
at org.jboss.ejb.client.EJBInvocationHandler.doInvoke(EJBInvocationHandler.java:202)
at org.jboss.ejb.client.EJBInvocationHandler.doInvoke(EJBInvocationHandler.java:181)
at org.jboss.ejb.client.EJBInvocationHandler.invoke(EJBInvocationHandler.java:144)
at com.sun.proxy.$Proxy2.checkDatabase(Unknown Source)
at TEST.testPetroca.main(testPetroca.java:23)
Related
Using the following code to get the list of data from table but getting invalid column error.
String sql = "select * from employees WHERE emp_status = :statusCode";
Map parameters = new HashMap();
parameters.put("statusCode", "Active");
MapSqlParameterSource parametersSourceMap = new MapSqlParameterSource(parameters );
List<Employee> employees rowSet = jdbcTemplate.queryForList(sql, parametersSourceMap);
Exception
Exception in thread "main" org.springframework.jdbc.UncategorizedSQLException: PreparedStatementCallback; uncategorized SQLException for SQL [select * from employees WHERE emp_status = :statusCode SQL state [null]; error code [17004]; Invalid column type; nested exception is java.sql.SQLException: Invalid column type
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:83)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:80)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:80)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:603)
at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:812)
at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:868)
at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:876)
at com.spring.EmployeeDAOImpl.addEmployee(EmployeeDAOImpl.java:46)
at com.spring.MainApp.main(MainApp.java:33)
Caused by: java.sql.SQLException: Invalid column type
Table have column as Varchar2
Anyone have idea why we can't get data based on String column?
I recently faced the same issue. In my case, I was using JdbcTemplate instead of NamedParameterJdbcTemplate. I am not sure if the issue is same for you.
You can define a bean of type NamedParameterJdbcTemplate and then autowire it in your repository class.
Configuration class :
#Bean
public NamedParameterJdbcTemplate yourNamedParameterJdbcTemplate(DataSource yourDataSource) {
return new NamedParameterJdbcTemplate(yourDataSource);
}
Repository class :
#Repository
public class YourRepositoryImpl implements YourRepository {
#Autowired
NamedParameterJdbcTemplate jdbcTemplate;
Try to pass parameters like this :
String sql = "SELECT * FROM employees WHERE emp_status = ?";
List<Employee> employees = jdbcTemplate.queryForList(
sql,
new Object[]{"Active"},
new BeanPropertyRowMapper<Employee>(Employee.class)
);
I am getting run time error in Play Framework 2.5 (Java) :
play.api.http.HttpErrorHandlerExceptions$$anon$1: Execution exception[[CompletionException: java.lang.IllegalStateException: Tried to remove the Entit yManager, but none was set.]]
at play.api.http.HttpErrorHandlerExceptions$.throwableToUsefulException(HttpErrorHandler.scala:280)
at play.api.http.DefaultHttpErrorHandler.onServerError(HttpErrorHandler.scala:206)
at play.api.GlobalSettings$class.onError(GlobalSettings.scala:160)
at play.api.DefaultGlobal$.onError(GlobalSettings.scala:188)
at play.api.http.GlobalSettingsHttpErrorHandler.onServerError(HttpErrorHandler.scala:98)
at play.core.server.netty.PlayRequestHandler$$anonfun$2$$anonfun$apply$1.applyOrElse(PlayRequestHandler.scala:100)
at play.core.server.netty.PlayRequestHandler$$anonfun$2$$anonfun$apply$1.applyOrElse(PlayRequestHandler.scala:99)
at scala.concurrent.Future$$anonfun$recoverWith$1.apply(Future.scala:344)
at scala.concurrent.Future$$anonfun$recoverWith$1.apply(Future.scala:343)
at scala.concurrent.impl.CallbackRunnable.run(Promise.scala:32)
Caused by: java.util.concurrent.CompletionException: java.lang.IllegalStateException: Tried to remove the EntityManager, but none was set.
at java.util.concurrent.CompletableFuture.encodeThrowable(CompletableFuture.java:292)
at java.util.concurrent.CompletableFuture.completeThrowable(CompletableFuture.java:308)
at java.util.concurrent.CompletableFuture.uniApply(CompletableFuture.java:593)
at java.util.concurrent.CompletableFuture$UniApply.tryFire(CompletableFuture.java:577)
at java.util.concurrent.CompletableFuture.postComplete(CompletableFuture.java:474)
at java.util.concurrent.CompletableFuture.completeExceptionally(CompletableFuture.java:1977)
at scala.concurrent.java8.FuturesConvertersImpl$CF.apply(FutureConvertersImpl.scala:21)
at scala.concurrent.java8.FuturesConvertersImpl$CF.apply(FutureConvertersImpl.scala:18)
at scala.concurrent.impl.CallbackRunnable.run(Promise.scala:32)
at scala.concurrent.BatchingExecutor$Batch$$anonfun$run$1.processBatch$1(BatchingExecutor.scala:63)
Caused by: java.lang.IllegalStateException: Tried to remove the EntityManager, but none was set.
at play.db.jpa.JPAEntityManagerContext.pop(JPAEntityManagerContext.java:74)
at play.db.jpa.DefaultJPAApi.withTransaction(DefaultJPAApi.java:155)
at play.db.jpa.DefaultJPAApi.withTransaction(DefaultJPAApi.java:195)
at play.db.jpa.TransactionalAction.call(TransactionalAction.java:25)
at play.core.j.JavaAction$$anonfun$7.apply(JavaAction.scala:108)
at play.core.j.JavaAction$$anonfun$7.apply(JavaAction.scala:108)
at scala.concurrent.impl.Future$PromiseCompletingRunnable.liftedTree1$1(Future.scala:24)
at scala.concurrent.impl.Future$PromiseCompletingRunnable.run(Future.scala:24)
at play.core.j.HttpExecutionContext$$anon$2.run(HttpExecutionContext.scala:56)
at play.api.libs.iteratee.Execution$trampoline$.execute(Execution.scala:70)
Below is the code :
#Transactional
public Result logincheck(){
Form<User> loginForm = Form.form(User.class).bindFromRequest();
User user = loginForm.get();
User searchUser = UserDao.findUser(user);
if (searchUser != null){
return ok(homepage.render());
}
return ok(login.render(loginForm));
}
In class UserDao:
public static User findUser(User user){
EntityManager em = jpaApi.em();
TypedQuery<User> query = JPA.em().createQuery("select u.* from [RL].[dbo].[userdetails] u where u.userid = :username and u.password = :password", User.class);
query.setParameter("username", user.userid);
query.setParameter("password", user.password);
try{
return (User) query.getSingleResult();
} catch(NoResultException e){
return null;
}
}
We found this issue while working with play2.5. We fixed it by adding
the persistence.xml file into the project as specified here : Play 2.5 JavaJPA creating a persistence unit
and adding the following in the application.conf:
jpa.default=defaultPersistenceUnit
You are using JPA.em() and jpaApi in the same method. Actually this should be the same entity manager. Starting from play 2.5 the proper way is jpaApi, JPA.em() is deprecated. You should take care to inject jpaApi.
The code may be like this:
public static User findUser(User user) {
JPAApi jpaApi = Play.current().injector().instanceOf(JPAApi.class);
EntityManager em = jpaApi.em();
TypedQuery<User> query = em.createQuery("select u.* from [RL].[dbo].[userdetails] u where u.userid = :username and u.password = :password", User.class);
...
}
You can read more here about dependency injection in Play
I have got a Query. (It's my full DAO method)
#Override
public void addUserRole(UserRole userRole) {
Transaction tx = sessionFactory.getCurrentSession().beginTransaction();
String query = "insert into 'user_roles'('role','username') values(%s,%s)";
Session session = this.sessionFactory.getCurrentSession();
List roleAdd = session.createQuery(String.format(query, "'ROLE_USER'", "'acid'")).list();
tx.commit();
}
And it gives me an exception
type Exception report message Request processing failed; nested exception is org.springframework.orm.hibernate4.HibernateQueryException: expecting IDENT, found ''user_roles'' near line 1, column 13
[insert into 'user_roles'('role','username') values('ROLE_USER','acid')]; nested exception is org.hibernate.hql.internal.ast.QuerySyntaxException: expecting IDENT, found ''user_roles'' near line 1, column 13
[insert into 'user_roles'('role','username') values('ROLE_USER','acid')] description The server encountered an internal error that prevented it from fulfilling this request.
Here's what your method should look like:
#Override
public void addUserRole(UserRole userRole) {
Transaction tx = sessionFactory.getCurrentSession().beginTransaction();
String query = "insert into 'user_roles'('role','username') values(%s,%s)";
Session session = this.sessionFactory.getCurrentSession();
int resultCount = session.createSQLQuery(String.format(query, "'ROLE_USER'", "'acid'")).executeUpdate();
tx.commit();
}
I have a working ORM and been able to map objects to my database. So its up an running.
I've created a web service that looks like this:
#Stateless
#Path("user")
#LocalBean
public class userFacade {
#PersistenceContext(unitName = "Fakebook3")
private EntityManager em;
public userFacade() {
// TODO Auto-generated constructor stub
}
public void persistUser(User user){
em.persist(user);
}
#GET
#Path("edit")
#Produces(MediaType.APPLICATION_JSON)
public Response editUserInformation(
#QueryParam("userid") int userid,
#QueryParam("jobbText") String jobbText,
#QueryParam("intresseText") String intresseText,
#QueryParam("bostadText") String bostadText
){
String jobbTextEscaped = StringEscapeUtils.escapeHtml3(jobbText);
String intresseTextEscaString = StringEscapeUtils.escapeHtml3(intresseText);
String bostadTextEscaped = StringEscapeUtils.escapeHtml3(bostadText);
String sql = "UPDATE user SET job=?, interest=?, bostad=? WHERE id="+userid;
Query query = em.createQuery(sql);
query.setParameter(1, jobbTextEscaped);
query.setParameter(2, intresseTextEscaString);
query.setParameter(3, bostadTextEscaped);
query.executeUpdate();
return Response.status(200).entity("This is a callback message. Handle it!").build();
}
}
I'm using eclipse web service tool and input the paramater values and get this error:
13:23:41,184 ERROR [org.jboss.as.ejb3.invocation] (default task-4) JBAS014134: EJB Invocation failed on component userFacade for method public javax.ws.rs.core.Response se.chas.fakebook.facade.userFacade.editUserInformation(int,java.lang.String,java.lang.String,java.lang.String): javax.ejb.EJBException: java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: fakebook.user is not mapped [UPDATE fakebook.user SET user.job=?, user.interests=?, user.bostad=? WHERE id=1]
at org.jboss.as.ejb3.tx.CMTTxInterceptor.handleExceptionInOurTx(CMTTxInterceptor.java:190) [wildfly-ejb3-8.1.0.Final.jar:8.1.0.Final]
at org.jboss.as.ejb3.tx.CMTTxInterceptor.invokeInOurTx(CMTTxInterceptor.java:275) [wildfly-ejb3-8.1.0.Final.jar:8.1.0.Final]
and so on. I tried to create to map the entities using eclipse and placed them in the same folder as the entities.
But I'm still getting same exception. I also tried changing the sql statement from "... facebook.user ..." to only use "... user ..."
What am I doing wrong?
I can't upload images here so here comes a link with a project tree: http://imgur.com/4yemPZH
Your query should be like this:
String sql = "UPDATE User SET job=?, interest=?, bostad=? WHERE id="+userid;
Try this :
UPDATE user SET job=:job, interest=:interest, bostad=:bostad WHERE id="+userid
query.setParameter("job", jobbTextEscaped);
query.setParameter("interest", intresseTextEscaString);
query.setParameter("bostad ", bostadTextEscaped);
I want to insert data into a table using the following code
public User registerUser(String usr, String pwd) {
u=em.find(User.class,usr);
if(u!=null)
{
return null;
}
String query1 = "insert into users values('" + usr + "','" + pwd +"')";
Query q = em.createQuery(query1);
u=em.find(User.class,usr);
return u;
}
here 'u' is the object of User class and em is EntityManager.
I get this following exception:
Servlet.service() for servlet action threw exception
org.hibernate.hql.ast.QuerySyntaxException: expecting OPEN, found 'values' near line 1, column 19 [insert into users values('pawan','am')]
Try
public User registerUser(String usr, String pwd) {
u=em.find(User.class,usr);
if(u!=null)
{
return null;
}
//Now saving...
em.getTransaction().begin();
em.persist(u); //em.merge(u); for updates
em.getTransaction().commit();
em.close();
return u;
}
If the PK is Identity, it will be set automatically in your persisted class, if you are using auto generation strategy (thanks to David Victor).
Edit to #aman_novice comment:
set it in your class
//Do this BEFORE getTransaction/persist/commit
//Set names are just a example, change it to your class setters
u.setUsr(usr);
u.setPwd(pwd);
//Now you can persist or merge it, as i said in the first example
em.getTransaction().begin();
(...)
About #David Victor, sorry I forgot about that.
You're not using SQL but JPAQL, there is no field-based insert. You persist object rather than inserting rows.
You should do something like this:
public User registerUser(String usr, String pwd) {
u=em.find(User.class,usr);
if(u!=null)
{
return u;
}
u = new User(usr, pwd);
em.persist(u);
return u;
}
This isn't really the way to go. You are trying to insert a row in a table but have no associated attached entity. If you're using the JPA entity manager - then create a new instance - set the properties & persist the entity.
E.g.
User u = new User();
u.setXXX(xx);
em.persist(u);
// em.flush() <<-- Not required, useful for seeing what is happening
// etc..
If you enable SQL loggging in Hibernate & flush the entity then you'll see what is sent to the database.
E.g. in persistence.xml:
<property name="hibernate.format_sql" value="true" />