I am running simple hibernate program ,but it is giving me error mention in the title
My hibernate.cfg.xml is as follows:-
<?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/myhiber</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">rishabh123#</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="hibernate.show_sql">true</property>
<mapping class="com.tut.ProjectwithMaven.Student"/>
</session-factory>
</hibernate-configuration>
My code is as follows:-
public class App
{
public static void main( String[] args )throws Exception
{
System.out.println( "Hello World!" );
// Configuration cfg=new Configuration();
try {
new Configuration().configure("hibernate.cfg.xml");
} catch (HibernateException e) {
// TODO Auto-generated catch block
try
{
throw (Throwable)e;
}
catch(Throwable ex)
{
ex.printStackTrace();
}
}
System.out.println("AAge");
SessionFactory factory=new Configuration().buildSessionFactory();
Student st=new Student();
st.setId(101);
st.setName("Rishabh");
st.setCity("Bangalore");
Session session=factory.openSession();
session.beginTransaction();
session.save(st);
session.getTransaction().commit();
session.close();
Please help in resolving this issue, i have checked pom.xml ,it seems to be right,but still giving same error again and again
Well, you are not using this configuration file. See the line you posted:
SessionFactory factory=new Configuration().buildSessionFactory();
It should be
SessionFactory factory = new Configuration().configure("hibernate.cfg.xml")
.buildSessionFactory();
Related
I am learning Hibernate and I dont understand why am I getting this error launching program:
java.lang.IllegalStateException: Cannot get a connection as the driver manager is not properly initialized at org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl.getConnection(DriverManagerConnectionProviderImpl.java:172)
at net.codejava.hibernate.VueloManager.setup(VueloManager.java:15)
at net.codejava.hibernate.VueloManager.main(VueloManager.java:54)
hibernate.cfg.xml file :
<?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://127.0.0.1:3306/vuelos_lite</property>
<property name="connection.username">root</property>
<property name="connection.password"></property>
<property name="show_sql">true</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<mapping class="net.codejava.hibernate.Vuelo" />
<mapping class="net.codejava.hibernate.Pasajero" />
<mapping class="net.codejava.hibernate.Pasaje" />
</session-factory>
</hibernate-configuration>
VueloManager class. This is the main class of the program:
public class VueloManager {
protected SessionFactory sessionFactory;
protected void setup() {
final StandardServiceRegistry registry = new StandardServiceRegistryBuilder().configure().build();
try {
sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory();
} catch (Exception ex) {
StandardServiceRegistryBuilder.destroy(registry);
}
}
protected void read() {
Session session = sessionFactory.openSession();
String identificadorId = "BRU-2222";
Vuelo vuelo = session.get(Vuelo.class, identificadorId);
System.out.println("Id: " + vuelo.getIdentificador());
System.out.println("Fecha: " + vuelo.getDate());
System.out.println("Tipo Vuelo: " + vuelo.getTipo_vuelo());
exit();
}
public static void main(String[] args) {
VueloManager manager = new VueloManager();
manager.setup();
//manager.read();
manager.exit();
}
}
I have checked hibernate.cfg.xml connections and all is fine.
I have created a maven project with hibernate 5.4 and successfully created DAOs now when I try to get Hibernate Session via getSessionFactory().getCurrentSession() I get Exception org.hibernate.HibernateException: No CurrentSessionContext configured! although I have already added
<property name="hibernate.current_session_context_class">thread</property> in hibernate.cfg.xml file. Already checked several forums including this question org.hibernate.HibernateException: No CurrentSessionContext configured but unable to solve it,
Here is the 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.bytecode.use_reflection_optimizer">false</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">onetozero</property>
<property name="hibernate.connection.url">jdbc:mysql://192.168.0.112:3306/ecdis</property>
<property name="hibernate.connection.username">root1</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL8Dialect</property>
<property name="show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<property name="hibernate.current_session_context_class">thread</property>
<mapping class="Domain.Route"/>
<mapping class="Domain.RoutePoint"/>
</session-factory>
</hibernate-configuration>
HibernateSession Class
public class HibernateSession {
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;
}
public static void shutdown() {
// Close caches and connection pools
getSessionFactory().close();
}
}
and this is how I am using getting the List via DAO
public List<T> list() {
Session session = HibernateSession.getSessionFactory().getCurrentSession();
CriteriaQuery<T> query = session.getCriteriaBuilder().createQuery(entityClass);
query.select(query.from(entityClass));
return session.createQuery(query).getResultList();
}
I am new new to Java and Hibernate, also not using any framework atm so a little detail can also go along the way. TIA
Use HibernateSession.getSessionFactory().openSession() rather than getCurrentSession() to get session, then session factory will bind session to current context as you are using current session context class thread not JTA.Details here
I have very simple maven + hibernate project.
I want to retrieve data and print it in console with the command "select * from product". But each time i launch my app, it rebuilds all tables in db, as a result all data is removed.
What should I do so tables are not rerebuilt each time I launch my app?
Main.java
public class Main {
static final Logger logger = LogManager.getLogger(Main.class);
public static void main(String[] args) {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.openSession();
List<Object> products = null;
try {
session.beginTransaction();
SQLQuery query = session.createSQLQuery("select * from product");
query.addEntity(Product.class);
products = query.list();
session.getTransaction().commit();
} catch (Exception e) {
session.getTransaction().rollback();
e.printStackTrace();
} finally {
session.close();
sessionFactory.close();
}
System.out.println("Hello");
for (Iterator iterator = products.iterator(); iterator.hasNext(); ) {
Product product = (Product) iterator.next();
logger.info("Hello");
}
}
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="hibernate.connection.driver_class">org.postgresql.Driver</property>
<property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/hibernate</property>
<property name="hibernate.connection.username">postgres</property>
<property name="hibernate.connection.password">****</property>
<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">create</property>
<property name="hibernate.jdbc.lob.non_contextual_creation">true</property>
<mapping class="models.User"/>
<mapping class="models.Role"/>
<mapping class="models.Product"/>
<mapping class="models.ProductCategory"/>
<mapping class="models.Order" />
</session-factory>
</hibernate-configuration>
Change your line
<property name="hbm2ddl.auto">create</property>
by
<property name="hbm2ddl.auto">validate</property>
Look also https://docs.jboss.org/hibernate/orm/5.2/userguide/html_single/Hibernate_User_Guide.html#configurations-hbmddl
Use following code in your hibernate.cfg.xml file
<property name="hbm2ddl.auto">Update</property>
instead of
<property name="hbm2ddl.auto">create</property>
Hibernate does not create any tables:
I got a Tomcat server where my jsf/hibernate project runs on. The database server is a MySQL server. Starts without problems but does not create any tables.
I made a new project without the Tomcat server and any other stuff. Only the Hibernate related code. Still no errors and warnings, but also no tables created.
Hibernate config (hibernate.cfg.xml):
<?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="connection.url">jdbc:mysql://localhost:3306/3bt_database</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.username">root</property>
<property name="connection.password"></property>
<property name="hbm2ddl.auto">create</property>
<mapping class="model.Testtable"/>
</session-factory>
</hibernate-configuration>
HibernateUtil:
public class HibernateUtil {
private static final SessionFactory sessionfactory = buildSessionFactory();
public static SessionFactory buildSessionFactory() throws HibernateException {
try {
Configuration configuration = new Configuration();
configuration.configure();
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
return configuration.buildSessionFactory(serviceRegistry);
} catch (Throwable ex) {
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionfactory(){
return sessionfactory;
}
}
StartStopListener:
#WebListener
public class StartStopListener implements ServletContextListener {
#Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
HibernateUtil.getSessionfactory().openSession();
}
#Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
HibernateUtil.getSessionfactory().close();
}
}
Testtable:
#Entity
#Table(name="tblTest")
public class Testtable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int testID;
private String testname;
}
Please do not tell me to create them manually. This is not the answer I am looking for.
try to prepend hibernate. in every propery name
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/3bt_database</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.hbm2ddl.auto">create</property>
<mapping class="model.Testtable"/>
</session-factory>
</hibernate-configuration>
Update :-
Provide one more property. try at beginning ..
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
//or try with
<property name="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>
(Posted on behalf of the OP).
I solved the problem. The mapping setting in the XML was no working properly. This link helped me out very much.
I have two different config file for two different database and each one of them as there sessions open. Below is the code.
FYI - for security reasons i removed all my credential and have dummy one placed in my config files
one.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="dialect">org.hibernate.dialect.Oracle10gDialect</property>
<property name="connection.url">URL</property>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="connection.username">userName</property>
<property name="connection.password">Password</property>
<mapping class="com.ClassNameOfTheTable" />
</session-factory>
</hibernate-configuration>
Second.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="hibernate.dialect">org.hibernate.dialect.OracleDialect</property>
<property name="hibernate.connection.driver_class">oracle.jdbc.OracleDriver</property>
<property name="hibernate.connection.url">url</property>
<property name="hibernate.connection.username">userName</property>
<property name="hibernate.connection.password">password</property>
<mapping class="com.tableClassName" />
</session-factory>
</hibernate-configuration>
HibernateStratApp class(where i set the configured file)
package com.tn.gov;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class HibernateStartApp {
private static final SessionFactory sessionFactory = buildSessionFactory1();
private static final SessionFactory sessionFactory1 = buildSessionFactory2();
Session session=null;
Transaction transaction = null;
private static SessionFactory buildSessionFactory1() {
try {
// Create the SessionFactory from hibernate.cfg.xml
return new Configuration().configure("one.cfg.xml").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 getSessionFactoryOne() {
return sessionFactory;
}
public static SessionFactory getSessionFactoryTwo(){
return sessionFactory1;
}
private static SessionFactory buildSessionFactory2() {
try {
// Create the SessionFactory from hibernate.cfg.xml
return new Configuration().configure("two.cfg.xml").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);
}
}
}
And by opening and closing sessions i am retrieving the values.
But i am geting failed.org.hibernate.exception.JDBCConnectionException: Error calling Driver#connect when i try to connect.
i could able to figure this out, It was the problem with the URL which i was pointing to, That weird, that the error message dint printed it out correct.