Error while Connecting postgres using Hibernate. - NullPointerException - java

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

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>

Connect to a database dynamically in hibernate

So I have multiple pluggable databases (PDBs) and I want to connect to any one of them dynamically using Hibernate. How do I achieve such functionality?
To connect to PDB1 (and likewise for other PDBs), I have:
protected void setupPdb1() {
final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
.configure("hibernate-1.cfg.xml") // configures settings from hibernate.cfg.xml
.build();
try {
sessionFactory1 = new MetadataSources(registry).buildMetadata().buildSessionFactory();
} catch (Exception ex) {
StandardServiceRegistryBuilder.destroy(registry);
throw new RuntimeException(ex);
}
}
My hibernate config file corresponding to PDB1 is as follows:
<?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="connection.url">jdbc:oracle:thin:#//localhost:1521/pdb1.oradev.oraclecorp.com</property>
<property name="connection.username">test</property>
<property name="connection.password">password12</property>
<property name="connection.driver_class">oracle.jdbc.OracleDriver</property>
<property name="dialect">org.hibernate.dialect.Oracle12cDialect</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hbm2ddl.auto">create</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<property name="current_session_context_class">thread</property>
<mapping class="net.codejava.hibernate.Book" />
</session-factory>
</hibernate-configuration>
The issue with this approach is there is one config file for each PDB. How do I dynamically select the PDB to connect to using Hibernate?
it depends on your strategy, what is the trigger to switch database ?

Hibernate doesn't create table and throw exception

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.

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.

MySQLNonTransientConnectionException: No operations allowed after connection closed

I am hoping someone can help me. My database connection keeps getting closed and will not reopen so I am having to restart my application every few hours.
I have seen other answers here and have tried implementing them but they dont seem to make any difference. My JDBC url has autoReconnect=true and I am using hibernate with a c3p0 connection pool.
Any help would be great!
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="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/devenv38?autoReconnect=true</property>
<property name="hibernate.connection.username">devenv38</property>
<property name="hibernate.connection.password">devenv38</property>
<property name="hibernate.connection.autoReconnect">true</property>
<property name="hibernate.connection.autoReconnectForPools">true</property>
<property name="connection.is-connection-validation-required">true</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Use the C3P0 connection pool provider -->
<property name="connection.provider_class">org.hibernate.connection.C3P0ConnectionProvider</property>
<property name="c3p0.acquire_increment">5</property>
<property name="c3p0.max_size">500</property>
<property name="c3p0.max_statements">0</property>
<property name="c3p0.idleConnectionTestPeriod">120</property>
<property name="c3p0.initialPoolSize">25</property>
<property name="c3p0.min_size">25</property>
<property name="c3p0.numHelperThreads">15</property>
<property name="c3p0.timeout">0</property> <!-- seconds -->
<property name="hibernate.show_sql">false</property>
<property name="hibernate.format_sql">false</property>
<property name="hibernate.hbm2ddl.auto">create</property>
<!-- resources -->
<mapping class="entities.Story" />
<mapping class="entities.User" />
</session-factory>
Database Connection Class
public class DatabaseConnection
{
static SessionFactory sf;
private DatabaseConnection()
{
Configuration configuration = new Configuration();
configuration.configure();
ServiceRegistry sr = new ServiceRegistryBuilder().applySettings(
configuration.getProperties()).buildServiceRegistry();
sf = configuration.buildSessionFactory(sr);
}
public static Session getSession()
{
if (sf == null)
{
new DatabaseConnection();
}
return sf.openSession();
}
}
Example usage
Session session = DatabaseConnection.getSession();
Transaction txn = session.beginTransaction();
User user = new User();
user.setUsername("JUNIT USER 1");
user.setEmail("test#test.com");
user.setPassword("Test Password");
session.save(user);
txn.commit();

Categories

Resources