Tried to remove the Entit yManager, but none was set - java

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

Related

Migrating to hibernate 5.1.16 from hibernate 4.3 have QuerySyntaxException

I'm trying to migrate my hibernate 4.3 to hibernate 5.1.16 and I am ending up with QuerySyntaxException which am not able to figure after one week.
I am using annotation for mapping and I checked my queries all of those uses the same name of my entity class, there is no conflict in the name in my queries which am sure and also the point is it worked with Hibernate 4.3.
All the solution in the web is only pointing to naming conflicts.__Maintence is my first table and the mapping issue is pointing at this table.
Here is my hibernate.cfg which I use for mapping.
<mapping class="wadetech.DB.entity.__Maintenance"/>
This is my __Maintenance class
#Entity
#Table(name = "__maintenance", uniqueConstraints = #UniqueConstraint(columnNames = "name"))
public class __Maintenance implements java.io.Serializable {
This is my __MaintenanceDAO
public Collection<__Maintenance> getMaintenanceByName(String name){
String query = "";
query += "select m from __Maintenance m";
query += " where m.name = :name ";
query += " order by ";
query += " m.startDate desc, m.idMaintenance desc";
return super.list(query, "name", name);
}
And here is my exception
wadetech.exceptions.InfrastructureException: org.hibernate.hql.internal.ast.QuerySyntaxException: __Maintenance is not mapped [select m from __Maintenance m where m.name = :name order by m.startDate desc, m.idMaintenance desc]
at wadetech.DB.base.BaseDAO.anonymousFindByQuery(BaseDAO.java:267)
at wadetech.DB.base.BaseDAO.findByQuery(BaseDAO.java:255)
at wadetech.DB.base.BaseDAO.list(BaseDAO.java:243)
at wadetech.DB.DAOS.__MaintenanceDAO.getMaintenanceByName(__MaintenanceDAO.java:78)
at com.at.project.utils.runtime.RuntimeModifier.HasExecuted(RuntimeModifier.java:128)
at wadetech.listeners.ModificationScriptStartupListener.contextInitialized(ModificationScriptStartupListener.java:47)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:5016)
at org.apache.catalina.core.StandardContext.startInternal(StandardContext.java:5528)
at org.apache.catalina.util.LifecycleBase.start(LifecycleBase.java:150)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1575)
at org.apache.catalina.core.ContainerBase$StartChild.call(ContainerBase.java:1565)
at java.util.concurrent.FutureTask.run(FutureTask.java:262)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: __Maintenance is not mapped [select m from __Maintenance m where m.name = :name order by m.startDate desc, m.idMaintenance desc]
at org.hibernate.hql.internal.ast.QuerySyntaxException.generateQueryException(QuerySyntaxException.java:79)
at org.hibernate.QueryException.wrapWithQueryString(QueryException.java:103)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:217)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:141)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:115)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:76)
Am also adding a section of my HibernateUtil as I have my doubts this is causing due to some transaction issues which I changed after moving to 5.1
Before I used tx.wasCommitted();
which I can't use anymore as was Committed is omitted in hibernate 5.1 so I changed it to the below code tx.getStatus() == TransactionStatus.COMMITTED
Here is my hibernateUtil
public static void beginTransaction(boolean readOnly) throws InfrastructureException {
try {
if( currentConnectionMode == ConnectionMode.MASTER_SLAVE && readOnly ) {
// it is a readOnly tx
Transaction tx = readOnlyThreadTransaction.get();
if (null == tx || tx.getStatus() == TransactionStatus.COMMITTED || tx.getStatus() == TransactionStatus.ROLLED_BACK) {
tx = getReadOnlySession().beginTransaction();
readOnlyThreadTransaction.set(tx);
}
} else {
Transaction tx = threadTransaction.get();
if (null == tx || tx.getStatus() == TransactionStatus.COMMITTED || tx.getStatus() == TransactionStatus.ROLLED_BACK) {
tx = getSession().beginTransaction();
threadTransaction.set(tx);
}
} // end if
} // end try
catch (HibernateException ex) {
WLog.DAOLogger.error("Begin transaction", ex);
throw new InfrastructureException(ex);
} // end catch
}
I want to stick on with hibernate 5.1 and don't want to migrate to hibernate 5.2 as 5.2 uses jdk 8+. I prefer hibernate 5.1 because I strictly need to use jdk 1.7
So finally I solve the above issue was.Even though the exception din't help to point the issue. The real problem was at hibernateUtils.
Before this was how my hiberenate utils for hibernate 4.3.
serviceRegistry = new StandardServiceRegistryBuilder().applySettings(
configuration.getProperties()).build();
sessionFactory = configuration.configure().buildSessionFactory(serviceRegistry);
and I changed it to
registry = new StandardServiceRegistryBuilder().configure().build();
MetadataSources sources = new MetadataSources(registry);
Metadata metadata = sources.getMetadataBuilder().build();
sessionFactory = metadata.getSessionFactoryBuilder().build();

