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 am using Hibernate 4.3.8.
Oracle Release 12.1.0.2.0 .
I have two entity name as Child and Parent Entity.
They are basically joined entity.
We are using Hibernate batching property for performance reason but when it try to save record in Child entity it throws StackOverflowError.
Hibernate Batching property:
<property name="hibernate.jdbc.batch_size">100</property>
<property name="hibernate.jdbc.batch_versioned_data">true</property>
<property name="hibernate.order_inserts">true</property>
<property name="hibernate.order_updates">true</property>
Child Entity HBM
<hibernate-mapping>
<class entity-name="ChildEntity_Name" table="ChildEntity_DB" dynamic-insert="true" dynamic-update="true">
<id name="ID" type="java.lang.Long" column="ID">
<generator class="native"/>
</id>
<version name="RevisionId" access="field" column="RevisionId" type="java.lang.Long" unsaved-value="undefined" generated="never"/>
<property name="ModifiedUser" type="java.lang.String" column="ModifiedUser"/>
<property name="DealName_db" type="java.lang.String" column="DealName_db"/>
<property name="TotalPrice_db" type="java.lang.Long" column="TotalPrice_db"/>
<property name="DealDate_db" type="java.lang.String" column="DealDate_db"/>
<property name="ModifiedDate" type="java.util.Date" column="ModifiedDate"/>
<property name="CreatedUser" type="java.lang.String" column="CreatedUser"/>
<property name="CreatedDate" type="java.util.Date" column="CreatedDate"/>
<many-to-one name="CE_UK" entity-name="Parent_Entity_Name" property-ref="UK_PD1" unique="false" fetch="join" update="true" insert="true">
<column name="CustID_db" not-null="true"/>
</many-to-one>
<properties name="UK_Child" unique="true" insert="true" update="true">
<property name="DealId_db" type="java.lang.String" column="DealId_db"/>
</properties>
</class>
</hibernate-mapping>
Parent Entity HBM:
<hibernate-mapping>
<class entity-name="Parent_Entity_Name" table="Parent_Entity_DB" dynamic-insert="true" dynamic-update="true" mutable="true" polymorphism="implicit" select-before-update="false" optimistic-lock="version">
<id name="ID" type="java.lang.Long" column="ID">
<generator class="native"/>
</id>
<version name="RevisionId" access="field" column="RevisionId" type="java.lang.Long" unsaved-value="undefined" generated="never"/>
<property name="ModifiedUser" type="java.lang.String" column="ModifiedUser" unique="false" optimistic-lock="true" lazy="false" generated="never"/>
<property name="CustName_db" type="java.lang.String" column="CustName_db" unique="false" optimistic-lock="true" lazy="false" generated="never"/>
<property name="CustAddress_db" type="java.lang.String" column="CustAddress_db" unique="false" optimistic-lock="true" lazy="false" generated="never"/>
<property name="ModifiedDate" type="java.util.Date" column="ModifiedDate" unique="false" optimistic-lock="true" lazy="false" generated="never"/>
<property name="CreatedUser" type="java.lang.String" column="CreatedUser" unique="false" optimistic-lock="true" lazy="false" generated="never"/>
<property name="CreatedDate" type="java.util.Date" column="CreatedDate" unique="false" optimistic-lock="true" lazy="false" generated="never"/>
<properties name="UK_PD1" unique="true" insert="true" update="true" optimistic-lock="true">
<property name="CustID_db" type="java.lang.String" column="CustID_db" unique="false" optimistic-lock="true" lazy="false" generated="never"/>
</properties>
</class>
</hibernate-mapping>
Class:
import java.util.HashMap;
import java.util.Map;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.Transaction;
public class TestBatching {
public static void main(String[] args) {
Session session = null;
Transaction tx = null;
try {
session = HibernateUtil.getSessionFactory().openSession();
System.out.println("Got the hibernate session ...");
tx = session.beginTransaction();
System.out.println("Opening tx ...");
Map<String, Object> parentEntityMap = new HashMap();
HashMap uniqueKeyMapping = new java.util.HashMap<>();
uniqueKeyMapping.put("CustID_db", String.valueOf(1));
parentEntityMap.put("CustID_db", String.valueOf(1));
parentEntityMap.put("UK_PD1", uniqueKeyMapping);
parentEntityMap.put("CustName_db", String.valueOf("John"));
parentEntityMap.put("CustAddress_db", String.valueOf("Mumbai"));
parentEntityMap.put("ModifiedDate", java.sql.Timestamp.valueOf("2017-11-15 15:30:14.332"));
parentEntityMap.put("CreatedDate", java.sql.Timestamp.valueOf("2017-11-15 15:30:14.332"));
parentEntityMap.put("ModifiedUser", String.valueOf("User1"));
parentEntityMap.put("CreatedUser", String.valueOf("User1"));
System.out.println("Saving record in Parent Entity ......");
session.save("Parent_Entity_Name", parentEntityMap);
System.out.println("Saved record in Parent Entity ......");
Map<String, Object> childEntityMap = new HashMap();
HashMap uniqueKeyMapping1 = new java.util.HashMap<>();
uniqueKeyMapping1.put("DealId_db", String.valueOf(1));
childEntityMap.put("UK_Child", uniqueKeyMapping1);
childEntityMap.put("DealId_db", String.valueOf(1));
childEntityMap.put("CustID_db", String.valueOf(1));
childEntityMap.put("DealName_db", String.valueOf("SS"));
childEntityMap.put("DealDate_db", "2017-11-15 15:30:14.332");
childEntityMap.put("TotalPrice_db", Long.valueOf(100));
childEntityMap.put("RevisionId", Long.valueOf("1"));
HashMap fkMapping = new java.util.HashMap<>();
fkMapping.put("CustID_db", String.valueOf(1));
fkMapping.put("ID", Long.valueOf("1"));
fkMapping.put("UK_PD1", fkMapping);
fkMapping.put("RevisionId", Long.valueOf("1"));
childEntityMap.put("CE_UK", fkMapping);
childEntityMap.put("ModifiedDate", java.sql.Timestamp.valueOf("2017-11-15 15:30:14.332"));
childEntityMap.put("CreatedDate", java.sql.Timestamp.valueOf("2017-11-15 15:30:14.332"));
childEntityMap.put("ModifiedUser", String.valueOf("User1"));
childEntityMap.put("CreatedUser", String.valueOf("User1"));
System.out.println("Saving record in Child Entity ......");
session.save("ChildEntity_Name", childEntityMap);
System.out.println("Saved record in Child Entity ......");
System.out.println("Flushing session ......");
session.flush();
System.out.println("Flushed session ......");
System.out.println("Commiting tx ......");
tx.commit();
System.out.println("Commited tx ......");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (session != null) {
session.close();
System.out.println(" closing hibernate session ...");
}
}
}
}
Hibernate Configuration:
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.Oracle10gDialect</property>
<property name="hibernate.connection.driver_class">oracle.jdbc.OracleDriver</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:#localhost:1521:xe</property>
<property name="hibernate.connection.username">user1</property>
<property name="hibernate.connection.password">user1</property>
<!-- Hibernate caching settings -->
<property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>
<property name="hibernate.cache.use_second_level_cache">false</property>
<!-- Hibernate-c3p0 settings -->
<property name="hibernate.c3p0.min_size">2</property>
<property name="hibernate.c3p0.max_size">50</property>
<property name="hibernate.c3p0.acquire_increment">1</property>
<property name="hibernate.c3p0.idle_test_period">100</property>
<property name="hibernate.c3p0.timeout">100</property>
<property name="hibernate.c3p0.max_statements">0</property>
<!-- Hibernate-Batching settings -->
<property name="hibernate.jdbc.batch_size">100</property>
<property name="hibernate.jdbc.batch_versioned_data">true</property>
<property name="hibernate.order_inserts">true</property>
<property name="hibernate.order_updates">true</property>
<!-- HBM Mapping files -->
<mapping resource="Child_entity.hbm.xml"/>
<mapping resource="Parent_entity.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Output:
Got the hibernate session ...
Opening tx ...
Saving record in Parent Entity ......
Saved record in Parent Entity ......
Saving record in Child Entity ......
Saved record in Child Entity ......
Flushing session ......
closing hibernate session ...
Exception in thread "main" java.lang.StackOverflowError
at java.base/java.lang.Long.hashCode(Long.java:1402)
at java.base/java.util.Objects.hashCode(Objects.java:116)
at java.base/java.util.HashMap$Node.hashCode(HashMap.java:297)
at java.base/java.util.AbstractMap.hashCode(AbstractMap.java:527)
at java.base/java.util.Objects.hashCode(Objects.java:116)
Note: Without hibernate batching property it is working fine.
Can anyone please help me here?
I'm writing simple app using Hibernate. I have hibernate.cfg.xml file as follows:
<!DOCTYPE hibernate-configuration SYSTEM
"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/demo
</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">1234</property>
<property name="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</property>
<!-- Use the C3P0 connection pool provider -->
<property name="hibernate.c3p0.min_size">5</property>
<property name="hibernate.c3p0.max_size">20</property>
<property name="hibernate.c3p0.timeout">300</property>
<property name="hibernate.c3p0.max_statements">50</property>
<property name="hibernate.c3p0.idle_test_period">3000</property>
<!--List of XML mapping files -->
<mapping class="www.Message"/>
</session-factory>
</hibernate-configuration>
and retrieve SessionFactory object as follows:
//in HibernateUtil.class
SessionFactory sessionFactory;
Configuration configuration=new
Configuration().configure("hibernate.cfg.xml");
sessionFactory=configuration.buildSessionFactory();`
And everything works fine until I add C3P0 jars:
c3p0-0.9.5.2.jar
hibernate-c3p0-5.2.14.Final.jar
mchange-commons-java-0.2.11.jar
After adding jars above, the app throws StackOverflowError.
Here's my main App class:
package www;
import org.hibernate.Session;
import utils.HibernateUtil;
import java.util.List;
public class HelloWorld {
public static void main(String[] args) {
Session session = null;
try {
session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
session.save(new Message("Hello Denmark!"));
session.getTransaction().commit();
session.close();
System.out.println("Message saved...");
session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
List messages = session.createQuery("from Message m order by m.text
asc").list();
System.out.println("Messages found:"+messages.size());
for (Object mes: messages) {
Message message = (Message) mes;
System.out.println(message.getText());
}
session.getTransaction().commit();
session.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (session != null) session.close();
}
}
}
Any help would be appreciated.
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>
I am trying to run following code in eclipse
package com.trial;
import java.sql.*;
import java.io.*;
import org.hibernate.*;
import org.hibernate.cfg.*;
public class AddStudent {
private static SessionFactory sessionFactory;
public static void main(String args[]) throws Exception {
DataInputStream d = new DataInputStream(System.in);
System.out.println("ENTER YOUR NAME");
String name = d.readLine();
System.out.println("ENTER YOUR DEGREE");
String degree = d.readLine();
System.out.println("ENTER YOUR PHONE");
int phone = Integer.parseInt(d.readLine());
System.out.println("Name: " + name);
System.out.println("Degree: " + degree);
System.out.println("Phone: " + phone);
if ((name.equals("") || degree.equals(""))) {
System.out.println("Information Required");
}
else {
try {
sessionFactory = new Configuration().configure("com//xml//hibernate.cfg.xml").buildSessionFactory();
}
catch (Exception e) {
System.out.println(e.getMessage());
}
Session s = sessionFactory.openSession();
Student stu = new Student();
stu.setName(name);
stu.setDegree(degree);
stu.setPhone(phone);
s.save(stu);
System.out.println("Added to Database");
if (s != null)
s.close();
}
}
}
But getting Runtime exception during creating session factory object that Unable to read XML.
I am using following xml files
hibernate.cfg.xml
<!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 name="studentFactory">
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/ganeshdb</property>
<property name="connection.username">****</property>
<property name="connection.password">****</property>
<property name="connection.pool_size">10</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">create</property>
<mapping resource="com//xml//student.hbm.xml" />
</session-factory>
</hibernate-configuration>
Mapping File
<?xml version="1.0"? encoding='UTF-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/hibernate-configuration-3.0.dtd">
<hibernate-mapping>
<class name="com.trial.Student" table="studentdemo">
<id name="id" type="int" column="ID">
<generator class="increment" />
</id>
<property name="name" column="name" />
<property name="degree" column="degree" />
<property name="phone" column="phone" />
</class>
</hibernate-mapping>
plz help.
<mapping resource="student.hbm.xml" />
and make sure it is in same direcotry as hibernate.cfg.xml