hibernate configuration exception - java

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.

Related

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

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

SB - How to provide a hibernate.cfg.xml file to a LocalSessionFactoryBuilder?

Introduction
I am trying to convert a working XML configured spring batch job to javaconfig and I am running into some issues with setting up the session. I want to use a hibernate.cfg.xml file to configure the connection (and I also use it elsewhere, so I do need to keep it).
Given
The working xml configuration looks as following:
<!-- Standard Spring Hibernate Reader -->
<bean id="hibernateItemReader" class="org.springframework.batch.item.database.HibernateCursorItemReader" scope="step">
<property name="sessionFactory" ref="sessionFactory" />
<property name="queryString" value="#{jobExecutionContext[HQL]}" />
<property name="useStatelessSession" value="false"/>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" lazy-init="true">
<property name="configLocation" value="classpath:hibernate.cfg.xml"/>
<property name="cacheableMappingLocations" value="classpath*:META-INF/mapping/*.hbm.xml"/>
</bean>
And the hibernate.cfg.xml looks as following:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE hibernate-configuration SYSTEM "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Connection to database -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/SAKILA</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">****</property>
<!-- Conversion from HQL to SQL in log -->
<property name="show_sql">false</property>
<property name="format_sql">true</property>
<property name="use_sql_comments">true</property>
<!-- Session and pool settings -->
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.c3p0.min_size">5</property>
<property name="hibernate.c3p0.max_size">20</property>
<property name="hibernate.c3p0.timeout">1800</property>
<property name="hibernate.c3p0.idle_test_period">1000</property>
<property name="hibernate.c3p0.max_statements">50</property>
</session-factory>
</hibernate-configuration>
The following java config..
#Bean
#Lazy(true)
public SessionFactory sessionFactory(){
LocalSessionFactoryBean session = new LocalSessionFactoryBean();
session.setConfigLocation(hibernateConfig());
session.setCacheableMappingLocations(mappings());
return session.getObject();
}
#Bean
#StepScope
public HibernateCursorItemReader reader(#Value("#{jobExecutionContext[HQL]}") String HQLQuery){
HibernateCursorItemReader reader = new HibernateCursorItemReader<>();
reader.setSessionFactory(sessionFactory());
reader.setQueryString(HQLQuery);
reader.setUseStatelessSession(false);
return reader;
}
Issue
reader.setSessionFactory(sessionFactory());
Throws:
Caused by: java.lang.IllegalStateException: A SessionFactory must be provided
After some research, I think I need to use the LocalSessionFactoryBuilder instead of the LocalSessionFactoryBean.
#Autowired
#Bean
public SessionFactory sessionFactory2(){
LocalSessionFactoryBuilder sessionBuilder = new LocalSessionFactoryBuilder(dataSource());
// ?? sessionBuilder.setConfigLocation(); ??
sessionBuilder.addDirectory(new File(url.toURI()));
}
However, I do not want to provide a datasource because I have all the datasource connection information configured in the hibernate.cfg.xml file.
The accepted answer on How to make hibernate.cfg.xml to a datasource bean suggest to keep the hibernate.cfg.xml file and add Spring configuration.
How do I add hibernate.cfg.xml file to the LocalSessionFactoryBuilder?
I figured it out. I do not want to use the LocalSessionFactoryBuilder at all. In my program I have the following class:
public class HibernateUtil {
private static final SessionFactory SESSIONFACTORY = buildSessionFactory();
private static final String HIBERNATE_CONFIGURATION_LOCATION = "hibernate.cfg.xml";
private static final String MAPPINGS_LOCATION = "src/main/resources/mappings";
private static ServiceRegistry serviceRegistry;
private static SessionFactory buildSessionFactory() {
try {
Configuration configuration = new Configuration();
configuration.configure(HIBERNATE_CONFIGURATION_LOCATION).addDirectory(new File(MAPPINGS_LOCATION));
serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
return sessionFactory;
} catch (Exception e) {
System.err.println("Initial SessionFactory creation failed." + e);
throw new ExceptionInInitializerError(e);
}
}
public static SessionFactory getSessionFactory(){
return SESSIONFACTORY;
}
public static void shutdown(){
getSessionFactory().close();
}
}
And calling reader.setSessionFactory(HibernateUtil.getSessionFactory()); did the trick for me!

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.cfg.xml not found (eclipse)

