Exception in thread "main" java.lang.IllegalStateException: Session/EntityManager is closed - java

I want to run this very basic Hibernate code:
public static void main(String[] args) throws Exception
{
SessionFactory sessFact = HibernateUtil.getSessionFactory();
Session session = sessFact.getCurrentSession();
Transaction tr = session.beginTransaction();
SystemUsers myContact = new SystemUsers(3);
SystemUsers yourContact = new SystemUsers(4);
SystemUsers yourContsact = new SystemUsers(5);
SystemUsers yourContssssact = new SystemUsers(6);
SystemUsers yourContssssasssct = new SystemUsers(7);
// Saving to the database
session.save(myContact);
session.save(yourContact);
session.save(yourContsact);
session.save(yourContssssact);
session.save(yourContssssasssct);
session.flush();
tr.commit();
List<SystemUsers> contactList = session.createQuery("from SYSTEM_USERS").list();
for (SystemUsers contact : contactList)
{
System.out.println("Id: " + contact.getId());
}
System.out.println("Successfully inserted");
sessFact.close();
}
config file:
<hibernate-configuration>
<session-factory>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<property name="hibernate.dialect">org.hibernate.dialect.SQLiteDialect</property>
<property name="hibernate.connection.driver_class">org.sqlite.JDBC</property>
<property name="hibernate.connection.url">jdbc:sqlite:/C:/sqlite/test.sqlite</property>
<property name="hibernate.connection.username"></property>
<property name="hibernate.connection.password"></property>
<property name="hibernate.connection.release_mode">auto</property>
<property name="current_session_context_class">thread</property>
<property name="hibernate.connection.autoReconnect">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping class="com.web.models.SystemUsers"/>
</session-factory>
</hibernate-configuration>
I get error:
Exception in thread "main" java.lang.IllegalStateException: Session/EntityManager is closed
at org.hibernate.internal.AbstractSharedSessionContract.checkOpen(AbstractSharedSessionContract.java:337)
at org.hibernate.engine.spi.SharedSessionContractImplementor.checkOpen(SharedSessionContractImplementor.java:135)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:648)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:102)
I use latest Hibernate version. Can you give me some advice how I can fix this issue?
Probably I need to initialize different factory?

i think the problem is in
session.flush();//this will flush all the data in the session so for commmiting there wont be any data.
tr.commit();
try this.
tr.commit();
session.flush();

Related

HibernateException: Too many connections , using c3p0

I created hibernate application with using c3p0 for get access to my database,
This is 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>
<property name="show_sql">true</property>
<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/example</property>
<property name="hibernate.connection.username">******</property>
<property name="hibernate.c3p0.min_size">5</property>
<property name="hibernate.c3p0.max_size">20</property>
<property name="hibernate.c3p0.timeout">3000</property>
<property name="hibernate.c3p0.max_statements">50</property>
<property name="hibernate.c3p0.idle_test_period">300</property>
<property name="hibernate.c3p0.testConnectionOnCheckout">true</property>
<property name="hibernate.c3p0.preferredTestQuery">SELECT 1</property>
<property name="hibernate.connection.password">*******</property>
<mapping resource="beans/Reminder.hbm.xml"/>
<mapping resource="beans/StressType.hbm.xml"/>
<mapping resource="beans/Medication.hbm.xml"/>
<mapping resource="beans/ReportType.hbm.xml"/>
<mapping resource="beans/Comobility.hbm.xml"/>
<mapping resource="beans/Report.hbm.xml"/>
</session-factory>
</hibernate-configuration>
And this my HibernateUtil file . I named it as SessionFactoryBuilder.java,
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
public class SessionFactoryBuilder
{
private static SessionFactoryBuilder instance;
private static SessionFactory sessionFactory;
private SessionFactoryBuilder()
{
buildConfig();
System.out.println("hehehehe");
}
private static void buildConfig()
{
Configuration configuration = new Configuration().configure();
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties());
sessionFactory = configuration.buildSessionFactory(builder.build());
}
public static SessionFactoryBuilder getInstance()
{
if(instance == null)
{
instance = new SessionFactoryBuilder();
}
return instance;
}
public SessionFactory getSessionFactory()
{
return sessionFactory;
}
}
When I get access to my database using this SessionFactoryBuilder, I get following , "Too many connections" .
This is an example how I used this,
ReportTypeService reportTypeService = new ReportTypeService();
List<ReportType> list = reportTypeService.getAllReportTypes();
for(int i=0;i<list.size();i++){
out.print("Type - "+list.get(i).getType());
}
This is not coming at all the time .But when it appears the connection to the database is gone.
Have any ideas ?

Hibernate XML Mapping Exception

