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.
Related
How to do bootstrap initialize hibernate in a maven web project?
public class HibernateTest {
public static void main(String [] args) {
UserData us1 = new UserData();
us1.setfName("amit");
return "hello";
}
}
It cannot be done by the above code, where UserData is an entity.
First declare dependency for hibernate in pomm.xml:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.2.2.Final</version>
</dependency>
Next create configuration file 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>
<!-- Database connection settings -->
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost/UserDB</property>
<property name="connection.username">root</property>
<property name="connection.password"></property>
<property name="connection.pool_size">10</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create</property>
<!-- <property name="FOREIGN_KEY_CHECKS">0</property> -->
<!-- Mapping files -->
<mapping class="com.stackoverflow.model.Person" />
<mapping class="com.stackoverflow.model.Phone" />
</session-factory>
</hibernate-configuration>
If you have your entities you should list them in tag <mapping class="pathToEntity">.
Next in main method :
// A SessionFactory is set up once for an application!
final StandardServiceRegistry registry = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml")
.build();
try {
SessionFactory sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory();
} catch (Exception e) {
// The registry would be destroyed by the SessionFactory, but we had
// trouble building the SessionFactory
// so destroy it manually.
StandardServiceRegistryBuilder.destroy(registry);
System.out.println("Exception\n" + e);
}
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
Here you create Sessionfactory and get current Session object to be able to query database.
This is my hibernate.cfg:
<?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>
<!-- Connessione al database -->
<property name="connection.driver_class">
oracle.jdbc.driver.OracleDriver
</property>
<property name="connection.url">
jdbc:oracle:thin:#localhost:1521:xe
</property>
<!-- Credenziali -->
<property name="hibernate.connection.username">Test</property>
<property name="connection.password">Test</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">
org.hibernate.dialect.Oracle10gDialect</property>
<!-- DISABILITA AUTO COMMIT -->
<property name="hibernate.connection.autocommit">true</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">
org.hibernate.cache.NoCacheProvider</property>
<property name="show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">validate</property>
<!-- Entity -->
<mapping class= "it.test.Tbl1"></mapping>
<mapping class= "it.test.Tbl2"></mapping>
<mapping class= "it.test.Tbl3"></mapping>
<mapping class= "it.test.Tbl4"></mapping>
</session-factory>
</hibernate-configuration>
and this the hibernate util file:
When i try to execute a simple query, i got the exception as -> "query exception: table not mapped".
But if i change the hibernate util as follows,
public class HibernateUtil {
private static SessionFactory sessionFactory;
private static ServiceRegistry serviceRegistry;
private static SessionFactory createSessionFactory() {
Configuration configuration = new Configuration();
configuration.configure();
serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
return sessionFactory;
}
public static SessionFactory getSessionFactory() {
if (sessionFactory == null)
sessionFactory = createSessionFactory();
return sessionFactory;
}
}
the program works with success.
Why the session factory doesn't gets loaded through configuration file?
console log:
10:54:44.989 [main] DEBUG org.hibernate.hql.internal.ast.ErrorCounte-
throwQueryException() : no errors
10:54:45.130 [main] DEBUG
org.hibernate.hql.internal.antlr.HqlSqlBaseWalker - select << begin
[level=1, statement=select]
org.hibernate.hql.internal.ast.QuerySyntaxException: Tbl1 is not mapped
[from Tbl1 eat where eat.activityId = :id]
at
org.hibernate.hql.internal.ast.QuerySyntaxException.generateQueryException
(QuerySyntaxException.java:79)
at org.hibernate.QueryException.wrapWithQueryString
(QueryException.java:103)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile
(QueryTranslatorImpl.java:218)
i think that the problem is this :
17:14:47.130 [main] DEBUG org.hibernate.internal.SessionFactoryRegistry -
Registering SessionFactory: a0044811-5a9f-483a-8ede-b136c9781bb3
(<unnamed>)
17:14:47.130 [main] DEBUG org.hibernate.internal.SessionFactoryRegistry -
Not binding SessionFactory to JNDI, no JNDI name configured
17:14:47.364 [main] DEBUG org.hibernate.stat.internal.StatisticsInitiator
- Statistics initialized [enabled=false]
can you help me??
While using method addAnnotatedClass you incoded Tbl1, Tbl2, Tbl3 (2 times) as mentioned in the code which is just edited and removed. .addAnnotatedClass(Tbl1.class).addAnnotatedClass(Tbl2.class).addAnnotatedClass(Tbl3.class).addAnnotatedClass(Tbl3.class).
While using xml configuration you are saying that you have four annotated classes. As mentioned
<mapping class= "it.test.Tbl1"></mapping>
<mapping class= "it.test.Tbl2"></mapping>
<mapping class= "it.test.Tbl3"></mapping>
<mapping class= "it.test.Tbl4"></mapping>
Please check if mapping for Tbl4.class exists or not or try to modify last addAnnotatedClass(Tbl3.class) to .addAnnotatedClass(Tbl4.class).
Probably you are missing .hbm files in case of loading via configuration file(xml file). Try adding hbm files for each table.
i think you are missing hibernate.cfg.xml file. i mean if your cfg file name is different from hibernate.cfg.xml, then need to configure Configuration configuration = new Configuration(); configuration.configure("filename.cfg.xml"); .beacause hibernate by default takes hibernate.cfg.xml file without configuring in configuration.configure(); but if cfg file name is different then need to put it in configure(). your file need to place in src folder. if you place it in different place then need to pass it with correct path.
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
I'm fairly new at this and I'm stuck. If someone could help, that would be great.
My code right now uses inbuilt connection pool, how to change to Weblogic configured connection pool ? My code right now is as below:
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>
<!-- Database connection settings -->
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<property name="hibernate.connection.release_mode">after_transaction</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>
<!-- Configure BLOB/CLOB settings in hibernate -->
<property name="hibernate.connection.SetBigStringTryClob">true</property>
<property name="hibernate.jdbc.batch_size">0</property>
<!--Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<property name="cache.use_query_cache">false</property>
<property name="cache.use_minimal_puts">false</property>
<property name="max_fetch_depth">3</property>
<!-- Bind the getCurrentSession() method to the thread. -->
<property name="current_session_context_class">thread</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
</session-factory>
</hibernate-configuration>
Hibernate Session Class that has the getSession method:
public class HibernateSession {
public Session getSession() {
Configuration configuration = new AnnotationConfiguration();
configuration.setProperty("hibernate.connection.username", USERNAME);
configuration.setProperty("hibernate.connection.password", PASSWORD);
configuration.setProperty("hibernate.connection.url", DB_URL);
configuration.configure("hibernate.cfg.xml");
SessionFactory sessionFactory = configuration.buildSessionFactory();
Session session = sessionFactory.getCurrentSession();
return session;
}
}
Hibernate version: 4.2.11.Final
Weblogic: 10.3.6
You need to use JNDI lookup to look up the datasource you configured via WebLogic Admin console.
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 .