I started using Hibernate today and tested a simple example but I'm getting the error: hibernate.cfg.xml not found.
I putted the hibernate.cfg.xml file in the src folder and here is its content:
<?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>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/test</property>
<property name="connection.username">test</property>
<property name="connection.password">test</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">update</property>
<mapping resource="com/mycompany/model/Product.hbm.xml"/>
</session-factory>
</hibernate-configuration>
And I putted the HibernateUtil.java file under util folder (src/util) and here is its content
package util;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
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("hibernate.cgf.xml").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();
}
}
I also have the Jars added to the build path.
My class Test.java :
import ...
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
ProductDao pd = new ProductDao();
try {
Product p = new Product("PC", 1000L);
pd.add(p);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The add method :
public void add(Product p) {
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
session.beginTransaction();
session.save(p);
tx.commit();
}
Thanks in advance
If using maven try putting it in
/src/main/resources
If using simple eclipse project (without maven), put it in project root directory (not in the src)
Also you misspelled the name of the file in the source
return new Configuration().configure("hibernate.cgf.xml").buildSessionFactory();
it must be
hibernate.cfg.xml
If its a Maven project just add cfg.xml file in /src/main/resources in eclips

org.hibernate.HibernateException: two open sessions

I am newbie in hibernate technology and I am struggling with the following exception:
org.hibernate.HibernateException: Illegal attempt to associate a
collection with two open sessions
I get this when I try to make a new line into my DB.
My setting/code:
<?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>
<!-- Paramètres de connexion à la base de données -->
<!-- <property name="connection.driver_class">com.mysql.jdbc.Driver</property> -->
<!-- <property name="connection.url">jdbc:mysql://localhost:3306/bh</property> -->
<!-- <property name="connection.username">root</property> -->
<!-- <property name="connection.password"></property> -->
<!-- <property name="dialect">org.hibernate.dialect.MySQLDialect</property> -->
<property name="connection.driver_class">org.postgresql.Driver</property>
<property name="connection.url">jdbc:postgresql://localhost:5432/projetForum</property>
<property name="connection.username">postgres</property>
<property name="connection.password">esct</property>
<property name="dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<!-- Comportement pour la conservation des tables -->
<property name="hbm2ddl.auto">update</property>
<!-- Activation : affichage en console, commentées et formatées -->
<property name="show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<property name="use_sql_comments">true</property>
<!-- Fichiers à mapper -->
<mapping class="com.forum.beans.Utilisateur" />
<mapping class="com.forum.beans.Topic" />
<mapping class="com.forum.beans.Post" />
</session-factory>
</hibernate-configuration>
A session holder:
package com.forum.utils;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
public class HibernateUtils {
private static final SessionFactory sessionFactory;
// Crée une unique instance de la SessionFactory à partir de
// hibernate.cfg.xml
static {
try {
sessionFactory = new AnnotationConfiguration().configure()
.buildSessionFactory();
} catch (HibernateException ex) {
throw new RuntimeException("Problème de configuration : "
+ ex.getMessage(), ex);
}
}
// Renvoie une session Hibernate
public static Session getSession() throws HibernateException {
return sessionFactory.openSession();
}
}
Code that causes the error :
Transaction tx = null;
try {
s = HibernateUtils.getSession();
tx = s.beginTransaction();
s.persist(u);
tx.commit();
} catch (Exception e) {
if (tx != null)
tx.rollback();
System.out.println(e);
}
Welcome to Hibernate, what I can see from your code:
Instead of using
openSession()
try
getSession()
Similar issue solved at URL

Categories

Resources