Hibernate doesn't create table and throw exception - java

I have a problem with my hibernate project.
When I try to start simple method the Hibernate throw exception:
Exception in thread "main" org.hibernate.exception.SQLGrammarException: could not execute statement
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:63)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
at ...
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'botsender.users' doesn't exist
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:400)
at com.mysql.jdbc.Util.getInstance(Util.java:383)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:980)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3847)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3783)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2447)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2594)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2545)
at ...
I've tried change my xml config but It didn't help.
Here's config:
<?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.id.new_generator_mappings">false</property>
<property name="hibernate.hbm2ddl">create</property>
<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">admin12345</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/botSender</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<mapping class="com.bot.entity.User"></mapping>
<mapping class="com.bot.entity.Role"></mapping>
<mapping class="com.bot.entity.Chanel"></mapping>
<mapping class="com.bot.entity.MessageToChanel"></mapping>
<mapping class="com.bot.entity.MessageToUser"></mapping>
<mapping class="com.bot.entity.Status"></mapping>
</session-factory>
And simple test-method is:
public class App
{
public static void main( String[] args )
{
SessionFactory sessionFactory = HibernateAnnotationUtil.getSessionFactory();
Session session = sessionFactory.openSession();
System.out.println("Session created");
Transaction tx = session.beginTransaction();
User user = new User();
user.setFirthName("Igor");
user.setLastName("Petrenko");
user.setNickName("6ruceVVayne");
user.setToken("somethink");
user.setRole(Role.ADMINISTRATOR);
session.save(user);
tx.commit();
System.out.println("User ID=" + user.getId());
}
}
I also tried to change "create" to "update". And change " org.hibernate.dialect.MySQLDialect" to "MySQL5InnoDBDialect". But I still get stuck on the same exception.

Related

Getting HibernateException : The internal connection pool has reached its maximum size and no connection is currently available

I am getting org.hibernate.HibernateException: The internal connection pool has reached its maximum size and no connection is currently available! I believe the problem is due to incorrect session handling. Can anyone suggest the correct way?
This is my Service class.
#Service
public class DataService {
#Autowired
private SessionFactory sessionFactory;
public User createUser(User newUser) {
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(newUser);
session.getTransaction().commit();
session.close();
return newUser;
}
public User findUser(UUID userId) {
Session session = sessionFactory.openSession();
session.beginTransaction();
try {
return session.get(User.class, userId);
} finally {
session.close();
}
}
}
Below is my Hibernate Configuration. I think my configuration is correct. My Session instantiation and closing in-service class is wrong.
<!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">com.mysql.cj.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/rest_database?useSSL=false</property>
<property name="connection.username">admin</property>
<property name="connection.password">admin</property>
<property name="connection.pool_size">1</property>
<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name="show_sql">true</property>
<property name="current_session_context_class">thread</property>
<property name="hbm2ddl.auto">update</property>
<property name="hibernate.dbcp.initialSize">5</property>
<property name="hibernate.dbcp.maxTotal">20</property>
<property name="hibernate.dbcp.maxIdle">10</property>
<property name="hibernate.dbcp.minIdle">5</property>
<property name="hibernate.dbcp.maxWaitMillis">-1</property>
<mapping class="com.in.models.User" />
</session-factory>
</hibernate-configuration>
In my hibernate.cfg.xml connection pool size was 1.
<property name="connection.pool_size">1</property>
My db query browser(DBeaver) was already connected to my database, hence when I was trying to save the object, it was giving the hibernate exception - no connection available.
When I increased the connection pool size to 2 in hibernate.cfg.xml. Exception got resolved, as database allowed 2 connections.
<property name="connection.pool_size">2</property>

Exception : buildSessionFactory - in Hibernate App

