Hibernate can not save object - java

I am doing the introductory tutorial on Hibernate from PluralSight.
For my database, I am using MYSQL.
In my main method, I am creating an object and I am trying to save it.
However, I get the following error:
Exception in thread "main" org.hibernate.MappingException: Unknown entity: com.simpleprogrammer.User
at org.hibernate.internal.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:776)
at org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1447)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:100)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:192)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:177)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:678)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:670)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:665)
at com.simpleprogrammer.Program.main(Program.java:16)
My main method is:
public static void main(String[] args) {
System.out.println("Hello World!");
Session session = HibernateUtilities.getSessionFactory().openSession();
session.beginTransaction();
User user = new User();
user.setName("Joe");
user.setGoal(250);
session.save(user);
session.getTransaction().commit();
session.close();
HibernateUtilities.getSessionFactory().close();
}
The error appears on the line with session.save(user);
My Utilities class:
package com.simpleprogrammer;
import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
public class HibernateUtilities {
private static SessionFactory sessionFactory;
private static StandardServiceRegistryBuilder ssrb;
static
{
try
{
Configuration configuration = new Configuration().configure("hibernate.cfg.xml");
ssrb = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
sessionFactory = configuration.buildSessionFactory(ssrb.build());
}
catch(HibernateException exception)
{
System.out.println("Problem creating session factory");
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
My 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 name="">
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">appuser</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3307</property>
<property name="hibernate.connection.username">appuser</property>
<property name="hibernate.default_schema">protein_tracker</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<mapping resource="com/simpleprogrammer/User.hbm.xml"/>
</session-factory
</hibernate-configuration>
I am sorry to post all this code, but I'm not sure which part is relevant.
I suspect that my error is caused by the database connection, but I'm not sure how to check that.

I had a syntactic error on the line:
</session-factory
This was in hibernate.cfg.xml

This is my first contribution to stackoverflow.com. And I was facing similar error,but now I resolved it by this given solution. So, I am writing this Answer.
You have to change your utility file like this:
static
{
try
{
Configuration configuration = new Configuration().configure("hibernate.cfg.xml");
//ssrb = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
sessionFactory = configuration.buildSessionFactory();
}
catch(HibernateException exception)
{
System.out.println("Problem creating session factory");
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
ssrb variable declaration and definition must be removed.
put configuration.buildSessionFactory(); instead of configuration.buildSessionFactory(ssrb.build());

Related

using hibernate and jpa with springboot

I have a spring boot project. I put in my resource folder hibernate.cfg.xml file.
this is my hibernate.cfg.xml 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.bytecode.use_reflection_optimizer">false</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">***</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/exportbatch?serverTimezone=UTC</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
</session-factory>
I have a hibernateUtil class used to instantiate a hibernate session.
public class HibernateUtil
{
private static final SessionFactory sessionFactory = buildSessionFactory();
private static SessionFactory buildSessionFactory()
{
try
{
// Create the SessionFactory from hibernate.cfg.xml
// return new Configuration().configure().buildSessionFactory();
return new AnnotationConfiguration().configure().buildSessionFactory();
}
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;
}
public static void shutdown()
{
// Close caches and connection pools
getSessionFactory().close();
}
}
In my application controller I have an endpoint in which I am requesting my mysql database.
#RequestMapping("/getbuildinginfo/{buildingid}")
public void getbuildinginfo(String buildingid)
Session session = null;
session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
String query = "select * from exportbatch.exportbatch";
SQLQuery sqlQuery = session.createSQLQuery(query);
List<Object[]> rows = sqlQuery.list();
HibernateUtil.shutdown();
This works fine the first time I run the project, but if I call the endpoint a second time, I am getting this exception:
org.hibernate.service.UnknownServiceException: Unknown service requested [org.hibernate.engine.jdbc.connections.spi.ConnectionProvider]
Could someone help me with this ? why it works the first time? Is it a spring boot context problem? if yes how could I resolve it ?

Cant connect to postgreSQL with Hibernate(Eclipse)

What i do wrong? After running main class i have view in console like in current screenshot below and the console continues to work and nothing happens.
hibernate.cfg.xml:
<?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>
<property name="connection.driver_class">org.postgresql.Driver</property>
<property name="connection.url">jdbc:postgresql://localhost:5432/Gillie_PL</property>
<property name="connection.username">postgres</property>
<property name="connection.password">postgres</property>
<property name="dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
</session-factory>
</hibernate-configuration>
hibernateUtil.class:
package hibernateConn;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static SessionFactory sessionFactory = null;
static {
Configuration cfg =
new Configuration().configure("/hibernateConn/hibernate.cfg.xml");
StandardServiceRegistryBuilder builder =
new StandardServiceRegistryBuilder()
.applySettings(cfg.getProperties());
sessionFactory = cfg.buildSessionFactory(builder.build());
}
public static SessionFactory getSessionFactory(){
return sessionFactory;
}
}
Main.Class:
package hibernateConn;
import org.hibernate.SessionFactory;
public class Main {
public static void main(String[] args) {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
}
}
After I run Main.class I have in console:
And that's all. Nothing more, the program continues to work and nothing happens, as if recursion occurs ... Maybe I did not correctly specify the settings in xml?
 
I rewrote the HibernateUtil.class :
static {
try{
sessionFactory = new Configuration().configure("/hibernateConn/hibernate.cfg.xml").buildSessionFactory();
}catch(Throwable ex){
System.err.println("++++Initial SessionFactory creation failed.++++: " + ex);
ex.printStackTrace();
}
}
public static SessionFactory getSessionFactory(){
return sessionFactory;
}
and it all worked. The question can be closed.

Connecting to SQL Server 2008 R2 with hibernate

I am trying to connect to a Microsoft SQL 2008 server through hibernate.it's not getting connected, following is hibernate.cfg.xml
<!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.microsoft.sqlserver.jdbc.SQLServerDriver</property>
<property name="hibernate.connection.password">1234</property>
<property name="hibernate.connection.url">jdbc:sqlserver://localhost:1433;databaseName=TEST</property>
<property name="hibernate.connection.username">username</property>
<property name="hibernate.default_schema">dbo</property>
<property name="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</property>
<property name="hibernate.show_sql">true</property>
</session-factory>
</hibernate-configuration>
`
And here is the code I use to try and establish an connection and do a query :
package com.simpleprogrammer;
import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
public class HibernateUtilities {
private static SessionFactory sessionFactory;
private static ServiceRegistry serviceRegistry;
static {
try {
Configuration config = new Configuration().configure().addResource("hibernate.cfg.xml");
serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
sessionFactory = config.buildSessionFactory(serviceRegistry);
}catch(HibernateException he){
System.out.println("Problem Caught ! " + he );
}
}
public static SessionFactory getSessionFactory(){
return sessionFactory;
}
}
`
The Main method :
package com.simpleprogrammer;
import org.hibernate.Session;
public class Program {
public static void main(String[] args) {
System.out.println("Hello World!") ;
Session session = HibernateUtilities.getSessionFactory().openSession();
session.close();
}
}
jar file was missing jboss-transaction-api_1.2_spec-1.0.0, Simply add it in project and it start working

Seems like Hibernate exceeds connection limit

Can anybody help me solve this situation?
I have a Tomcat and simple JSF Application: https://github.com/gooamoko/jsfbilling/.
When I run application on Tomcat, it runs normally, but after several requests (for example 10 quick refresh page) raise the exception can't open connection.
I think, it's normal, but where is the mistake?
In the configuration file hibernate.cfg.xml
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<property name="connection.driver_class">org.postgresql.Driver</property>
<property name="connection.url">jdbc:postgresql://localhost:5432/netstat</property>
<property name="connection.username">netstat</property>
<property name="connection.password">netstat</property>
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!-- configuration pool via c3p0 -->
<property name="c3p0.min_size">5</property>
<property name="c3p0.max_size">100</property>
<property name="c3p0.max_statements">200</property>
<property name="c3p0.timeout">600</property> <!-- seconds -->
<property name="transaction.factory_class">org.hibernate.transaction.JDBCTransactionFactory</property>
<property name="current_session_context_class">thread</property>
<property name="hibernate.show_sql">false</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<!-- Mapping classes -->
<mapping class="ru.gooamoko.model.Group" />
<mapping class="ru.gooamoko.model.Host" />
<mapping class="ru.gooamoko.model.Traffic" />
<mapping class="ru.gooamoko.model.DailyTraffic" />
</session-factory>
</hibernate-configuration>
or in the Java classess
package ru.gooamoko.dao;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class HibernateProvider {
private static SessionFactory factory;
private static ServiceRegistry registry;
public static SessionFactory getSessionFactory() {
Configuration configuration = new Configuration();
configuration.configure();
registry = new StandardServiceRegistryBuilder().applySettings(
configuration.getProperties()).build();
factory = configuration.buildSessionFactory(registry);
return factory;
}
}
package ru.gooamoko.dao;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
public class GenericDao {
private SessionFactory factory;
protected Session session;
protected void begin() {
session = factory.getCurrentSession();
session.beginTransaction();
}
protected void commit() {
if (session.isOpen()) {
session.getTransaction().commit();
}
}
protected void rollback() {
if (session.isOpen()) {
session.getTransaction().rollback();
}
}
public GenericDao() {
this.factory = HibernateProvider.getSessionFactory();
}
}
In the tomcat log I see this
27-Aug-2014 15:06:24.559 WARNING [C3P0PooledConnectionPoolManager[identityToken->1hge12w9467h4hm1tfa5tj|3b40a97d]-HelperThread-#2] com.mchange.v2.resourcepool.BasicResourcePool.forceKillAcquires Having failed to acquire a resource, com.mchange.v2.resourcepool.BasicResourcePool#4df5a3a4 is interrupting all Threads waiting on a resource to check out. Will try again in response to new client requests.
27-Aug-2014 15:06:24.563 WARNING [C3P0PooledConnectionPoolManager[identityToken->1hge12w9467h4hm1tfa5tj|3b40a97d]-HelperThread-#2] com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask.run com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask#628977a2 -- Acquisition Attempt Failed!!! Clearing pending acquires. While trying to acquire a needed new resource, we failed to succeed more than the maximum number of allowed acquisition attempts (30). Last acquisition attempt exception:
org.postgresql.util.PSQLException: ?????: ?????????? ????? ??????????? ??????????????? ??? ??????????? ????????????????? (?? ??? ??????????)
at org.postgresql.core.v3.ConnectionFactoryImpl.readStartupMessages(ConnectionFactoryImpl.java:572)
at org.postgresql.core.v3.ConnectionFactoryImpl.openConnectionImpl(ConnectionFactoryImpl.java:177)
at org.postgresql.core.ConnectionFactory.openConnection(ConnectionFactory.java:64)
at org.postgresql.jdbc2.AbstractJdbc2Connection.<init>(AbstractJdbc2Connection.java:136)
at org.postgresql.jdbc3.AbstractJdbc3Connection.<init>(AbstractJdbc3Connection.java:29)
at org.postgresql.jdbc3g.AbstractJdbc3gConnection.<init>(AbstractJdbc3gConnection.java:21)
at org.postgresql.jdbc4.AbstractJdbc4Connection.<init>(AbstractJdbc4Connection.java:31)
at org.postgresql.jdbc4.Jdbc4Connection.<init>(Jdbc4Connection.java:24)
at org.postgresql.Driver.makeConnection(Driver.java:393)
at org.postgresql.Driver.connect(Driver.java:267)
at com.mchange.v2.c3p0.DriverManagerDataSource.getConnection(DriverManagerDataSource.java:146)
at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:195)
at com.mchange.v2.c3p0.WrapperConnectionPoolDataSource.getPooledConnection(WrapperConnectionPoolDataSource.java:184)
at com.mchange.v2.c3p0.impl.C3P0PooledConnectionPool$1PooledConnectionResourcePoolManager.acquireResource(C3P0PooledConnectionPool.java:200)
at com.mchange.v2.resourcepool.BasicResourcePool.doAcquire(BasicResourcePool.java:1086)
at com.mchange.v2.resourcepool.BasicResourcePool.doAcquireAndDecrementPendingAcquiresWithinLockOnSuccess(BasicResourcePool.java:1073)
at com.mchange.v2.resourcepool.BasicResourcePool.access$800(BasicResourcePool.java:44)
at com.mchange.v2.resourcepool.BasicResourcePool$ScatteredAcquireTask.run(BasicResourcePool.java:1810)
at com.mchange.v2.async.ThreadPoolAsynchronousRunner$PoolThread.run(ThreadPoolAsynchronousRunner.java:648)
How and where should I correct close open connections?
Thanks for wasting your time for me.
I've read Hibernate documentation and found example of HibernateUtil class.
After comparing with my HibernateProvider I found, that seems like in my HibernateProvider Factory was build every call of getSessionFactory(). New version of HibernateProvider is
package ru.gooamoko.dao;
import org.hibernate.HibernateException;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
public class HibernateProvider {
private static final SessionFactory factory = buildFactory();
public static SessionFactory getSessionFactory() {
return factory;
}
private static SessionFactory buildFactory() {
try {
Configuration configuration = new Configuration();
configuration.configure();
ServiceRegistry registry = new StandardServiceRegistryBuilder().applySettings(
configuration.getProperties()).build();
return configuration.buildSessionFactory(registry);
} catch (HibernateException ex) {
// Make sure you log the exception, as it might be swallowed
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
}
So, now query
SELECT COUNT(*) FROm pg_stat_activity;
returns 6, one of which is psql client. Even after minute of re-requesting page. I think, it's a progress.
The only one thing remains - is to make possible for Hibernate work with postgresql-jdbc.jat in Tomcat /lib folder and no use jar in WEB-INF/lib. I read that placing postgresql-jdbc.jar into WEB-INF/lib may cause memory leaks.
P.S. I also read, that Hibernate should automaticaly close connections when session commits or rollback and I don't need to close connections explicitly.
Thanks for your suggestions, cos I always need someone who keep my eyes open.

Hibernate: javax.naming.NoInitialContextException (using DAO generated by Hibernate)

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.

Categories

Resources