java.lang.ClassCastException cause by JPQL session bean

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)

Play Framework 2.3.4 Java Ebean Execution exception[[IllegalStateException: Transaction is Inactive]]

I use Play Framework 2.3.4, Java8, Ebean.
Ebean transaction code is not working.
Please your help.
Java Code
Ebean.execute(new TxRunnable() {
public void run() {
User user = new User();
user.id = 1;
user.save();
}
});
server error log is
play.api.Application$$anon$1: Execution exception[[IllegalStateException: Transaction is Inactive]]
at play.api.Application$class.handleError(Application.scala:296) ~[com.typesafe.play.play_2.11-2.3.4.jar:2.3.4]
at play.api.DefaultApplication.handleError(Application.scala:402) [com.typesafe.play.play_2.11-2.3.4.jar:2.3.4]
at play.core.server.netty.PlayDefaultUpstreamHandler$$anonfun$3$$anonfun$applyOrElse$4.apply(PlayDefaultUpstreamHandler.scala:320) [com.typesafe.play.play_2.11-2.3.4.jar:2.3.4]
at play.core.server.netty.PlayDefaultUpstreamHandler$$anonfun$3$$anonfun$applyOrElse$4.apply(PlayDefaultUpstreamHandler.scala:320) [com.typesafe.play.play_2.11-2.3.4.jar:2.3.4]
at scala.Option.map(Option.scala:145) [org.scala-lang.scala-library-2.11.1.jar:na]
Caused by: java.lang.IllegalStateException: Transaction is Inactive
at com.avaje.ebeaninternal.server.transaction.JdbcTransaction.commit(JdbcTransaction.java:583) ~[org.avaje.ebeanorm.avaje-ebeanorm-3.3.4.jar:na]
at com.avaje.ebeaninternal.api.ScopeTrans.onFinally(ScopeTrans.java:101) ~[org.avaje.ebeanorm.avaje-ebeanorm-3.3.4.jar:na]
at com.avaje.ebeaninternal.server.core.DefaultServer.execute(DefaultServer.java:724) ~[org.avaje.ebeanorm.avaje-ebeanorm-3.3.4.jar:na]
at com.avaje.ebeaninternal.server.core.DefaultServer.execute(DefaultServer.java:709) ~[org.avaje.ebeanorm.avaje-ebeanorm-3.3.4.jar:na]
at com.avaje.ebean.Ebean.execute(Ebean.java:1264) ~[org.avaje.ebeanorm.avaje-ebeanorm-3.3.4.jar:na]
Thanks.
provide transaction scope
TxScope txScope = TxScope.requiresNew();
Ebean.execute(txScope, new TxRunnable() {
public void run() {
User user = new User();
user.id = 1;
user.save();
}
});

ExceptionHandling in Spring