I'm working on an E-Commerce App using Hibernate Framework. But I'm facing a problem during the execution. The test program throws an Exception :
Exception in thread "main" java.lang.ExceptionInInitializerError
at HibernateUtil.buildSessionFactory(HibernateUtil.java:19)
at HibernateUtil.<clinit>(HibernateUtil.java:9)
at Test.main(Test.java:10)
Caused by: java.lang.NullPointerException
at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processFkSecondPassesInOrder(InFlightMetadataCollectorImpl.java:1708)
at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processSecondPasses(InFlightMetadataCollectorImpl.java:1617)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:278)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.build(MetadataBuildingProcess.java:83)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:418)
at org.hibernate.boot.internal.MetadataBuilderImpl.build(MetadataBuilderImpl.java:87)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:692)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:724)
at HibernateUtil.buildSessionFactory(HibernateUtil.java:14)
... 2 more
My HibernateUtil :
import org.hibernate.*;
import org.hibernate.cfg.*;
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();
}
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;
}
}
Hibernate.cfg.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- local connection properties -->
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/ecom</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password"></property>
<property name="hibernate.connection.pool_size">10</property>
<!-- dialect for MySQL -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.show_sql">true</property>
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<property name="cache.use_query_cache">false</property>
<mapping class="Metier.Category"/>
<mapping class="Metier.Customer"/>
<mapping class="Metier.CustomerOrder"/>
<mapping class="Metier.orderedProduct"/>
<mapping class="Metier.orderedProductID"/>
<mapping class="Metier.Product"/>
</session-factory>
</hibernate-configuration>
Please tell me what is the source of the Exception.
Cheers.

Use Two hibernate.cfg.xml files in a Application

