this is the error
org.hibernate.hql.ast.QuerySyntaxException: Payment is not mapped [select p from Payment p]
I don't understand how come this error is thrown, the class should be mapped as I will show you briefly. I have a very basic config, like this one: http://docs.jboss.org/hibernate/annotations/3.5/reference/en/html/ch01.html
I have tried to add the mapping definition into hibernate.cfg.xml and I have also tried to add it programmatically. Neither of them worked. Could anybody tell me what am I missing here? (it is not the first time I put together a Hibernate project)
this is the hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/paymentsdatabase</property>
<property name="hibernate.connection.username">xxx</property>
<property name="hibernate.connection.password">xxx</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.hbm2ddl.auto">create</property>
<!-- <mapping class="com.lsyh.swati.zk.model.Payment"/> -->
</session-factory>
</hibernate-configuration>
the database connection is working fine, I have tested that
this is the static initializer in my HibernateUtil
static {
try {
// Create the SessionFactory from standard (hibernate.cfg.xml)
// config file.
sessionFactory = new AnnotationConfiguration()
.addPackage("com.lsyh.swati.zk.model")
.addAnnotatedClass(Payment.class)
.configure().buildSessionFactory();
} catch (Throwable ex) {
// Log the exception.
System.err.println("Initial SessionFactory creation failed. " + ex);
throw new ExceptionInInitializerError(ex);
}
}
and this is where I use the sessionFactory in the PaymentIODb class:
public static List<Payment> readDataFromDb(){
StatelessSession session = StoreHibernateUtil.getSessionFactory().openStatelessSession();
Query query = session.createQuery("select p from Payment p");
List<Payment> payments = query.list();
session.close();
return payments;
}
this is the stack trace
org.hibernate.hql.ast.QuerySyntaxException: Payment is not mapped [select p from Payment p]
at org.hibernate.hql.ast.util.SessionFactoryHelper.requireClassPersister(SessionFactoryHelper.java:158)
at org.hibernate.hql.ast.tree.FromElementFactory.addFromElement(FromElementFactory.java:87)
at org.hibernate.hql.ast.tree.FromClause.addFromElement(FromClause.java:70)
at org.hibernate.hql.ast.HqlSqlWalker.createFromElement(HqlSqlWalker.java:255)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.fromElement(HqlSqlBaseWalker.java:3056)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.fromElementList(HqlSqlBaseWalker.java:2945)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.fromClause(HqlSqlBaseWalker.java:688)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:544)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:281)
at org.hibernate.hql.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:229)
at org.hibernate.hql.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:228)
at org.hibernate.hql.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:160)
at org.hibernate.hql.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:111)
at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:77)
at org.hibernate.engine.query.HQLQueryPlan.<init>(HQLQueryPlan.java:56)
at org.hibernate.engine.query.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:72)
at org.hibernate.impl.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:133)
at org.hibernate.impl.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:112)
at com.lsyh.swati.zk.controller.PaymentIODb.readDataFromDb(PaymentIODb.java:35)
at com.lsyh.swati.zk.controller.PaymentIODb.resolveVariable(PaymentIODb.java:20
I'd expect one of two things to be the reason:
either you don't have Payment listed in your hibernat.cfg.xml or where ever you config your mapped classes.
another reason might be the confusion between javax...Entity and org.hibernate....Entity. Make sure you use the first one.
Instead of
Query query = session.createQuery("select p from Payment p");
try this
Query query = session.createQuery("select p from " + Payment.class.getName() + " p");
uncomment the commented mapping code in hibernate.cfg.xml config file
<!-- <mapping class="com.lsyh.swati.zk.model.Payment"/> -->
change it to
<mapping class="com.lsyh.swati.zk.model.Payment"/>
for more information refer this link
http://www.javabeat.net/tips/112-configure-mysql-database-with-hibernate-mappi.html
Your entity bean is not getting registered i guess.
Set proper root package name of your entity beans in packagesToScan property.
Also check your #Table(name="name_of_your_table").
Although accepted answer is correct, would like to add context to the first part of the answer.
Inside of your config.java (or whatever you have named your application configuration file in packages), ensure you have properly configured your entityScan:
package com.example.config;
import org.springframework.boot.autoconfigure.domain.EntityScan;
#EntityScan("com.example.entities")
However, if you like our team have moved your objects into their own packages, you may want to allow for a scan of all package folders:
#EntityScan("com.example.*")
Now that not all entities are in the entities folder specifically.
For me, my Class was not listed in my Persistence.xml file in the class section.
Do that to solve the ish. or wherever your classes are listed.
I had same problem , instead #Entityt mapping i
I used following code for getting records
private #Autowired HibernateTemplate incidentHibernateTemplate;
List<Map<String, Object>> list = null;
list = incidentHibernateTemplate.execute(new HibernateCallback<List<Map<String, Object>>>() {
#Override
public List<Map<String, Object>> doInHibernate(Session session) throws HibernateException {
Query query = session.createSQLQuery("SELECT * from table where appcode = :app");
query.setParameter("app", apptype);
query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);
return query.list();
}
});
I used following code for update
private #Autowired HibernateTemplate incidentHibernateTemplate;
Integer updateCount = 0;
updateCount = incidentHibernateTemplate.execute((Session session) -> {
Query<?> query = session
.createSQLQuery("UPDATE tablename SET key = :apiurl, data_mode = :mode WHERE apiname= :api ");
query.setParameter("apiurl", url);
query.setParameter("api", api);
query.setParameter("mode", mode);
return query.executeUpdate();
}
);
Related
I'm using Spring and Hibernate (hibernate-core 3.3.1.GA), and as a result of a web call, the code does a transaction with several inserts. Sometimes, one of the inserts fails with Hibernate saying 'Duplicate entry ... for key 'PRIMARY'. I have not been able to identify any pattern on when this happens -- it may work for 4 - 5 requests, and then it fails, then works on retrying, and then may fail on the next request.
Below are the relevant parts of the code:
Controller
#RequestMapping(value = "/users", method = RequestMethod.POST)
public #ResponseBody Map<Object, Object> save(<params>) throws IllegalArgumentException {
...
try {
map = userHelper.save(<parameters>);
...
} catch (Exception e) {
e.printStackTrace();
}
}
The exception is thrown in the above part.
UserHelper.save() method
#Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
public HashMap<String, Object> save(<parameters>) throws NumberParseException, IllegalArgumentException, HibernateException {
....
userService.save(<parameters>);
return save;
}
UserService
HBDao dao;
#Autowired
public UserService(org.hibernate.SessionFactory sessionFactory) {
dao = new HBDao(sessionFactory);
}
...
#Transactional(propagation = Propagation.SUPPORTS, rollbackFor = Exception.class)
public HashMap<String, Object> save(<parameters>) throws NumberParseException {
...
User user;
// several lines to create User object
dao.save(user);
...
lookupService.saveUserConfigurations(user, userType, loginById);
...
return response;
}
HBDao
This class wraps hibernate sessions.
public HBDao(SessionFactory sf) {
this.sessionFactory = sf;
}
private Session getSession() {
sessionFactory.getCurrentSession();
}
public void save(Object instance) {
try {
getSession().saveOrUpdate(instance);
} catch (RuntimeException re) {
throw re;
}
}
lookupService.saveUserConfigurations(user, userType, loginById) call results in the below methods in LookupRepository class to be executed:
LookupRepository
#Transactional(propagation = Propagation.SUPPORTS, rollbackFor = Exception.class)
public LookupMapping save(LookupMapping configuration) {
dao.save(configuration);
return configuration;
}
public Collection<LookupMapping> saveAll(Collection<LookupMapping> configurations) {
configurations.forEach(this::save);
return configurations;
}
LookupMapping
#Entity
public class LookupMapping {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long configId;
...
}
Hibernate Mapping for LookupMapping class
<hibernate-mapping package="com...configuration.domain">
<class name="LookupMapping" table="lookup_mapping" mutable="false">
<id column="id" name="configId" type="long">
<generator class="increment"/>
</id>
...
</class>
</hibernate-mapping>
Hibernate config
<hibernate-configuration>
<session-factory name="sosFactory">
<!-- Database connection settings -->
...
<property name="connection.pool_size">2</property>
<!-- SQL dialect -->
<property name="dialect">com. ... .CustomDialect</property>
<!-- Enable Hibernate's current session context -->
<property name="current_session_context_class">org.hibernate.context.ManagedSessionContext</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<property name="format_sql">true</property>
...
</session-factory>
</hibernate-configuration>
Below are the lines from the log:
2018-05-04 10:24:51.321 7|13|60f566fa-4f85-11e8-ba9b-93dd5bbf4a00 ERROR [http-nio-8080-exec-1] org.hibernate.util.JDBCExceptionReporter - Duplicate entry '340932' for key 'PRIMARY'
2018-05-04 10:24:51.321 7|13|60f566fa-4f85-11e8-ba9b-93dd5bbf4a00 WARN [http-nio-8080-exec-1] org.hibernate.util.JDBCExceptionReporter - SQL Error: 1062, SQLState: 23000
2018-05-04 10:24:51.322 7|13|60f566fa-4f85-11e8-ba9b-93dd5bbf4a00 ERROR [http-nio-8080-exec-1] org.hibernate.event.def.AbstractFlushingEventListener - Could not synchronize database state with session
org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:94) ~[hibernate-core-3.3.1.GA.jar:3.3.1.GA]
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66) ~[hibernate-core-3.3.1.GA.jar:3.3.1.GA]
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:275) ~[hibernate-core-3.3.1.GA.jar:3.3.1.GA]
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:266) ~[hibernate-core-3.3.1.GA.jar:3.3.1.GA]
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:167) ~[hibernate-core-3.3.1.GA.jar:3.3.1.GA]
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321) [hibernate-core-3.3.1.GA.jar:3.3.1.GA]
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:50) [hibernate-core-3.3.1.GA.jar:3.3.1.GA]
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1027) [hibernate-core-3.3.1.GA.jar:3.3.1.GA]
at com.arl.mg.helpers.UserHelper.save(UserHelper.java:329) [classes/:?]
...
I'm working on a legacy codebase (so cannot upgrade Hibernate easily), and the code that I wrote are in LookupRepository class (and LookupService which is called in UserService).
The Duplicate entry error happens while persisting the LookupMapping objects. There are always two of this object being persisted, and when the error occurs, the duplicate ID is created same as the last entry. That is, if for the first request, IDs 999 and 1000 were inserted, and if the error occurs for the next request, the duplicate ID will be 1000 (and not 999).
Another, possibly important thing to note is that Hibernate shows this line:
org.hibernate.jdbc.ConnectionManager [] - transaction completed on session with on_close connection release mode; be sure to close the session to release JDBC resources!
This is all the info that I have so far, and I hope I've covered the relevant code as well. Any help will be much appreciated. Do let me know if I have to give more info.
Thanks!
The problem was with the ID generation strategy defined in the Hibernate mapping file.
The strategy was set as increment, which seems to work only when there are no other processes inserting to the table. In my case, it seems that sometimes there were previously open sessions, and new requests ended up inserting to the table simultaneously.
The solution was to change the strategy to native, which uses the underlying database's strategy to generate ID.
<hibernate-mapping package="com...configuration.domain">
<class name="LookupMapping" table="lookup_mapping" mutable="false">
<id column="id" name="configId" type="long">
<generator class="native"/>
</id>
...
</class>
</hibernate-mapping>
I agree with response by #shyam I would switch to some sequence generator.
But also have a look at this peace of code:
User user;
// several lines to create User object
dao.save(user);
...
lookupService.saveUserConfigurations(user, userType, loginById);
In this case you are sending user to saveUserConfigurations which is not managed, and within saveUserConfigurations you might calling merge method. This will cause additional insert statement. Consider refactoring your code to:
User user;
// several lines to create User object
// dao.save should return the stored value of user.
user = dao.save(user);
...
lookupService.saveUserConfigurations(user, userType, loginById);
With such constructions you will be using stored entity (i.e. managed by current hibernate's session). and have a look at all your code and prevent usage of not managed entities once those have been stored.
I am trying to integrate my java play application with hibernate orm and here is my project structure.
As you can see, I have placed my pojos inside a package named models and hibernate.cfg.xml inside conf.
hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/db_name</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">password</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hibernate.enable_lazy_load_no_trans">true</property>
<mapping resource="models/Coating.hbm.xml"/>
<mapping resource="models/Fitting.hbm.xml"/>
<mapping resource="models/Product.hbm.xml"/>
<mapping resource="models/ProductHasCoating.hbm.xml"/>
<mapping resource="models/ProductHasFitting.hbm.xml"/>
<mapping resource="models/ProductHasSize.hbm.xml"/>
<mapping resource="models/Size.hbm.xml"/>
</session-factory>
</hibernate-configuration>
HibernateUtil class : (inside services)
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
// Create the SessionFactory from standard (hibernate.cfg.xml)
// config file.
sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
} catch (Throwable ex) {
// Log the exception.
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
Controller Class
public class LoginController extends Controller {
public Result login() throws SQLException {
Session s = HibernateUtil.getSessionFactory().openSession();
Criteria c = s.createCriteria(Coating.class);
c.add(Restrictions.eq("code", "CO3444"));
Coating co = (Coating) c.uniqueResult();
String title = co.getTitle();
s.close();
return ok(views.html.login_page.login.render(title));
}
}
Everything seems fine for me and once I compile and run the application, It terminates the application server with below error.
Initial SessionFactory creation failed.org.hibernate.InvalidMappingException: Could not parse mapping document from resource models/Coating.hbm.xml
Uncaught error from thread [play-dev-mode-akka.actor.default-dispatcher-4]: null, shutting down JVM since 'akka.jvm-exit-on-fatal-error' is enabled for for ActorSystem[play-dev-mode]
java.lang.ExceptionInInitializerError
at services.HibernateUtil.<clinit>(HibernateUtil.java:18)
at controllers.LoginController.login(LoginController.java:15)
at router.Routes$$anonfun$routes$1.$anonfun$applyOrElse$2(Routes.scala:164)
at play.core.routing.HandlerInvokerFactory$$anon$3.resultCall(HandlerInvoker.scala:134)
at play.core.routing.HandlerInvokerFactory$$anon$3.resultCall(HandlerInvoker.scala:133)
at play.core.routing.HandlerInvokerFactory$JavaActionInvokerFactory$$anon$8$$anon$2$$anon$1.invocation(HandlerInvoker.scala:108)
at play.core.j.JavaAction$$anon$1.call(JavaAction.scala:82)
at play.http.DefaultActionCreator$1.call(DefaultActionCreator.java:31)
at play.core.j.JavaAction.$anonfun$apply$8(JavaAction.scala:132)
at scala.concurrent.Future$.$anonfun$apply$1(Future.scala:653)
at scala.util.Success.$anonfun$map$1(Try.scala:251)
at scala.util.Success.map(Try.scala:209)
at scala.concurrent.Future.$anonfun$map$1(Future.scala:287)
at scala.concurrent.impl.Promise.liftedTree1$1(Promise.scala:29)
at scala.concurrent.impl.Promise.$anonfun$transform$1(Promise.scala:29)
at scala.concurrent.impl.CallbackRunnable.run(Promise.scala:60)
at play.core.j.HttpExecutionContext$$anon$2.run(HttpExecutionContext.scala:56)
at play.api.libs.streams.Execution$trampoline$.execute(Execution.scala:70)
at play.core.j.HttpExecutionContext.execute(HttpExecutionContext.scala:48)
at scala.concurrent.impl.CallbackRunnable.executeWithValue(Promise.scala:68)
at scala.concurrent.impl.Promise$KeptPromise$Kept.onComplete(Promise.scala:368)
at scala.concurrent.impl.Promise$KeptPromise$Kept.onComplete$(Promise.scala:367)
at scala.concurrent.impl.Promise$KeptPromise$Successful.onComplete(Promise.scala:375)
at scala.concurrent.impl.Promise.transform(Promise.scala:29)
at scala.concurrent.impl.Promise.transform$(Promise.scala:27)
at scala.concurrent.impl.Promise$KeptPromise$Successful.transform(Promise.scala:375)
at scala.concurrent.Future.map(Future.scala:287)
at scala.concurrent.Future.map$(Future.scala:287)
at scala.concurrent.impl.Promise$KeptPromise$Successful.map(Promise.scala:375)
at scala.concurrent.Future$.apply(Future.scala:653)
at play.core.j.JavaAction.apply(JavaAction.scala:132)
at play.api.mvc.Action.$anonfun$apply$2(Action.scala:96)
at play.api.libs.streams.StrictAccumulator.$anonfun$mapFuture$4(Accumulator.scala:174)
at scala.util.Try$.apply(Try.scala:209)
at play.api.libs.streams.StrictAccumulator.$anonfun$mapFuture$3(Accumulator.scala:174)
at scala.Function1.$anonfun$andThen$1(Function1.scala:52)
at scala.Function1.$anonfun$andThen$1(Function1.scala:52)
at play.api.libs.streams.StrictAccumulator$$anon$1.apply(Accumulator.scala:218)
at play.api.libs.streams.StrictAccumulator$$anon$1.apply(Accumulator.scala:217)
at java.util.function.Function.lambda$andThen$1(Function.java:88)
at java.util.function.Function.lambda$andThen$1(Function.java:88)
at play.libs.streams.Accumulator$StrictAccumulator$1.apply(Accumulator.java:403)
at play.libs.streams.Accumulator$StrictAccumulator$1.apply(Accumulator.java:400)
at scala.Function1.$anonfun$andThen$1(Function1.scala:52)
at scala.Function1.$anonfun$andThen$1(Function1.scala:52)
at scala.Function1.$anonfun$andThen$1(Function1.scala:52)
at play.api.libs.streams.StrictAccumulator.run(Accumulator.scala:207)
at play.core.server.AkkaHttpServer.executeAction(AkkaHttpServer.scala:298)
at play.core.server.AkkaHttpServer.executeHandler(AkkaHttpServer.scala:255)
at play.core.server.AkkaHttpServer.handleRequest(AkkaHttpServer.scala:201)
at play.core.server.AkkaHttpServer.$anonfun$createServerBinding$1(AkkaHttpServer.scala:107)
at akka.stream.impl.fusing.MapAsync$$anon$24.onPush(Ops.scala:1191)
at akka.stream.impl.fusing.GraphInterpreter.processPush(GraphInterpreter.scala:512)
at akka.stream.impl.fusing.GraphInterpreter.processEvent(GraphInterpreter.scala:475)
at akka.stream.impl.fusing.GraphInterpreter.execute(GraphInterpreter.scala:371)
at akka.stream.impl.fusing.GraphInterpreterShell.runBatch(ActorGraphInterpreter.scala:584)
at akka.stream.impl.fusing.GraphInterpreterShell$AsyncInput.execute(ActorGraphInterpreter.scala:468)
at akka.stream.impl.fusing.GraphInterpreterShell.processEvent(ActorGraphInterpreter.scala:559)
at akka.stream.impl.fusing.ActorGraphInterpreter.akka$stream$impl$fusing$ActorGraphInterpreter$$processEvent(ActorGraphInterpreter.scala:741)
at akka.stream.impl.fusing.ActorGraphInterpreter$$anonfun$receive$1.applyOrElse(ActorGraphInterpreter.scala:756)
at akka.actor.Actor.aroundReceive(Actor.scala:517)
at akka.actor.Actor.aroundReceive$(Actor.scala:515)
at akka.stream.impl.fusing.ActorGraphInterpreter.aroundReceive(ActorGraphInterpreter.scala:666)
at akka.actor.ActorCell.receiveMessage(ActorCell.scala:527)
at akka.actor.ActorCell.invoke(ActorCell.scala:496)
at akka.dispatch.Mailbox.processMailbox(Mailbox.scala:257)
at akka.dispatch.Mailbox.run(Mailbox.scala:224)
at akka.dispatch.Mailbox.exec(Mailbox.scala:234)
at akka.dispatch.forkjoin.ForkJoinTask.doExec(ForkJoinTask.java:260)
at akka.dispatch.forkjoin.ForkJoinPool$WorkQueue.runTask(ForkJoinPool.java:1339)
at akka.dispatch.forkjoin.ForkJoinPool.runWorker(ForkJoinPool.java:1979)
at akka.dispatch.forkjoin.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:107)
Caused by: org.hibernate.InvalidMappingException: Could not parse mapping document from resource models/Coating.hbm.xml
at org.hibernate.cfg.Configuration$MetadataSourceQueue.processHbmXml(Configuration.java:3764)
at org.hibernate.cfg.Configuration$MetadataSourceQueue.processHbmXmlQueue(Configuration.java:3753)
at org.hibernate.cfg.Configuration$MetadataSourceQueue.processMetadata(Configuration.java:3741)
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1410)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1844)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1928)
at services.HibernateUtil.<clinit>(HibernateUtil.java:14)
... 71 more
Caused by: org.hibernate.MappingException: class models.Coating not found while looking for property: id
at org.hibernate.internal.util.ReflectHelper.reflectedPropertyClass(ReflectHelper.java:233)
at org.hibernate.mapping.SimpleValue.setTypeUsingReflection(SimpleValue.java:362)
at org.hibernate.cfg.HbmBinder.bindSimpleId(HbmBinder.java:453)
at org.hibernate.cfg.HbmBinder.bindRootPersistentClassCommonValues(HbmBinder.java:386)
at org.hibernate.cfg.HbmBinder.bindRootClass(HbmBinder.java:326)
at org.hibernate.cfg.HbmBinder.bindRoot(HbmBinder.java:177)
at org.hibernate.cfg.Configuration$MetadataSourceQueue.processHbmXml(Configuration.java:3761)
... 77 more
Caused by: java.lang.ClassNotFoundException: models.Coating
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:264)
at org.hibernate.internal.util.ReflectHelper.classForName(ReflectHelper.java:193)
at org.hibernate.internal.util.ReflectHelper.reflectedPropertyClass(ReflectHelper.java:229)
... 83 more
UPDATED
But once I remove all the mappings from hibernate.cfg.xml and change the LoginController code to below :
Session s = HibernateUtil.getSessionFactory().openSession();
Connection c = s.getSessionFactory().getSessionFactoryOptions().getServiceRegistry()
.getService(ConnectionProvider.class).getConnection();
//Criteria c = s.createCriteria(Coating.class);
//c.add(Restrictions.eq("code", "CO3444"));
//Coating co = (Coating) c.uniqueResult();
//String title = co.getTitle();
//s.close();
String title = c.getMetaData().getDatabaseProductName();
return ok(views.html.login_page.login.render(title));
Application starts and runs fine in the browser with the output of MySQL
Which means there is no any hibernate configuration errors and no any errors with the HibernateUtil class either.
Any help would be appreciable. Thank you.
In this case play-framework does not look for the xml mappings inside model package. So I have to put them inside conf package together with hibernate.cfg.xml. Below image shows how the project structure looks like:
And then do not forget to add
Thread.currentThread().setContextClassLoader(OneOfYourModelClass.class.getClassLoader());
line inside the HibernateUtil class before building the session factory.
...
static {
try {
Thread.currentThread().setContextClassLoader(SomeClass.class.getClassLoader());
sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
} catch (Throwable ex) {
...
so the context can be set ClassLoader of one Entity and the others are also loaded properly.
I'm creating an application with Hibernate JPA and I use c3p0 for connection pooling with MySQL. I have an issue with the number of connections to the MySQL database as it hits the 152 opened connections, this is not wanted since I define in my c3p0 config file the max pool size to 20, and of course I close every entity manager I get from the EntityManagerFactory after committing every transaction.
For every time a controller is executed, I notice more than 7 connections are opened, and if I refresh, then 7 connections are opened again without the past idle connections being closed. And in every DAO function I call, the em.close() is executed. I admit here that the issue is in my code, but I don't know what I am doing wrong here.
This is the Sondage.java entity:
#Entity
#NamedQuery(name="Sondage.findAll", query="SELECT s FROM Sondage s")
public class Sondage implements Serializable {
private static final long serialVersionUID = 1L;
public Sondage() {}
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
private byte needLocation;
//bi-directional many-to-one association to ResultatSondage
#OneToMany(mappedBy = "sondage", cascade = CascadeType.ALL)
#OrderBy("sondage ASC")
private List<ResultatSondage> resultatSondages;
//bi-directional many-to-one association to SondageSection
#OneToMany(mappedBy = "sondage", cascade = CascadeType.ALL)
private List<SondageSection> sondageSections;
}
And here's my DAO class:
#SuppressWarnings("unchecked")
public static List<Sondage> GetAllSondage() {
EntityManager em = PersistenceManager.getEntityManager();
List<Sondage> allSondages = new ArrayList<>();
try {
em.getTransaction().begin();
Query query = em.createQuery("SELECT s FROM Sondage s");
allSondages = query.getResultList();
em.getTransaction().commit();
} catch (Exception ex) {
if (em.getTransaction().isActive()) {
em.getTransaction().rollback();
}
allSondages = null;
} finally {
em.close();
}
return allSondages;
}
As you see, em is closed. In my JSP, I do this: I know this is not the good way of doing thing in the view side.
<body>
<div class="header">
<%#include file="../../../Includes/header.jsp" %>
</div>
<h2 style="color: green; text-align: center;">الاستمارات</h2>
<div id="allsurveys" class="pure-menu custom-restricted-width">
<%
List<Sondage> allSondages = (List<Sondage>) request.getAttribute("sondages");
for (int i = 0; i < allSondages.size(); i++) {
%>
<%= allSondages.get(i).getName()%>
<%
if (request.getSession().getAttribute("user") != null) {
Utilisateur user = (Utilisateur) request.getSession().getAttribute("user");
if (user.getType().equals("admin")) {
%>
تعديل
<%
}
}
%>
<br />
<%
}
%>
</div>
</body>
I'm guessing that every time I call user.getType(), a request is established ? If so, how can I prevent this?
For c4p0 config file, I included it in persistence.xml, I saw several posts saying that I need to put the c3p0 config file in c3p0-config.xml, but with my setup the c3p0 is initialized with the values I pass in the persistence.xml file, also the mysql connections are reaching 152 connections but the maxpoolsize is at 20, here's the persistence.xml file
<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="CAOE" transaction-type="RESOURCE_LOCAL">
<class>com.caoe.Models.ChoixQuestion</class>
<class>com.caoe.Models.Question</class>
<class>com.caoe.Models.Reponse</class>
<class>com.caoe.Models.ResultatSondage</class>
<class>com.caoe.Models.Section</class>
<class>com.caoe.Models.Sondage</class>
<class>com.caoe.Models.SondageSection</class>
<class>com.caoe.Models.SousQuestion</class>
<class>com.caoe.Models.Utilisateur</class>
<properties>
<property name="hibernate.connection.provider_class"
value=" org.hibernate.service.jdbc.connections.internal.C3P0ConnectionProvider" />
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.connection.password" value=""/>
<property name="hibernate.connection.url"
value="jdbc:mysql://localhost:3306/caoe?useUnicode=yes&characterEncoding=UTF-8"/>
<property name="hibernate.connection.username" value="root"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.c3p0.max_size" value="50" />
<property name="hibernate.c3p0.min_size" value="3" />
<property name="hibernate.c3p0.max_statements" value="20" />
<property name="hibernate.c3p0.acquire_increment" value="1" />
<property name="hibernate.c3p0.idle_test_period" value="30" />
<property name="hibernate.c3p0.timeout" value="35" />
<property name="hibernate.c3p0.checkoutTimeout" value="60000" />
<property name="hibernate.connection.release_mode" value="after_statement" />
<property name="debugUnreturnedConnectionStackTraces"
value="true" />
</properties>
</persistence-unit>
</persistence>
EDIT: I'm deploying the Application to a red hat server with Tomcat and MySQL Installed. I'm just wondering why Hibernate is opening too much connections to MySQL, with all entity managers closed no connection will remain open, but this is not the case. I'm guessing and correct me if I'm true that the connections are opened when I do something like this:
List<Sondage> allSondages = SondageDao.getAllSondages();
for (Sondage sondage : allSondages) {
List<Question> questions = sondage.getQuestions();
//code to display questions for example
}
Here when I use sondage.getQuestions(), does Hibernate open a connection to the database and doesn't close it after, am I missing something in the configuration file that close or return connection to pool when it's done with it. Thanks in advance for any help.
EDIT2 :
Since people are asking for versions, here they are :
JAVA jre 1.8.0_25
Apache Tomcat v7.0
hibernate-core-4.3.10
hibernate c3p0 4.3.10.final
hibernate-jpa 2.1
Thanks in advance
The mysql version is Mysql 5.6.17 if that can help...
EDIT 4: as people are getting confused about witch version of the code I posted is buggy, let me edit this so you'll know what happens exactly:
First I'll start by showing what's the buggy code, as you guys don't care about what's working:
#SuppressWarnings("unchecked")
public static List<Sondage> GetAllSondage() {
EntityManager em = PersistenceManager.getEntityManager();
List<Sondage> allSondages = new ArrayList<>();
try {
em.getTransaction().begin();
Query query = em.createQuery("SELECT s FROM Sondage s");
allSondages = query.getResultList();
em.getTransaction().commit();
} catch (Exception ex) {
if (em.getTransaction().isActive()) {
em.getTransaction().rollback();
}
allSondages = null;
} finally {
em.close();
}
return allSondages;
}
So this is basically what I did for all my dao functions, I know transaction is not needed here, since I saw questions pointing that transactions are important for connection to close. beside this , I getEntityManager from PersistenceManager class that has an EntityManagerFactory singleton Object, so getEntityManager creates an entityManager from the EntityManagerFactory singleton Object:=> code is better than 1000 word :
PesistenceManager.java:
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class PersistenceManager
{
private static EntityManagerFactory emf = null;
public static EntityManager getEntityManager()
{
return getEntityManagerFactory().createEntityManager();
}
public static EntityManagerFactory getEntityManagerFactory()
{
if(emf == null) {
emf = Persistence.createEntityManagerFactory("CAOE");
return emf;
}
else
return emf;
}
}
Yes this is cool and all good, but where's the problem?
The problem here is that this version opens the connections and never close them, the em.close() have no effect, it keeps the connection open to the database.
The noob fix:
What I did to fix this issue is create an EntityManagerFactory for every request, it mean that the dao looks something like this:
#SuppressWarnings("unchecked")
public static List<Sondage> GetAllSondage() {
//this is the method that return the EntityManagerFactory Singleton Object
EntityManagerFactory emf = PersistenceManager.getEntitManagerFactory();
EntityManager em = emf.createEntityManager();
List<Sondage> allSondages = new ArrayList<>();
try {
em.getTransaction().begin();
Query query = em.createQuery("SELECT s FROM Sondage s");
allSondages = query.getResultList();
em.getTransaction().commit();
} catch (Exception ex) {
if (em.getTransaction().isActive()) {
em.getTransaction().rollback();
}
allSondages = null;
} finally {
em.close();
emf.close();
}
return allSondages;
}
Now this is bad and I'll just keep it while I don't have answer for this question (it seems like forver :D ). So with this code basically All connections gets closed after hibernate doesn't need them. Thanks in advance for any efforts you put in this question :)
I think that Hibernate and C3P0 are behaving correctly here. In fact you should see that there are always at least three connections to the database open as per your C3P0 configuration.
When you execute a query Hibernate will use a connection from the pool and then return it when it is done. It will not close the connection. C3P0 might shrink the pool if the min size is exceeded and some of the connections time out.
In your final example you see the connections closed because you've shut down your entity manager factory and therefore your connection pool as well.
You call Persistence.createEntityManagerFactory("CAOE") every time. It is wrong. Each call createEntityManagerFactory creates new (indepented) connection pool. You should cache EntityManagerFactory object somewhere.
EDIT:
Also you should manually shutdown EntityManagerFactory. You can do it in #WebListener:
#WebListener
public class AppInit implements ServletContextListener {
public void contextInitialized(ServletContextEvent sce) {}
public void contextDestroyed(ServletContextEvent sce) {
PersistenceManager.closeEntityMangerFactory();
}
}
Otherwise each case of redeploy is source of leaked connections.
Can you try the following:
<property name="hibernate.connection.release_mode" value="after_transaction" />
<property name="hibernate.current_session_context_class" value="jta" />
instead of your current release mode?
Since sibnick has already answered the technical questions I'll try to address some points you seem to be confused about. So let me give you some ideas on how a hibernate application and connection-pool is intended to work:
Opening a database connection is an "expensive" operation. In order to avoid having to pay that cost for each and every request, you use a connection-pool. The pool opens a certain number of connections to the database in advance and when you need one you can borrow one of those existing connections. At the end of the transaction, these connections will not be closed but returned to the pool so they can be borrowed by the next request. Under heavy load, there might be too few connections to serve all requests so the pool might open additional connections that might be closed later on but not at once.
Creating an EntityManagerFactory is even more expensive (it will create caches, open a new connection-pool, etc.), so, by all means, avoid doing it for every request. Your response-times will become incredibly slow. Also creating too many EntityManagerFactories might exhaust your PermGen-space. So only create one EntityManagerFactory per application/persistence-context, create it at application startup (otherwise the first request will take too long) and close it upon application shutdown.
Bottom line: When using a connection-pool you should expect a certain number of DB-connections to remain open for the lifetime of your application. What must not happen is that the number increases with every request. If you insist on having the connections closed at the end of the session don't use a pool and be prepared to pay the price.
I ran into the same problem and was able to fix it by creating a singleton wrapper class for the EntityManagerFactory and creating the EntityManager where it's needed. You're having the connection overload problem because you're wrapping the EntityManager creation in the singleton class, which is wrong. The EntityManager provides the transaction scope (should not be re-used), the EntityManagerFactory provides the connections (should be re-used).
from: https://cloud.google.com/appengine/docs/java/datastore/jpa/overview
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public final class EMF {
private static final EntityManagerFactory emfInstance =
Persistence.createEntityManagerFactory("CAOE");
private EMF() {}
public static EntityManagerFactory get() {
return emfInstance;
}
}
and then use the factory instance to create an EntityManager for each request.
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import EMF;
// ...
EntityManager em = EMF.get().createEntityManager();
In my application property i have some datasource related parameter. Those are given bellow:
# DataSource Parameter
minPoolSize:5
maxPoolSize:100
maxIdleTime:5
maxStatements:1000
maxStatementsPerConnection:100
maxIdleTimeExcessConnections:10000
Here, **maxIdleTime** value is the main culprit. It takes value in second. Here maxIdleTime=5 means after 5 seconds if connection is not using then it will release the connection and it will take the minPoolSize:5 connection. Here maxPoolSize:100 means it will take maximum 100 connection at a time.
In my DataSource Configuration class i have a bean. Here is the example code:
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.core.env.Environment;
import org.springframework.beans.factory.annotation.Autowired;
#Autowired
private Environment env;
#Bean
public ComboPooledDataSource dataSource(){
ComboPooledDataSource dataSource = new ComboPooledDataSource();
try {
dataSource.setDriverClass(env.getProperty("db.driver"));
dataSource.setJdbcUrl(env.getProperty("db.url"));
dataSource.setUser(env.getProperty("db.username"));
dataSource.setPassword(env.getProperty("db.password"));
dataSource.setMinPoolSize(Integer.parseInt(env.getProperty("minPoolSize")));
dataSource.setMaxPoolSize(Integer.parseInt(env.getProperty("maxPoolSize")));
dataSource.setMaxIdleTime(Integer.parseInt(env.getProperty("maxIdleTime")));
dataSource.setMaxStatements(Integer.parseInt(env.getProperty("maxStatements")));
dataSource.setMaxStatementsPerConnection(Integer.parseInt(env.getProperty("maxStatementsPerConnection")));
dataSource.setMaxIdleTimeExcessConnections(10000);
} catch (PropertyVetoException e) {
e.printStackTrace();
}
return dataSource;
}
Hope this will solve your problem :)
Looks like issue is related to Hibernate bug. Please try to specify fetch strategy EAGER in your OneToMany annotations.
#OneToMany(mappedBy = "sondage", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
I am not so into Hibernate and I have the following problem trying to follow a tutorial. I am using Hibernate 4
So I have a client class named HelloWorldClient:
public class HelloWorldClient {
public static void main(String[] args) {
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
Message message = new Message( "Hello World with Hibernate & JPA Annotations" );
session.save(message);
session.getTransaction().commit();
session.close();
}
}
As you can see this class use the HibernateUtil to retrieve the Hibernate Session object, this one:
public class HibernateUtil {
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// Create the SessionFactory from hibernate.cfg.xml
Configuration configuration = new Configuration().configure("hibernate.cfg.xml");
return configuration.buildSessionFactory( new StandardServiceRegistryBuilder().applySettings( configuration.getProperties() ).build() );
}
catch (Throwable ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
and, as you can see, this class use the hibernate.cfg.xml configuration file that is putted into the root of my project, this one:
<?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>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/hello-world</property>
<property name="connection.username">root</property>
<property name="connection.password">myPswd</property>
<!--SQL dialect -->
<property name = dialect ">org.hibernate.dialect.MySQLDialect</property>
<!--Use Annotation - based mapping metadata -->
<mapping class="entity.Message" />
</session-factory>
</hibernate-configuration>
The problem is that when I perform this application I obtain this error message:
INFO: HHH000040: Configuration resource: hibernate.cfg.xml
Initial SessionFactory creation failed.org.hibernate.HibernateException: Could not parse configuration: hibernate.cfg.xml
Exception in thread "main" java.lang.ExceptionInInitializerError
at util.HibernateUtil.buildSessionFactory(HibernateUtil.java:21)
at util.HibernateUtil.<clinit>(HibernateUtil.java:10)
at client.HelloWorldClient.main(HelloWorldClient.java:13)
Caused by: org.hibernate.HibernateException: Could not parse configuration: hibernate.cfg.xml
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2165)
at org.hibernate.cfg.Configuration.configure(Configuration.java:2077)
at util.HibernateUtil.buildSessionFactory(HibernateUtil.java:15)
... 2 more
Caused by: org.dom4j.DocumentException: Error on line 2 of document : Non è consentita una destinazione di istruzione di elaborazione corrispondente a "[xX][mM][lL]". Nested exception: Non è consentita una destinazione di istruzione di elaborazione corrispondente a "[xX][mM][lL]".
at org.dom4j.io.SAXReader.read(SAXReader.java:482)
at org.hibernate.cfg.Configuration.doConfigure(Configuration.java:2157)
... 4 more
It seems that it can't read the hibernate.cfg.xml file or something like this.
Why? What am I missing ? How can I fix this issue ?
The mapping document is not a valid XML. Fix the line 19:
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
Other then that it shoud work.
There are 2 problems in your mapping file :
white line is not allowed on line 2: just remove the empty line. (this is the cause of your current error... very explicit by the way : "Error on line 2 of document")
quote is missing when you declare the dialect:
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
I'm new to Hibernate. Using Hibernate 3.0 from Eclipse indigo.
The topic is discussed here and the answer is not helpful, Hibernate: javax.naming.NoInitialContextException (Component Mapping via Annotations)
i.e. I tried removing name from session-factory and still getting the error.
Am I missing something? Can anyone help with this?
The error is as follows:
Feb 6, 2013 3:59:05 PM PatternsHome getSessionFactory
SEVERE: Could not locate SessionFactory in JNDI
javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial
at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:662)
at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:305)
at javax.naming.InitialContext.getURLOrDefaultInitCtx(InitialContext.java:342)
at javax.naming.InitialContext.lookup(InitialContext.java:409)
at PatternsHome.getSessionFactory(PatternsHome.java:26)
at PatternsHome.<init>(PatternsHome.java:21)
at OutputProcessing.saveData(OutputProcessing.java:47)
at OutputProcessing.FPFileOutputWriter(OutputProcessing.java:110)
at OrderPatternFileCreate.main(OrderPatternFileCreate.java:84)
Exception in thread "main" java.lang.IllegalStateException: Could not locate SessionFactory in JNDI
at PatternsHome.getSessionFactory(PatternsHome.java:29)
at PatternsHome.<init>(PatternsHome.java:21)
at OutputProcessing.saveData(OutputProcessing.java:47)
at OutputProcessing.FPFileOutputWriter(OutputProcessing.java:110)
at OrderPatternFileCreate.main(OrderPatternFileCreate.java:84)
Hibernate configuration file:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost/test</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
<property name="show sql">true</property>
<mapping resource="hibernate_db_mapping.hbm.xml"/>
</session-factory>
</hibernate-configuration>
The DAO file is generated by Hibernate and outline is given as:
public class PatternsHome {
private static final Log log = LogFactory.getLog(PatternsHome.class);
private final SessionFactory sessionFactory = getSessionFactory();
protected SessionFactory getSessionFactory() {
try {
return (SessionFactory) new InitialContext()
.lookup("SessionFactory");
} catch (Exception e) {
log.error("Could not locate SessionFactory in JNDI", e);
throw new IllegalStateException(
"Could not locate SessionFactory in JNDI");
}
}
.....
}
I'm not able to make this work on a stand alone. But I created a generic DAO with HibernateUtil and created sessionFactory using
sessionFactory = new Configuration().configure(new File("hibernate.cfg.xml")).buildSessionFactory();
and accessed DB in my DAO using
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = null;
try{
transaction = session.beginTransaction();
session.save(myData);
transaction.commit();
System.out.println("Data is Saved");
}catch(Exception e){
e.printStackTrace();
}finally{
session.close();
}
This worked.