I'm trying to test the hibernate configuration of a project, but when I try to run the test it throws a MappinException saying that it does not known my entity, I checked the database and it is not creating the tables either, so my guess is that it is not reading the mapping files, but I checked that and the path is correct. And the package and class properties inside the mapping files is also correct (supposely).
Most of the questions I read are Annotation Focused, does anyone has an idea what's happening under the hood?
Thanks in advance
I have the following directory structure:
The hibernate.cfg.xml file it's like follows:
<hibernate-configuration>
<session-factory>
<!-- Hibernate Configuration -->
<property name="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="hibernate.connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="hibernate.hbm2ddl.auto">
update
</property>
<!-- Database Configuration -->
<property name="hibernate.connection.url">
jdbc:mysql://127.0.0.1:3306/library_management?createDatabaseIfNotExist=true
</property>
<property name="hibernate.connection.username">
root
</property>
<property name="hibernate.connection.password">
cetys
</property>
<!-- Class Mapping Files -->
<mapping resource="Hibernate.config/mapping/Book.hbm.xml"/>
<mapping resource="Hibernate.config/mapping/Classification.hbm.xml"/>
<mapping resource="Hibernate.config/mapping/Collection.hbm.xml"/>
<mapping resource="Hibernate.config/mapping/Loan.hbm.xml"/>
<mapping resource="Hibernate.config/mapping/NonExistentRegistry.hbm.xml"/>
</session-factory>
</hibernate-configuration>
The Loan mapping file is:
<hibernate-mapping package="com.cetys.cetyslibraryinventory.Core.DomainModels">
<class name="Loan" table="loan">
<meta attribute="class-description">
This class contains the basic information for a Loan
</meta>
<id name="id" column="loan_id" type="int"></id>
<many-to-one name="bookId" class="Book" unique="true"
column="book_id" cascade="all"/>
</class>
</hibernate-mapping>
The model:
package com.cetys.cetyslibraryinventory.Core.DomainModels;
//imports ommited
public class Loan implements Catalogable {
private int id;
private int book_id;
protected Loan () {
}
public Loan ( int id, int book_id ) {
this.id = id;
this.book_id = book_id;
}
// Getters and Setters Ommited
}
And when I try to run the following:
public class Program {
public static void main ( String[] args ) {
SessionFactory sessionFactory = null;
Session session = null;
Transaction tx = null;
try {
Configuration configuration = new Configuration();
configuration.configure( "hibernate.cfg.xml" );
ServiceRegistry serviceRegistry
= new StandardServiceRegistryBuilder().applySettings(
configuration.getProperties() ).build();
sessionFactory = configuration.
buildSessionFactory( serviceRegistry );
session = sessionFactory.openSession();
Loan ln = new Loan( 0, 0 );
tx = session.beginTransaction();
session.save( ln );
tx.commit();
} catch ( Exception e ) {
LOGGER.log( Level.SEVERE, e.getMessage(), e );
} finally {
if ( session != null ) {
session.close();
}
if ( sessionFactory != null ) {
sessionFactory.close();
}
}
}
}
Exception Error:
SEVERE: Unknown entity: com.cetys.cetyslibraryinventory.Core.DomainModels.Loan
org.hibernate.MappingException: Unknown entity: com.cetys.cetyslibraryinventory.Core.DomainModels.Loan
at org.hibernate.internal.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:776)
at org.hibernate.internal.SessionImpl.getEntityPersister(SessionImpl.java:1533)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:104)
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:682)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:674)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:669)
at com.cetys.cetyslibraryinventory.Program.main(Program.java:74)
Jun 08, 2016 10:04:41 AM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop
INFO: HHH10001008: Cleaning up connection pool [jdbc:mysql://127.0.0.1:3306/library_management?createDatabaseIfNotExist=true]

node to traverse cannot be null SQL SELECT

I have a problem with a query in HQL also my SQL base has some databases , so need to put together a query that take this table at the bottom, my sql base always starts in database 'database' and I must refer to the database webproduction then so I wrote my query :
#Entity
#Table(name="File")
#NamedQueries(
{
#NamedQuery(name="file.allList",
query = "use webproduction select * from File")
}
)
My Config:
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.SQLServerDialect</property>
<property name="hibernate.connection.driver_class">com.microsoft.sqlserver.jdbc.SQLServerDriver</property>
<property name="hibernate.connection.url">jdbc:sqlserver://10.11.1.05</property>
<property name="hibernate.connection.username">sa</property>
<property name="hibernate.connection.password"></property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<!-- <mapping class="entity.Sell" /> -->
<mapping class="entity.File" />
</session-factory>
</hibernate-configuration>
My Class hibernate:
public class HibernateUtil {
private static final SessionFactory sessionFactory;
static {
try {
sessionFactory = new AnnotationConfiguration().configure(
"config/sql_hibernate.cfg.xml").buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
My method:
public List<File> getFile() throws Exception{
session = HibernateUtil.getSessionFactory().openSession();
query = session.getNamedQuery("file.allList");
List<File> list1 = query.list();
session.close();
return list1;
}
For SQL server you would remove the 'use webproduction' from your named query and use:
jdbc:sqlserver://10.11.1.05;DatabaseName=webproduction
as your hibernate.connection.url
see http://www.java2s.com/Tutorial/Java/0340__Database/AListofJDBCDriversconnectionstringdrivername.htm

hibernate configuration exception

StackTrace:
Initial SessionFactory creation failed.org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
Exception in thread "main" java.lang.ExceptionInInitializerError
at org.hibernate.tutorial.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:20)
at org.hibernate.tutorial.util.HibernateUtil.<clinit>(HibernateUtil.java:9)
at org.hibernate.tutorial.EventManager.createAndStoreEvent(EventManager.java:23)
at org.hibernate.tutorial.EventManager.main(EventManager.java:16)
Caused by: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.determineDialect(DialectFactoryImpl.java:104)
at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.buildDialect(DialectFactoryImpl.java:71)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:209)
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:1887)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1845)
at org.hibernate.tutorial.util.HibernateUtil.buildSessionFactory(HibernateUtil.java:14)
... 3 more
my hibernate config:
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">org.hsqldb.jdbcDriver</property>
<property name="connection.url">jdbc:mysql://127.0.0.1:3306/hibernate</property>
<property name="connection.username">root</property>
<property name="connection.password"></property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create</property>
<mapping resource="org/hibernate/tutorial/domain/Event.hbm.xml" />
</session-factory>
</hibernate-configuration>
my code:
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(
new StandardServiceRegistryBuilder().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;
}
}
public class EventManager {
public static void main(String[] args) {
EventManager mgr = new EventManager();
if (args[0].equals("store")) {
mgr.createAndStoreEvent("My Event", new Date());
}
HibernateUtil.getSessionFactory().close();
}
private void createAndStoreEvent(String title, Date theDate) {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
Event theEvent = new Event();
theEvent.setTitle(title);
theEvent.setDate(theDate);
session.save(theEvent);
session.getTransaction().commit();
}
}
Your sessionfactory property names are incorrect. They should be
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.cache.use_second_level_cache">false</property>
Note the property name is hibernate.

