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.
Related
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 ?
I want to encrypt the password in configuration file using Jasypt. For this I use a library based in jasypt because seems that there are some problems with it using hibernate 4.3.
The password is stored in an environment variable named PSS_RES and is encripted with PBEWithMD5AndTripleDes algorithm
The configuration file:
<?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="connection.provider_class">net.lizalab.util.jasypt.h4.ext.connectionprovider.EncryptedDriverManagerConnectionProviderImpl</property>
<property name="connection.encryptor_registered_name">configurationHibernateEncryptor</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/DB</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">ENC(RcnYVTTYFbrVB346Lp4txlbj2oI0TMglCtQ3GNvopFU=)</property>
<property name="hibernate.connection.pool_size">1</property>
<property name="hibernate.current_session_context_class">thread</property>
</session-factory>
hibernateutil
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.EnvironmentStringPBEConfig;
import org.jasypt.hibernate4.encryptor.HibernatePBEEncryptorRegistry;
public class HibernateUtil {
private static final SessionFactory sessionFactory =buildSessionFactory();
private static SessionFactory buildSessionFactory() {
try {
// TODO Auto-generated method stub
EnvironmentStringPBEConfig envConfig = new EnvironmentStringPBEConfig();
envConfig.setPasswordEnvName("PSS_RES");
System.out.println(envConfig.getPasswordEnvName());
System.out.println(envConfig.getPassword());
StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
HibernatePBEEncryptorRegistry registry = HibernatePBEEncryptorRegistry.getInstance();
encryptor.setAlgorithm("PBEWithMD5AndTripleDES");
encryptor.setConfig(envConfig);
registry.registerPBEStringEncryptor("configurationHibernateEncryptor", encryptor);
Configuration configuration=new Configuration();
configuration.configure("hibernate.cfg.xml");
ServiceRegistry serviceRegistry=new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
SessionFactory sessionFactory= configuration.buildSessionFactory(serviceRegistry);
return sessionFactory;
} catch (Throwable e) {
// TODO: handle exception
System.err.println("error en la conexion "+e );
throw new ExceptionInInitializerError();
}
}
public static SessionFactory getSessionfactory() {
return sessionFactory;
}
}
This is the exception that I get when I start the application.
[main] INFO net.lizalab.util.jasypt.h4.ext.connectionprovider.EncryptedDriverManagerConnectionProviderImpl - configure : Using Encryptor registered with name: configurationHibernateEncryptor
[main] INFO net.lizalab.util.jasypt.h4.ext.connectionprovider.EncryptedDriverManagerConnectionProviderImpl - configure : Found registered Encryptor, checking connection properties ..
[main] INFO net.lizalab.util.jasypt.h4.ext.connectionprovider.EncryptedDriverManagerConnectionProviderImpl - decryptIfEncrypted : Decrypting value for encrypted property: hibernate.connection.password
error en la conexion org.jasypt.exceptions.EncryptionOperationNotPossibleException
Exception in thread "main" java.lang.ExceptionInInitializerError
at com.Eu.controladores.HibernateUtil.buildSessionFactory(HibernateUtil.java:37)
at com.Eu.controladores.HibernateUtil.<clinit>(HibernateUtil.java:11)
at com.Eu.dao.PersonaDao.listaPersonas(PersonaDao.java:47)
at com.Eu.paneles.PanelFiltros.RellenarTablaPersonas(PanelFiltros.java:382)
at com.Eu.paneles.PanelFiltros.<init>(PanelFiltros.java:84)
at com.Eu.formularios.FrmPrincipal.<init>(FrmPrincipal.java:126)
at com.Eu.controladores.Application.main(Application.java:11)
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 ?
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());
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