I'm blocked on this problem for many hours and I don't understand the problem as it works fine with another entity of my project.
I created a Java EE project with Glassfish 4, JPA 2 and EJB 3 in Eclipse IDE.
I'm using a mysql database for storing.
I created a entity bean named Company and a DAO to manage it. I did all it needs to work and it works well.
The problem is that I did exactly the same thing for another entity bean, called Newsletter, but this one doesn't work.
Java throws an EJBException, telling me that the abstract schema is unknown, but it exists in the DB.
The tables company and newsletter are in the same db, so I used the same persistence unit for both of them.
Some questions I found on Google or here are solved by adding the class to the persitence-unit and I did it, but it still throws me an exception.
Here is my NEWSLETTER table:
+--------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+--------------+------+-----+---------+----------------+
| idNewsletter | int(11) | NO | PRI | NULL | auto_increment |
| firstname | varchar(100) | NO | | NULL | |
| lastname | varchar(100) | NO | | NULL | |
| email | varchar(255) | NO | | NULL | |
+--------------+--------------+------+-----+---------+----------------+
My bean Newsletter:
#Entity
public class Newsletter {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long idNewsletter;
#Column(name="firstname")
private String firstname;
#Column(name="lastname")
private String lastname;
#Column(name="email")
private String email;
}
Here is my persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="2lifedb_PU" transaction-type="JTA">
<jta-data-source>jdbc/bonecp_resource</jta-data-source>
<class>com.twolife.beans.User</class>
<class>com.twolife.beans.Company</class>
<class>com.twolife.beans.Office</class>
<class>com.twolife.beans.BankDetails</class>
<class>com.twolife.beans.Logo</class>
<class>com.twolife.beans.Newsletter</class>
<properties>
<property name="eclipselink.logging.level.sql" value="FINE"/>
<property name="eclipselink.logging.parameters" value="true"/>
</properties>
</persistence-unit>
And the DAO class:
#Stateless
public class DAONewsletter {
private static final String SQL_SELECT_NEWSLETTER = "SELECT n FROM NEWSLETTER n WHERE n.email = :email";
#PersistenceContext(unitName="2lifedb_PU")
private EntityManager em;
public void create(Newsletter newsletter) throws DAOException {
try {
em.persist(newsletter);
} catch (Exception e) {
throw new DAOException(e);
}
}
public Newsletter find(String email) throws DAOException {
Newsletter newsletter = new Newsletter();
Query query = em.createQuery(SQL_SELECT_NEWSLETTER);
query.setParameter("email", email);
try {
newsletter = (Newsletter) query.getSingleResult();
} catch (NoResultException e) {
return null;
} catch (Exception e) {
throw new DAOException(e);
}
return newsletter;
}
}
And finally, here is the stacktrace of my exception:
Caused by: java.lang.IllegalArgumentException: An exception occurred while creating a query in EntityManager:
Exception Description: Problem compiling [SELECT n FROM NEWSLETTER n WHERE n.email = :email].
[14, 24] The abstract schema type 'NEWSLETTER' is unknown.
[33, 40] The state field path 'n.email' cannot be resolved to a valid type.
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.createQuery(EntityManagerImpl.java:1585)
at com.sun.enterprise.container.common.impl.EntityManagerWrapper.createQuery(EntityManagerWrapper.java:456)
at com.twolife.dao.DAONewsletter.find(DAONewsletter.java:30)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.glassfish.ejb.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:1081)
at org.glassfish.ejb.security.application.EJBSecurityManager.invoke(EJBSecurityManager.java:1153)
at com.sun.ejb.containers.BaseContainer.invokeBeanMethod(BaseContainer.java:4695)
at com.sun.ejb.EjbInvocation.invokeBeanMethod(EjbInvocation.java:630)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:582)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.doCall(SystemInterceptorProxy.java:163)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.aroundInvoke(SystemInterceptorProxy.java:140)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:883)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:822)
at com.sun.ejb.containers.interceptors.InterceptorManager.intercept(InterceptorManager.java:369)
at com.sun.ejb.containers.BaseContainer.__intercept(BaseContainer.java:4667)
at com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:4655)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:212)
... 36 more
Caused by: Exception [EclipseLink-0] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.JPQLException
Exception Description: Problem compiling [SELECT n FROM NEWSLETTER n WHERE n.email = :email].
[14, 24] The abstract schema type 'NEWSLETTER' is unknown.
[33, 40] The state field path 'n.email' cannot be resolved to a valid type.
at org.eclipse.persistence.internal.jpa.jpql.HermesParser.buildException(HermesParser.java:155)
at org.eclipse.persistence.internal.jpa.jpql.HermesParser.validate(HermesParser.java:347)
at org.eclipse.persistence.internal.jpa.jpql.HermesParser.populateQueryImp(HermesParser.java:278)
at org.eclipse.persistence.internal.jpa.jpql.HermesParser.buildQuery(HermesParser.java:163)
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.buildEJBQLDatabaseQuery(EJBQueryImpl.java:142)
at org.eclipse.persistence.internal.jpa.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)
... 60 more
If anoyone get an idea, that would be really helpful!
And sorry for some english mistakes, it is not my mother language...
em.createQuery() expects a JPQL query, not a SQL query. SQL and JPQL are not the same language. SQL works with tables and columns. JPQL works with entities, fields/properties and associations. NEVER with table and column names. The syntax is similar, but different.
Your entity is named Newsletter, but your query uses NEWSLETTER. Class names are case sensitive.
I had the same issue in wildfly 10.0 with eclipselink 2.6.
I solved adding the following system property to standalone.xml file
<?xml version='1.0' encoding='UTF-8'?>
<server xmlns="urn:jboss:domain:4.2">
<system-properties>
<property name="eclipselink.archive.factory" value="org.jipijapa.eclipselink.JBossArchiveFactoryImpl"/>
</system-properties>
...
</server>
Related
Instead of using a local mySQL Database i created an external database with https://remotemysql.com/. The problem I am having is that I cant connect to the database.
This is my hibernate config file:
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- SQL Dialect -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Database Connection Settings -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://www.remotemysql.com:3306/oJv6mOSx3X</property>
<property name="hibernate.connection.username">34kjldxck</property>
<property name="hibernate.connection.password">mysecpw</property>
<property name="show_sql">true</property>
<!-- Specifying Session Context -->
<property name="hibernate.current_session_context_class">org.hibernate.context.internal.ThreadLocalSessionContext</property>
<!-- Mapping With Model Class Containing Annotations -->
<mapping class="com.jcg.hibernate.maven.User" />
</session-factory>
This is how I am trying to connect to the database:
public class AppMain {
static Session sessionObj;
static SessionFactory sessionFactoryObj;
private static SessionFactory buildSessionFactory() {
// Creating Configuration Instance & Passing Hibernate Configuration File
Configuration configObj = new Configuration();
configObj.configure("hibernate.cfg.xml");
// Since Hibernate Version 4.x, ServiceRegistry Is Being Used
ServiceRegistry serviceRegistryObj = new StandardServiceRegistryBuilder().applySettings(configObj.getProperties()).build();
// Creating Hibernate SessionFactory Instance
sessionFactoryObj = configObj.buildSessionFactory(serviceRegistryObj);
return sessionFactoryObj;
}
public static void main(String[] args) {
try {
sessionObj = buildSessionFactory().openSession();
} catch(Exception ex){
ex.printStackTrace();
}
}
}
This is the error I get:
org.hibernate.exception.JDBCConnectionException: Error calling Driver#connect
at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator$1$1.convert(BasicConnectionCreator.java:122)
at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator.convertSqlException(BasicConnectionCreator.java:140)
at org.hibernate.engine.jdbc.connections.internal.DriverConnectionCreator.makeConnection(DriverConnectionCreator.java:58)
at org.hibernate.engine.jdbc.connections.internal.BasicConnectionCreator.createConnection(BasicConnectionCreator.java:75)
at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.configure(DriverManagerConnectionProviderImpl.java:106)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:111)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:234)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:206)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.buildJdbcConnectionAccess(JdbcServicesImpl.java:260)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:94)
at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:111)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:234)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:206)
at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1885)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1843)
at com.jcg.hibernate.maven.AppMain.buildSessionFactory(AppMain.java:24)
at com.jcg.hibernate.maven.AppMain.main(AppMain.java:30)
Caused by: java.sql.SQLException: java.lang.ClassCastException: java.math.BigInteger cannot be cast to java.lang.Long
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1074)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:988)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:974)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:919)
at com.mysql.jdbc.ConnectionImpl.buildCollationMapping(ConnectionImpl.java:1041)
at com.mysql.jdbc.ConnectionImpl.initializePropsFromServer(ConnectionImpl.java:3481)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2445)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2215)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:813)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:399)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:334)
at org.hibernate.engine.jdbc.connections.internal.DriverConnectionCreator.makeConnection(DriverConnectionCreator.java:55)
... 14 more
Caused by: java.lang.ClassCastException: java.math.BigInteger cannot be cast to java.lang.Long
at com.mysql.jdbc.ConnectionImpl.buildCollationMapping(ConnectionImpl.java:992)
... 27 more
enter code here
Now I am guessing that the error is because of the connection url I guess. Whats strange that i get am Math exception(igInteger cannot be cast to java.lang.Long)
if you scroll down into the error, in the caused by section , I think you have a field in database of type BigInteger and it's mapped to Long class field, which cause a ClassCastException
Hope it helps
This type of error indicates error to connect to the database
(search the exception for results).
It is hard to say what is the reason.
It could be related to the version of the connector.jar.
I would check that but first. Also would check if you are able to connect to a local database from your hibernate framework.
Spring JDBC Template can't execute Queries containing nested Query in the FROM clause
I am using spring JDBCTemplate to execute queries. And the code uses SqlRowSet, instead of RowMapper or RowExtractor.
Now there seems to be some problem while executing a Query which contains a nested query in the FROM clause. When I test the query in the Workbench or Mysql Console, it works perfectly fine.
Following is the code
JdbcTemplate jdbcTemplate = new JdbcTemplate(txManager.getDataSource());
try {
String sqlQuery = "SELECT profile.user_profile_id, profile.user_id, profile.first_name "
+ "FROM (SELECT user_profile_id, user_id, first_name FROM user_profile WHERE user_id = 1) AS profile";
// The following line is throwing exception
SqlRowSet resultSet = jdbcTemplate.queryForRowSet(sqlQuery);
if (resultSet.next()) {
...... // Put in a POJO
}
} catch(DataAccessException e) {
e.printStackTrace();
// Throw Proper User Defined Exception
}
But, if I change the Query to the following, it works perfectly fine.
String sqlQuery = "SELECT profile.user_profile_id, profile.user_id, profile.first_name "
+ "FROM user_profile AS profile";
NOTE : My database name is titans
I am getting the following exception. It says that table 'titans.*' doesn't exists. It seems absurd to me.
org.springframework.jdbc.BadSqlGrammarException: StatementCallback; bad SQL grammar [SELECT prof.user_profile_id, prof.user_id, prof.first_name, prof.last_name FROM (SELECT inner_prof.user_profile_id, inner_prof.user_id, inner_prof.first_name, inner_prof.last_name FROM titans.user_profile AS inner_prof WHERE user_id = 1) AS prof ]; nested exception is com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'titans.*' doesn't exist
at org.springframework.jdbc.support.SQLErrorCodeSQLExceptionTranslator.doTranslate(SQLErrorCodeSQLExceptionTranslator.java:237)
at org.springframework.jdbc.support.AbstractFallbackSQLExceptionTranslator.translate(AbstractFallbackSQLExceptionTranslator.java:72)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:407)
at org.springframework.jdbc.core.JdbcTemplate.query(JdbcTemplate.java:456)
at org.springframework.jdbc.core.JdbcTemplate.queryForRowSet(JdbcTemplate.java:501)
at com.titansinc.user.dsp.impl.UserDSP.getUserProfileByUserID(UserDSP.java:188)
at com.titansinc.user.service.UserService.getUserProfileByUserID(UserService.java:36)
at controllers.com.titans.play.controllers.Application.testReadMethod(Application.java:40)
at Routes$$anonfun$routes$1$$anonfun$applyOrElse$6$$anonfun$apply$24.apply(routes_routing.scala:141)
at Routes$$anonfun$routes$1$$anonfun$applyOrElse$6$$anonfun$apply$24.apply(routes_routing.scala:141)
at play.core.Router$HandlerInvokerFactory$$anon$4.resultCall(Router.scala:264)
at play.core.Router$HandlerInvokerFactory$JavaActionInvokerFactory$$anon$15$$anon$1.invocation(Router.scala:255)
at play.core.j.JavaAction$$anon$1.call(JavaAction.scala:55)
at play.GlobalSettings$1.call(GlobalSettings.java:67)
at play.core.j.JavaAction$$anonfun$11.apply(JavaAction.scala:82)
at play.core.j.JavaAction$$anonfun$11.apply(JavaAction.scala:82)
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:40)
at play.api.libs.iteratee.Execution$trampoline$.execute(Execution.scala:46)
at play.core.j.HttpExecutionContext.execute(HttpExecutionContext.scala:32)
at scala.concurrent.impl.Future$.apply(Future.scala:31)
at scala.concurrent.Future$.apply(Future.scala:492)
at play.core.j.JavaAction$class.apply(JavaAction.scala:82)
at play.core.Router$HandlerInvokerFactory$JavaActionInvokerFactory$$anon$15$$anon$1.apply(Router.scala:252)
at play.api.mvc.Action$$anonfun$apply$1$$anonfun$apply$4$$anonfun$apply$5.apply(Action.scala:130)
at play.api.mvc.Action$$anonfun$apply$1$$anonfun$apply$4$$anonfun$apply$5.apply(Action.scala:130)
at play.utils.Threads$.withContextClassLoader(Threads.scala:21)
at play.api.mvc.Action$$anonfun$apply$1$$anonfun$apply$4.apply(Action.scala:129)
at play.api.mvc.Action$$anonfun$apply$1$$anonfun$apply$4.apply(Action.scala:128)
at scala.Option.map(Option.scala:145)
at play.api.mvc.Action$$anonfun$apply$1.apply(Action.scala:128)
at play.api.mvc.Action$$anonfun$apply$1.apply(Action.scala:121)
at play.api.libs.iteratee.Iteratee$$anonfun$mapM$1.apply(Iteratee.scala:483)
at play.api.libs.iteratee.Iteratee$$anonfun$mapM$1.apply(Iteratee.scala:483)
at play.api.libs.iteratee.Iteratee$$anonfun$flatMapM$1.apply(Iteratee.scala:519)
at play.api.libs.iteratee.Iteratee$$anonfun$flatMapM$1.apply(Iteratee.scala:519)
at play.api.libs.iteratee.Iteratee$$anonfun$flatMap$1$$anonfun$apply$14.apply(Iteratee.scala:496)
at play.api.libs.iteratee.Iteratee$$anonfun$flatMap$1$$anonfun$apply$14.apply(Iteratee.scala:496)
at scala.concurrent.impl.Future$PromiseCompletingRunnable.liftedTree1$1(Future.scala:24)
at scala.concurrent.impl.Future$PromiseCompletingRunnable.run(Future.scala:24)
at akka.dispatch.TaskInvocation.run(AbstractDispatcher.scala:41)
at akka.dispatch.ForkJoinExecutorConfigurator$AkkaForkJoinTask.exec(AbstractDispatcher.scala:393)
at scala.concurrent.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260)
at scala.concurrent.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339)
at scala.concurrent.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979)
at scala.concurrent.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107)
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'titans.*' doesn't exist
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:377)
at com.mysql.jdbc.Util.getInstance(Util.java:360)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:978)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3887)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3823)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2435)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2582)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2526)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2484)
at com.mysql.jdbc.StatementImpl.executeQuery(StatementImpl.java:1446)
at com.mysql.jdbc.Field.getCollation(Field.java:448)
at com.mysql.jdbc.ResultSetMetaData.isCaseSensitive(ResultSetMetaData.java:549)
at com.sun.rowset.CachedRowSetImpl.initMetaData(CachedRowSetImpl.java:722)
at com.sun.rowset.CachedRowSetImpl.populate(CachedRowSetImpl.java:639)
at org.springframework.jdbc.core.SqlRowSetResultSetExtractor.createSqlRowSet(SqlRowSetResultSetExtractor.java:79)
at org.springframework.jdbc.core.SqlRowSetResultSetExtractor.extractData(SqlRowSetResultSetExtractor.java:62)
at org.springframework.jdbc.core.SqlRowSetResultSetExtractor.extractData(SqlRowSetResultSetExtractor.java:45)
at org.springframework.jdbc.core.JdbcTemplate$1QueryStatementCallback.doInStatement(JdbcTemplate.java:446)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:396)
... 44 more
Looks like queryForRowSet(sqlQuery) method has this bug. I reported the bug on spring JIRA.
An alternative approach would be to use ResultSetExtractor or RowMapper to implement the db call. This implementation doesn't throw any exceptions for the above mentioned queries.
....
String sqlQuery = ".....";
Object[] parameters = { .... };
ITestPOJO resultList = jdbcTemplate.query(sqlQuery, parameters,
new ResultSetExtractor<ITestPOJO>() {
#Override
public ITestPOJO extractData(ResultSet rs) throws SQLException, DataAccessException {
// TODO use ResultSet from here
// return ITestPOJO object
}
});
...
I have problem log exception only message is logged.
NLog config:
<target name="logfile"
xsi:type="File"
fileName="log.txt"
layout="${longdate} | ${machinename} | ${processid} | ${processname} | ${level} | ${logger} | |${message} | ${exception:format=tostring}" />
<logger name="*"
minlevel="Info"
writeTo="logfile" />
Usage:
private static Logger _logger = LogManager.GetCurrentClassLogger();
_logger.Error("my message", new Exception("my exception"));
Log output:
2014-04-24 18:17:29.0841 | PC_NAME | 6464 | APP_NAME.vshost | Error | AppName.ViewModel | my message |
Exception is ignore.
I found some thread but for me not work.
Nlog is using sepecial methods for logging exceptions which are using the <loglevel>Exception naming schema.
So in your case you need to use the ErrorException method in order to your exceptions get logged correctly:
private static Logger _logger = LogManager.GetCurrentClassLogger();
_logger.ErrorException("my message", new Exception("my exception"));
Actually, void Error(string message, Exception exception); is obsolete
You can use ILogger.Error(Exception, string) method like below
catch (Exception e)
{
Log.Error(e, "it happens");
}
and a little bit modified layout with ${onexception}. This will check is there an exception to be logged
<target name="logfile"
xsi:type="File"
fileName="log.txt"
layout="${longdate} | ${machinename} | ${processid} | ${processname} | ${level} | ${logger} | |${message} ${onexception:| ${exception:format=tostring}}" />
/>
Entity classes were created in Eclipse using the JPA wizard from an existing MySQL database, but had to remove the #OneToMany annotations because these errors pop up during enhancement (using DataNucleus Enhancer version 3.1.1).
java.lang.RuntimeException: Unexpected exception
at com.google.appengine.tools.enhancer.Enhancer.execute(Enhancer.java:76)
at com.google.appengine.tools.enhancer.Enhance.<init>(Enhance.java:71)
at com.google.appengine.tools.enhancer.Enhance.main(Enhance.java:51)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.google.appengine.tools.enhancer.Enhancer.execute(Enhancer.java:74)
... 2 more
Caused by: java.lang.VerifyError: Expecting a stackmap frame at branch target 40
Exception Details:
Location:
cultivartehidroponia/Order.getOrderItems()Ljava/util/List; #4: ifnull
Reason:
Expected stackmap frame at this location.
Bytecode:
0000000: 2ab4 004a c600 242a b400 4a2a 07b9 006f
0000010: 0300 9a00 162a b400 4a2a 072a b601 0db9
0000020: 0098 0400 c001 0fb0 2ab6 0056 9900 2e2a
0000030: b400 5a05 32c0 005c 07b6 0079 9a00 1e2a
0000040: b400 5a06 32c0 005c 07b6 0079 9a00 0ebb
0000050: 007b 5913 0111 b700 80bf 2ab6 010d b0
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2531)
at java.lang.Class.getDeclaredMethods(Class.java:1855)
at org.datanucleus.metadata.annotations.AbstractAnnotationReader.getJavaBeanAccessorAnnotationsForClass(AbstractAnnotationReader.java:310)
at org.datanucleus.metadata.annotations.AbstractAnnotationReader.getMetaDataForClass(AbstractAnnotationReader.java:146)
at org.datanucleus.metadata.annotations.AnnotationManagerImpl.getMetaDataForClass(AnnotationManagerImpl.java:171)
at org.datanucleus.metadata.MetaDataManager.loadAnnotationsForClass(MetaDataManager.java:2650)
at org.datanucleus.metadata.MetaDataManager.loadClasses(MetaDataManager.java:496)
at org.datanucleus.enhancer.DataNucleusEnhancer.getFileMetadataForInput(DataNucleusEnhancer.java:734)
at org.datanucleus.enhancer.DataNucleusEnhancer.enhance(DataNucleusEnhancer.java:525)
at org.datanucleus.enhancer.DataNucleusEnhancer.main(DataNucleusEnhancer.java:1258)
... 7 more
I can use the entities fine, just without the mapped-by fields.
To bypass this issue, I had to temporarily implement this functionality using transient fields, such as:
#Transient private List<ViewProduct> products;
and simulate the #OneToMany feature manually as:
public List<ViewProduct> getProducts() {
EntityManager em = EMF.get().createEntityManager();
EntityTransaction trans = em.getTransaction();
try {
trans.begin();
this.products = em.createNamedQuery("ViewProduct.findByProductTemplate", ViewProduct.class).setParameter("prodTemplateId", this.getProdTemplateId()).getResultList();
trans.commit();
}...
But this defeats the purpose of having that nice feature... ;(
Maybe a configuration issue? But why does everything else work and not this?
Anyone out there with similar errors? Any recommendations?
Thanks in advance!!!
DataNucleus v3.1 is not supported/developed, and hasn't been for some time. You should use v3.2+, which has at least one fix to JDK 1.7 enhancement.
If you are using Eclipse and Google plug-in, you may need to upgrade the IDE. I was using Indigo with 1.9.4 and I have similar issues with the enhancer. Problem is gone after I switched to Kepler with the associated Google plug-in, etc.
After solving my initial properties-local.xml issue, I have moved on to another problem. I initially had a naming context error that I resolved by changing the value of oxf.fr.persistence.provider.*.*.* to be db matching my resource definition for JBoss.
Now, when saving a form definition I receive an error dialogue with the message.
There was an error communicating with the database.
Please contact the application administrator.
When I check the server.log I noticed that the first exception occurred after clicking continue after inputting the new form name, title and description.
The exception is this:
21:41:26,312 ERROR [org.orbeon.oxf.controller.PageFlowControllerProcessor] (http--127.0.0.1-8080-8) error caught {controller: "oxf:/apps/fr/page-flow.xml", method: "GET", path: "/fr/service/persistence/crud/orbeon/library/form/form.xhtml"}
21:41:26,406 ERROR [org.orbeon.oxf.controller.PageFlowControllerProcessor] (http--127.0.0.1-8080-8)
+----------------------------------------------------------------------------------------------------------------------+
|An Error has Occurred |
|----------------------------------------------------------------------------------------------------------------------|
|org.orbeon.oxf.common.ValidationException: line 18, column 47 of oxf:/apps/fr/persistence/proxy.xpl (executing process|
|----------------------------------------------------------------------------------------------------------------------|
|Application Call Stack |
|----------------------------------------------------------------------------------------------------------------------|
|oxf:/apps/fr/page-flow.xml |reading page model data output| 18|
|······················································································································|
|element=<service path="/fr/service/persistence/.*" model="persistence/proxy.xpl"/> |
|model =persistence/proxy.xpl |
|----------------------------------------------------------------------------------------------------------------------|
|oxf:/apps/fr/persistence/proxy.xpl |executing processor | 18|
|······················································································································|
|element=<p:processor name="fr:persistence-proxy"/> |
|name ={http://orbeon.org/oxf/xml/form-runner}persistence-proxy |
|----------------------------------------------------------------------------------------------------------------------|
|----------------------------------------------------------------------------------------------------------------------|
|Exception: java.lang.NullPointerException |
I'm assuming my properties-local.xml needs some work. Here are the contents:
<properties xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:oxf="http://www.orbeon.com/oxf/processors">
<property as="xs:string" name="oxf.fr.persistence.provider.*.*.*" value="db"/>
<property as="xs:string" name="oxf.fr.persistence.mysql.datasource" value="db"/>
</properties>
I had the same error without the second property.