I am using spring with hibernate and when I am trying to insert a data which already exists, it throws DataIntegrityViolationException.
So to handle this exception I have placed a try/catch block in my save method in DAO layer, but it's not getting caught.
After that I placed a try/catch block in save method of service layer also but there also its not getting caught.
I have a testMain method in my service layer and when I am handling there its getting caught there.
Please help how to handle this in my DAO layer
public class TestMain {
/**
* #param args
*/
public static void main(String[] args) {
ApplicationContext applicationContext = SpringUtil
.getApplicationContextInstance();
UserDaoService userDaoService = applicationContext.getBean("userDaoService",
UserDaoService.class);
UserDaoImpl userDao = applicationContext.getBean("userDaoImpl",
UserDaoImpl.class);
User user = new User();
user.setActive(true);
user.setEmail("shariquealam01#gmail.com");
user.setFirstName("Md");
user.setMiddleName("Sharique");
user.setLastName("Alam");
user.setId(1);
user.setPassword("123");
user.setUserName("shariquealam01");
userDaoService.saveUser(user);
}
}
#Service
public class UserDaoService {
#Autowired
public UserDao userDao;
#Transactional
public void saveUser(User user){
System.out.println("User Saving");
/*user.setActive(true);
user.setEmail("shariquealam06#gmail.com");
user.setFirstName("Md");
user.setMiddleName("Sharique");
user.setLastName("Alam");
user.setId(6);
user.setPassword("123");
user.setUserName("shariquealam06");*/
userDao.saveUser(user) ;
/*try{
System.out.println("Inside Service Try");
userDao.saveUser(user);
} catch (Exception e){
System.out.println("Exception Occured "+e);
}*/
// deleteUser(3);
}
}
#Repository
public class UserDaoImpl implements UserDao {
#Autowired
private SessionFactory sessionFactory;
public Role getRole(int id){
Session session = getSessionFactory().getCurrentSession();
Role role = (Role) session.get(Role.class, id);
return role;
}
#Override
public void saveUser(User user) {
// Session session = getSessionFactory().getCurrentSession();
/*role.setRoleId(102);
role.setRoleName("User");*/
// role.getUsers().add(user);
/*session.save(user);*/
//logger.info( "Executing Query to ADD User"); //Since this query is important for the state of application, have info logging
Role role = getRole(102);
user.getRoles().add(role);
Session session = sessionFactory.getCurrentSession();
session.save( user );
//userId = user.getId();
//logger.info( "User ADDED to DB with userId as {}", user.getId() );
//session.save(role);
}
}
Exception in thread "main" org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
at org.springframework.orm.hibernate4.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:163)
at org.springframework.orm.hibernate4.HibernateTransactionManager.convertHibernateAccessException(HibernateTransactionManager.java:730)
at org.springframework.orm.hibernate4.HibernateTransactionManager.doCommit(HibernateTransactionManager.java:592)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:757)
at org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:726)
at org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:515)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:291)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:653)
at com.sharique.service.UserDaoService$$EnhancerBySpringCGLIB$$956522ab.saveUser(<generated>)
at com.sharique.main.TestMain.main(TestMain.java:40)
Caused by: org.hibernate.exception.ConstraintViolationException: could not execute statement
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:129)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:211)
at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:62)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3124)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3581)
at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:104)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:465)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:351)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:350)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:56)
at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1222)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:425)
at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.beforeTransactionCommit(JdbcTransaction.java:101)
at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:177)
at org.springframework.orm.hibernate4.HibernateTransactionManager.doCommit(HibernateTransactionManager.java:584)
... 9 more
Caused by: com.microsoft.sqlserver.jdbc.SQLServerException: Violation of PRIMARY KEY constraint 'PK__USER_DET__F3BEEBFF77DFC722'. Cannot insert duplicate key in object 'dbo.USER_DETAILS'.
at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(SQLServerException.java:216)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(SQLServerStatement.java:1515)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(SQLServerPreparedStatement.java:404)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PrepStmtExecCmd.doExecute(SQLServerPreparedStatement.java:350)
at com.microsoft.sqlserver.jdbc.TDSCommand.execute(IOBuffer.java:5696)
at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeCommand(SQLServerConnection.java:1715)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeCommand(SQLServerStatement.java:180)
at com.microsoft.sqlserver.jdbc.SQLServerStatement.executeStatement(SQLServerStatement.java:155)
at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.executeUpdate(SQLServerPreparedStatement.java:314)
at org.apache.commons.dbcp2.DelegatingPreparedStatement.executeUpdate(DelegatingPreparedStatement.java:98)
at org.apache.commons.dbcp2.DelegatingPreparedStatement.executeUpdate(DelegatingPreparedStatement.java:98)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:208)
... 22 more
The exception, as the stack trace should show, doesn't happen when you call persist() or save(). It happens when flush() is called, i.e. when the SQL insert statements are actually executed. And flush() is called automatically just before the transaction commits.
You could call flush() explicitely and catch the exception, but that would be useless, because Hibernate exceptions are irrecoverable. They leave the session in an unusable state. The only safe thing to do when facing such an exception is to rolback the transaction and close the session.
So do the right thing: use autogenerated primary keys and/or check that the data doesn't exist, using a query, before trying to insert it.

Hibernate requires mapping of classes/tables. Already done

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

Categories