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
Related
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)
Mvn clean and Mvn install are successful without warnings and errors.The files hibernate.cfg.xml and App.java are:
The error from console during initialization is:
log4j:WARN No appenders could be found for logger (org.jboss.logging).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Exception in thread "main" org.hibernate.HibernateException: Connection cannot be null when 'hibernate.dialect' not set
at org.hibernate.service.jdbc.dialect.internal.DialectFactoryImpl.determineDialect(DialectFactoryImpl.java:97)
at org.hibernate.service.jdbc.dialect.internal.DialectFactoryImpl.buildDialect(DialectFactoryImpl.java:67)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:170)
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 com.icdab.www.icdab_first.App.init(App.java:33)
at com.icdab.www.icdab_first.App.main(App.java:76)
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">oracle.jdbc.OracleDriver</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:#localhost:1521:ORCL</property>
<property name="hibernate.connection.username">system</property>
<property name="hibernate.connection.password">password</property>
<property name="hiberante.dialect">org.hibernate.dialect.Oracle10gDialect</property>
<property name="show_sql">true</property>
<mapping class="com.icdab.www.icdab_first.CompundKey" />
<mapping class="com.icdab.www.icdab_first.Customer" />
<mapping class="com.icdab.www.icdab_first.Employee" />
<mapping class="com.icdab.www.icdab_first.EventPlan" />
<mapping class="com.icdab.www.icdab_first.EventPlanLine" />
<mapping class="com.icdab.www.icdab_first.EventRequest" />
<mapping class="com.icdab.www.icdab_first.Facility" />
<mapping class="com.icdab.www.icdab_first.Location" />
<mapping class="com.icdab.www.icdab_first.ResourceTbl" />
</session-factory>
</hibernate-configuration>
App.java:
package com.icdab.www.icdab_first;
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
/**
* Hello world!
*
*/
public class App
{
private SessionFactory factory;
private void init(){
System.out.println("in init");
Configuration config = new Configuration().configure("hibernate.cfg.xml")
/*.addAnnotatedClass(CompundKey.class)
.addAnnotatedClass(Customer.class)
.addAnnotatedClass(Employee.class)
.addAnnotatedClass(EventPlan.class)
.addAnnotatedClass(EventPlanLine.class)
.addAnnotatedClass(EventRequest.class)
.addAnnotatedClass(Facility.class)
.addAnnotatedClass(Location.class)
.addAnnotatedClass(ResourceTbl.class) */;
// learn why did you use the annotatedclass and configuration.
ServiceRegistry registry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
factory=config.buildSessionFactory(registry);
}
#SuppressWarnings("deprecation")
private void persistAnnotatedLists(){
Session session = factory.getCurrentSession();
session.beginTransaction();
Customer customer = new Customer();
customer.setAddress("address123");
customer.setCity("lansing");
customer.setContact("1632 ne ave");
customer.setCustname("john");
customer.setCustno("1234");
customer.setInternal("internal");
customer.setPhone(122345679);
customer.setState("OR");
customer.setZip(97654);
List<EventRequest> ers = new ArrayList<EventRequest>();
ers.add(new EventRequest(123,new Date(92,5,1),new Date(91,5,1),new Date(93,5,1),"av",123,456,124));
ers.add(new EventRequest(1234,new Date(92,5,2),new Date(91,5,2),new Date(93,5,2),"av",124,457,125));
customer.setEventrequests(ers);
session.save(customer);
session.getTransaction().commit();
System.out.println("done persist");
}
private void retrieveList(){
Session session = factory.getCurrentSession();
session.beginTransaction();
List list = session.createQuery("from com.icdab.www.icdab_first.Customer").list();
for (Object object : list) {
System.out.println("** List items: "+object);
}
session.getTransaction().commit();
System.out.println("Done retrieve");
}
public static void main (String[] args){
App app = new App();
app.init();
app.persistAnnotatedLists();
app.retrieveList();
}
}
And the project structure is:
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.
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());