how to specify two hibernate configurations for a one application,
i have created two hibernate files and mention them in SessionFactory.util
hibernateMaster.cfg.xml file is working fine..
but when shut down Master database server and try to use application with hibernateMaster.cfg.xml and retrieve data it gives me "null"
but if i restart the Application it is working fine with hibernateMaster.cfg.xml file
here are my hibernate files
hibernateMaster.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>
<!-- Database Connection Settings -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://192.168.232.143:3306/cps</property>
<property name="hibernate.connection.username">gaiz</property>
<property name="hibernate.connection.password">mysql</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.current_session_context_class">thread</property>
<mapping resource="lib/driver/mappings/Patient.hbm.xml"/>
<mapping resource="lib/driver/mappings/Allergy.hbm.xml"/>
<mapping resource="lib/driver/mappings/Hospital.hbm.xml"/>
<mapping resource="lib/driver/mappings/StatStaff.hbm.xml"/>
<mapping resource="lib/driver/mappings/StatWard.hbm.xml"/>
<mapping resource="lib/driver/mappings/User.hbm.xml"/>
<mapping resource="lib/driver/mappings/UserRole.hbm.xml"/>
<mapping resource="lib/driver/mappings/UserLog.hbm.xml"/>
</session-factory>
</hibernate-configuration>
hibernateSlave.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>
<!-- Database Connection Settings -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://192.168.232.144:3306/cps</property>
<property name="hibernate.connection.username">gaiz2</property>
<property name="hibernate.connection.password">mysql</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.current_session_context_class">thread</property>
<mapping resource="lib/driver/mappings/Patient.hbm.xml"/>
<mapping resource="lib/driver/mappings/Allergy.hbm.xml"/>
<mapping resource="lib/driver/mappings/Hospital.hbm.xml"/>
<mapping resource="lib/driver/mappings/StatStaff.hbm.xml"/>
<mapping resource="lib/driver/mappings/StatWard.hbm.xml"/>
<mapping resource="lib/driver/mappings/User.hbm.xml"/>
<mapping resource="lib/driver/mappings/UserRole.hbm.xml"/>
<mapping resource="lib/driver/mappings/UserLog.hbm.xml"/>
</session-factory>
</hibernate-configuration>
SessionFactoryUtil.java
package lib;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import core.resources.statisticalResource;
public class SessionFactoryUtil {
//This class creates a session factory object by looking at the hibernate configuration (hibernate.cfg.xml)
private static SessionFactory sesFactory;
private static ServiceRegistry sesRegistry;
static Configuration cfg;
static{
try{
cfg= new Configuration().configure("lib/hibernateMaster.cfg.xml");
sesRegistry = new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry();
sesFactory=cfg.buildSessionFactory(sesRegistry);
try{
Session session = SessionFactoryUtil.getSessionFactory().openSession();
Transaction tx = session.beginTransaction();
System.out.println("Connected to Master Database Server");
}
catch(Throwable ex){
cfg= new Configuration().configure("lib/hibernateSlave.cfg.xml");
sesRegistry = new ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServiceRegistry();
sesFactory=cfg.buildSessionFactory(sesRegistry);
System.out.println("Connected to Slave Database Server");
}
}
catch(Throwable ex){
System.out.println("Master & Slave Database Error.");
System.err.println("Initial SessionFactory Creation Failed"+ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sesFactory;
}
}
i dnt knw whether i have done something wrong on have done something wrong in SessionFactoryUtil.java .
Your problem is that you initialize your factory in a static way.
static{
...
}
That code is executed only once, when you start your application. That way when you shut down your master server hibernate stills asking for it.
You should initialize both configurations and use the main, if exists, or secondary in other case. You can do this in the getSessionFactory() method, that is executed each time the method is call, but not in an static initializer.

Hibernate does not see data inserted from external application

I am using Hibernate as an ORM for a server daemon.
This code returns no items if the table associated is empty at run time but has an item added outside of hibernate.
public static List<QueueItem> queue()
{
SessionFactory factory = HibernateUtil.getSessionFactory();
Session session = factory.openSession();
session.flush();
session.clear();
#SuppressWarnings("unchecked")
List<QueueItem> topList = session.createQuery("FROM QueueItem i ORDER BY i.id asc").setMaxResults(3).list();
session.close();
return topList;
}
Here is the hibernate config
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration SYSTEM
"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://10.10.1.4/lanjukebox_test</property>
<property name="hibernate.connection.username">ussqldev</property>
<property name="hibernate.connection.password">ussqldev</property>
<property name="hibernate.jdbc.batch_size">25</property>
<property name="connection.pool_size">1</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="current_session_context_class">thread</property>
<property name="hibernate.cache.use_second_level_cache">false</property>
<property name="show_sql">false</property>
<property name="hbm2ddl.auto">validate</property>
<!-- List of XML mapping files -->
<mapping resource="usagisoft/lan/jukebox/domain/entities/Song.hbm.xml"/>
<mapping resource="usagisoft/lan/jukebox/domain/entities/Id3.hbm.xml"/>
<mapping resource="usagisoft/lan/jukebox/domain/entities/QueueItem.hbm.xml"/>
<mapping resource="usagisoft/lan/jukebox/domain/entities/Vote.hbm.xml"/>
<mapping resource="usagisoft/lan/jukebox/domain/entities/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
If I create an object and persist it from within the application it works fine, If there is already data in the table and I insert the data it finds the other objects, the issue arises as soon as the table is empty during run time.
This is a big issue because another application handles the inserting of data for these objects.
I am using hibernate 4.2.7.Final with Java 1.7(jdk1.7.0_45) in eclipse.
You can resolve this problem since
hibernate.cfg.xml
adding this tag:
<property name="hibernate.connection.autocommit">true</property>

Error while Connecting postgres using Hibernate. - NullPointerException

Am getting below exception while connecting to postgresql,
INFO: HHH000046: Connection properties: {user=postgres, password=****}
Exception in thread "main" java.lang.NullPointerException
at org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl.getConnection(DriverManagerConnectionProviderImpl.java:214)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl$ConnectionProviderJdbcConnectionAccess.obtainConnection(JdbcServicesImpl.java:242)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:117)
at org.hibernate.service.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:75)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:159)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:131)
at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1797)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1755)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1840)
at org.sri.hibernate.main.MainClass.main(MainClass.java:16)
Here is my hibernate.cfg.xml file.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration SYSTEM "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
<property name="hibernate.connection.url">"jdbc:postgresql://localhost:5432/TestDataBase</property>
<property name="hibernate.connection.username">postgres</property>
<property name="hibernate.connection.password">1234</property>
<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hibernate.hbm2ddl.auto">create-drop</property>
<mapping class="org.sri.hibernate.beans.UserDetails"/>
</session-factory>
</hibernate-configuration>
My connection URL, user Name and password are correct. Am trying to connect by using,
public static void main(String args[])
{
SessionFactory sf=new Configuration().configure().buildSessionFactory();
Session ss=sf.openSession();
Transaction tran=null;
UserDetails det= new UserDetails();
det.setDateOfBirth(new Date());
det.setUserName("SomeName");
try
{
tran=ss.beginTransaction();
ss.save(det);
tran.commit();
ss.close();
}catch(Exception e)
{
System.out.println(e.getMessage());
}
}
I use the same code to connect Oracle DB ( after changing the properties in xml ) it works fine, am I missing something specific to postgres ? Please help

Categories

Resources