i am trying Hibernate 4 in Netbeans 8, the problem is that after the the committed is done the application still running.
Here is the code
public class TestHibernateAnotation {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Users user = new Users();
Users user2 = new Users();
user2.setUser_name("Djalil");
user.setUser_name("Daniel");
Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
session.save(user);
session.save(user2);
session.getTransaction().commit();
session.close();
System.out.print("End of code");
}
}
My Hibernate 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.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
<property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/SalesTest</property>
<property name="hibernate.connection.username">postgres</property>
<property name="hibernate.connection.password">admin</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.hbm2ddl.auto">create</property>
<mapping class="testhibernateanotation.NewClass"/>
<mapping class="testhibernateanotation.Users"/>
any Idea about this issue
thank you,
You need to explicitly destroy the service registry after session.close();. This seems to be a bug in newer hibernate versions. So basically your code that cleans up at the end should look like :
sessionFactory.close();
StandardServiceRegistryBuilder.destroy(sessionFactory.getSessionFactoryOptions().getServiceRegistry());
Plug: I had posted an example here - including this issue.
I found the solution (in an other post),
it would be adding this to your config files:
<property name="hibernate.c3p0.acquire_increment">1</property>
<property name="hibernate.c3p0.idle_test_period">100</property>
<property name="hibernate.c3p0.max_size">10</property>
<property name="hibernate.c3p0.max_statements">10</property>
<property name="hibernate.c3p0.min_size">10</property>
<property name="hibernate.c3p0.timeout">100</property>
They said that it is bug in hibernate 4
you will have to close the SessionFactory object [ HibernateUtil.getSessionFactory().openSession() ]
The SessionFactory is a heavyweight object; it is usually created during application start up and kept for later use.The SessionFactory is a thread safe object and used by all the threads of an application.
We can create one SessionFactory implementation per database in any application. If your application is referring to multiple databases, then you need to create one SessionFactory per database.
its how hibernate SessionFactory was designed.
https://docs.jboss.org/hibernate/orm/3.5/api/org/hibernate/SessionFactory.html
Related
In my web app I use the session-per-request pattern. I have a connection pool and open sessions in a Filter using SessionFactory.openSession() and then Session.close().
In the same app, for a complex process, I want to use session-per-conversation. I tried to open a second Session with SessionFactory.openSession(), but subsequently calling Session.disconnect() does nothing.
How can I manually connect/disconnect sessions? This is my Hibernate configuration file:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
<property name="hibernate.connection.url">jdbc:postgresql://localhost/.....</property>
<property name="hibernate.connection.username">...</property>
<property name="hibernate.connection.password">...</property>
<property name="hibernate.c3p0.min_size">1</property>
<property name="hibernate.c3p0.max_size">20</property>
<property name="hibernate.c3p0.timeout">300</property>
<property name="hibernate.c3p0.test_connection_on_checkout">true</property>
<property name="hibernate.cache.use_second_level_cache">true</property>
</session-factory>
</hibernate-configuration>
The Java code:
longSession = mySessionFactory.openSession();
System.out.println(((SessionImplementor) longSession).isConnected());
longSession.disconnect();
System.out.println(((SessionImplementor) longSession).isConnected());
This outputs true twice...
I think this is related to this note in Hibernate Documents:
Note that disconnect() called on a session where the connection was
retrieved by Hibernate through its configured ConnectionProvider has
no effect, provided ConnectionReleaseMode.ON_CLOSE is not in effect
Also note to this in Documentation for session-per-conversation:
Committing a database transaction disconnects a session from the JDBC
connection and returns the connection to the pool
This say you need only to commit transactions to return the connection to the pool, except for the last transaction in your conversation:
// foo is an instance loaded earlier by the old session
Transaction t = session.beginTransaction(); // Obtain a new JDBC connection, start transaction
foo.setProperty("bar");
session.flush(); // Only for last transaction in conversation
t.commit(); // Also return JDBC connection
session.close(); // Only for last transaction in conversation
I am new bee to Hibernate and trying out things.
One thing that seems to amuse all is how to connect to different databases?
I have two questions here:
If in the same web app I need to connect to MySQL and Oracle, how do I do it?
I am using MySQL and have two databases test1 and test2, how to connect and retrieve data?
I have read in a blog that we can create different configuration files and do it.
I tried it but was not sucessful.
Here's what I tried:
SessionFactory sf = (SessionFactory) new Configuration().configure(path);
Where path is the path of the config file.
Is this the right way?
Using annotation mappings as an example:
Configuration cfg1 = new AnnotationConfiguration();
cfg1.configure("/hibernate-oracle.cfg.xml");
cfg1.addAnnotatedClass(SomeClass.class); // mapped classes
cfg1.addAnnotatedClass(SomeOtherClass.class);
SessionFactory sf1 = cfg1.buildSessionFactory();
Configuration cfg2 = new AnnotationConfiguration();
cfg2.configure("/hibernate-mysql.cfg.xml");
cfg2.addAnnotatedClass(SomeClass.class); // could be the same or different than above
cfg2.addAnnotatedClass(SomeOtherClass.class);
SessionFactory sf2 = cfg2.buildSessionFactory();
Then use sf1 and sf2 to get the sessions for each database. For mapping files, you just use cfg.addClass instead of addAnnotatedClass. Put the cfg.xml files in the root package in this case. Those will have the Oracle or MySQL dialect and connection information.
It cannot be done using one hibernate configuration file. You need to have two configurations files for it.
To configure mysql database
hibernate-mysql.cfg.xml
To configure oracle database
hibernate-oracle.cfg.xml
In Details, mysql configuration file be like this.
<?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">PASSWORD</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/UR_DB_NAME</property>
<property name="hibernate.connection.username">USERNAME</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<mapping class="domain.EmployeeMysql"></mapping>
</session-factory>
</hibernate-configuration>
In Details, oracle configuration file be like this.
<?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">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.password">PASSWORD</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:UR DB NAME</property>
<property name="hibernate.connection.username">USERNAME</property>
<property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
<property name="show_sql">true</property>
<mapping class="domain.EmployeeOracleSql"></mapping>
</session-factory>
</hibernate-configuration>
And code should be like this.
mysql configuration
private static SessionFactory sessionAnnotationFactory;
sessionAnnotationFactory = new Configuration().configure("hibernate-mysql.cfg.xml").buildSessionFactory();
Session session = sessionAnnotationFactory.openSession();
oracle sql configuration
sessionAnnotationFactory = new Configuration().configure("hibernate-oracle.cfg.xml").buildSessionFactory();
Session session = sessionAnnotationFactory.openSession()
Ideally you should move to Distributed transaction type of system[using Java Transaction Analyzer org.hibernate.transaction.JTATransactionFactory] in this case. If you are running in JBoss App Server, you can do it by using "Distributed Transaction Managers". You can learn more about it here.
You can also use a catalog with the value of the other database
#Table(name = "foo", schema = "bar", catalog = "OtherDatabase")
You can also Add mapping class in configuration.xml file
Note : this is for annotations and for resources use resources keyword instead of class
<mapping class="packageName.classNmae1"/>
<mapping class="packageName.classNmae2"/>
You can connect two databases test1 and test2, retrieve data with only one hibernate with some tricks:
hibernate SQLQuery: just add database name with the table "select * from test1.table1", "select * from test2.table2"
hibernate persistence: using the key schema in the hibernate mapping xml
<class name="Table1Class" table="table1" schema="test1">
<class name="Table2Class" table="table2" schema="test2">
Hi i trying to write my first Hibernate program,
its giving an error while instantiating the session factory.
I'm using hibernate 5.0.4 & java 8 & eclipse Luna SR1 (4.4.1) & oracle 11g.
MainClass is:
public class MainMethod {
public static void main(String[] args) {
SampleClass s = new SampleClass();
s.setId(1);
s.setValue("Value_1");
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(s);
session.getTransaction().commit();
}
}
the hibernate.cfg.xml is
<?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.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:#localhost:1521:mndb11g</property>
<property name="hibernate.connection.username">temp_p</property>
<property name="hibernate.connection.password">temp_p</property>
<property name="connection.pool_size">1</property>
<property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
<property name="hibernate.default_schema">temp_p</property>
<property name="hbm2ddl.auto">create</property>
<property name="show_sql">true</property>
<mapping class="com.h.SampleClass.SampleClass"/>
</session-factory>
</hibernate-configuration>
Its giving an exception at
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
The exception stack trace is
Exception in thread "main" java.lang.NullPointerException
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl$AggregatedClassLoader.getResources(ClassLoaderServiceImpl.java:173)
at java.util.ServiceLoader$LazyIterator.hasNextService(ServiceLoader.java:348)
at java.util.ServiceLoader$LazyIterator.hasNext(ServiceLoader.java:393)
at java.util.ServiceLoader$1.hasNext(ServiceLoader.java:474)
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.loadJavaServices(ClassLoaderServiceImpl.java:324)
at org.hibernate.integrator.internal.IntegratorServiceImpl.<init>(IntegratorServiceImpl.java:40)
at org.hibernate.boot.registry.BootstrapServiceRegistryBuilder.build(BootstrapServiceRegistryBuilder.java:213)
at org.hibernate.cfg.Configuration.<init>(Configuration.java:119)
at com.h.MainMethod.main(MainMethod.java:19)
Can anyone please help to solve this.
Thanks in advance.
This could happen due to several reasons.
May be the Entity cannot be found. In your hibernate.cfg.xml file the entity is mentioned as com.h.SampleClass.SampleClass
Please double check the class name and the package name.
Make sure that the hibernate libraries are added as user libraries. Not system libraries. More info
Hope this helps.
It sounds like hibernate.cfg.xml is not on your classpath when the code runs. If you are using maven put it in src/main/resources.
I am struggling at the moment to find out why I get this error messages.
I'm using hibernate for the first time so that I could have configured something wrong.
IMO it could be one of this 3 problems.
My hibernate.cfg.xml file is at the wrong "place" but I didn't change the classpath and the hibernet file is inside the src folder.
I get a warning at the line where I create a new SessionFactory SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
There are 2 types which i can get back from buildSessionFactory()
SessionFactory
Configuration
Of course I took SessionFactory but maybe I overlook something.
package hibernate;
import java.util.Date;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import persistencelayer.*;
public class HibernateTest {
public static void main(String[] args) {
TestUserDetails user2 = new TestUserDetails();
user2.setUserId(1);
user2.setUserName("First User");
user2.setAddress("First User's address");
user2.setJoinedDate(new Date());
user2.setDescription("Description of the user goes here");
try {
//SessionFactory wird erzeugt, mit der Konfiguration von Hibernate
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
// session.save(user);
session.save(user2);
session.getTransaction().commit();
} catch (Exception e) {
System.out.println("Fehler beim erstellen der SessionFactory");
}
}
}
`
It could also be that i configured my hibernate.cfg.xml file wrong. I am deleting the username, password and host, for safety reasons.
I am trying to find the solution since google but it is simply not working.
I am using Oracle as DB btw.
Suggestions would be appreciated. Thank you in advance and sorry for the long post :).
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Database connection settings -->
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:#host:port:ssid:</property>
<property name="hibernate.connection.username">name</property>
<property name="hibernate.connection.password">password</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="hibernate.connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property>
<!-- Disable the second-level cache -->
<property name="hibernate.cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="hibernate.show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hibernate.hbm2ddl.auto">create</property>
<!-- Names the annotated entity class -->
<mapping class="persistencelayer.Project"/>
<mapping class="persistencelayer.User"/>
<!-- <mapping class="persistencelayer.Employer"/>
<mapping class="persistencelayer.IndividualTest"/>
<mapping class="persistencelayer.ObjectType"/>
<mapping class="persistencelayer.TestChamber"/>
<mapping class="persistencelayer.TestMethod"/>
<mapping class="persistencelayer.TestUserDetails"/> -->
</session-factory>
i have found the problem it is inside the hibernate.cfg.xml file.
i copied it from the offical hibernate 4.3.9 files.
This section is wrong.
<property name="hibernate.connection.password" />password</property>
there should not be a "/" on the left side where password is meant to be put in.
I read almost all thread about How configure hibernate datasource but I can't find help. I mean in hibernate.cfg.xml element <property name="hibernate.connection.datasource"> ? </property> i know i have to set up with jndi. i try to google it but all articles are based on developing with jbossas, ejb, tomcat, weblogic and their jndi. But i need jndi of java SE. Correct me please if i am wrong.
I am new to Hibernate so I am using NetBeans, SE project with Hibernate 3.2.5 jars. (I am studying Hibernate from book Beginning Hibernate 2nd edition, apress and source code derive on the book...)
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>
<property name="hibernate.connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="hibernate.connection.url">
jdbc:mysql://127.0.0.1:3306/asd
</property>
<property name="hibernate.connection.username">root</property>
<!-- nastaveni dialektu -->
<property name="hibernate.dialect">
org.hibernate.dialect.MySQLInnoDBDialect
</property>
<!-- jndi nastaveni -->
<property name="hibernate.connection.datasource">
java:hibernate/SessionFactory
</property>
<property name="hibernate.connection.username">root</property>
<property name="cache.provider_class">
org.hibernate.cache.NoCacheProvider
</property>
<property name="hibernate.jndi.class">javax.naming.InitialContext</property>
</session-factory>
</hibernate-configuration>
And I have only one class FirstHibernate:
package firsthibernate;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
public class FirstHibernate {
private static SessionFactory session = null;
private static Session s = null;
public static void main(String[] args) {
try {
session = new AnnotationConfiguration().configure().buildSessionFactory();
s = session.openSession();
s.beginTransaction();
// List l = s.createQuery("from query").list();
s.getTransaction().commit();
} catch (Exception ex) {
if (s.getTransaction() != null) {
//s.getTransaction().rollback();
}
System.out.println(ex.toString());
} finally {
s.close();
}
}
}
I obtain this message:
SEVERE: Could not obtain initial context javax.naming.NoInitialContextException: Cannot instantiate class: javax.naming.InitialContext [Root exception is java.lang.ClassCastException: javax.naming.InitialContext cannot be cast to javax.naming.spi.InitialContextFactory]
You don't need that complex setup for SE.
Hope this link helps
Hibernate Sample App
Check Hibernate Quick Start
From what i perceive you are configuring hibernate in a non managed environment . In Non managed environment hibernate handles the connections via simple connection pools .Its not possible to have a data source configured in the non managed mode . You can have a look at http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/transactions.html#transactions-demarcation-nonmanaged for further details .