Hibernate query.executeUpdate() not working properly

Hibernate query.executeUpdate() is not working..
Here is the code for updating
public static void expDue(){
Session session=HibernateUtil.getSessionFactory().openSession();
java.util.Date utilDate=new java.util.Date();
java.sql.Date sqldate=new java.sql.Date(utilDate.getTime());
Format formatter = new SimpleDateFormat("yyyy-MM-dd");
String a= formatter.format(sqldate);
boolean b=false;
if(b==false){
Query query = session.createQuery(" update Issue set dueStatus = 'true' where returnDate='"+a+"'");
int result = query.executeUpdate();
System.out.println(query.executeUpdate()+"Rows affected: " + result);
b=true;
}
Here, printing the result shows correct value, but no change in database.
And hibernate code
<hibernate-configuration>
<session-factory>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.HSQLDialect</property>
<!-- Database connection settings -->
<property name="hibernate.connection.driver_class">org.hsqldb.jdbcDriver</property>
<property name="hibernate.connection.url">jdbc:hsqldb:db/hsql/library;shutdown=true</property>
<property name="hibernate.connection.username">sa</property>
<property name="hibernate.connection.password">sa</property>
<property name="hibernate.dialect">org.hibernate.dialect.HSQLDialect</property>
<!-- JDBC connection pool (use the built-in one) -->
<property name="connection.pool_size">1</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property
name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!-- disable batching so HSQLDB will propagate errors correctly. -->
<property name="jdbc.batch_size">0</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- List all the mapping documents we're using -->
<mapping class="com.habitz.librarymanagement.domain.Admin" />
<mapping class="com.librarymanagement.domain.Book" />
<mapping class="com.librarymanagement.domain.Category" />
<mapping class="com.librarymanagement.domain.Group" />
<mapping class="com.librarymanagement.domain.Issue" />
<mapping class="com.librarymanagement.domain.Member" />
</session-factory>
</hibernate-configuration>
In console printing the result shows correct values. But the database shows no change...
If you know about this please share answers here...
UPDATE
Transaction tx = null;
tx = session.beginTransaction();
Query query = session
.createQuery(" update Issue set dueStatus = 'true' where returnDate='"
+ a + "'");
int result = query.executeUpdate();
System.out.println(query.executeUpdate() + "Rows affected: "
+ result);
tx.commit();
Transaction tx = null;
tx = session.beginTransaction();
boolean b = false;
if (b == false) {
Query query = session
.createQuery(" update Issue set dueStatus = 'true' where returnDate='"
+ a + "'");
query.executeUpdate();
tx.commit();
You have forgotten to execute update before committing transaction.

Categories

Resources