StackOverflowError thrown when C3P0 jars are added - java

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.

Related

Hibernate - Unable to make JDBC Connection [jdbc:mysql//localhost:3306/hibernatedb

I am trying to create a basic hibernate application using hibernate 5.2.10 release. When I run it it says
org.hibernate.HibernateException: Unable to make JDBC Connection [jdbc:mysql//localhost:3306/hibernatedb]
hibernate.cfg.xml:
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.url">jdbc:mysql//localhost:3306/hibernatedb</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name="hibernate.cache.use_query_cache">true</property>
<property name="hibernate.hbm2ddl.auto">udpate</property>
<mapping class="com.chandu.app.model.UserDetails"/>
</session-factory>
Main class:
public class HibernateTest {
public static void main(String[] args) {
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
UserDetails user = getUserObject();
session.save(user);
session.getTransaction().commit();
session.clear();
}
private static UserDetails getUserObject() {
UserDetails user = new UserDetails();
user.setUserName("Test User");
return user;
}
Console:
Code Structure:
I have gone through some of the forums, but couldnt find a solution for the same.
Thanks for the help!
jdbc:mysql//localhost:3306/hibernatedb
Use a colon (:) both before and after "mysql":
jdbc:mysql://localhost:3306/hibernatedb

Hibernate rebuilds tables of DB

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 tables but also throws no errors

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.

HIbernate Stateless Session entity configuration

We are using hibernate to populate a ddbb with data from multiples files. Multiples threads are proccessing the files and when x files are processed we flush the data on the database.
When i try to write on the database we get the next error:
core.exception.SavingException: org.hibernate.MappingException: Unknown entity: FilesPT
at databaseaccess.session.GenericManagerImpl.insertBatch(GenericManagerImpl.java:75)
at FileWriter.flushFiles(FileWriter.java:425)
Caused by: org.hibernate.MappingException: Unknown entity: FilesPT
at org.hibernate.impl.SessionFactoryImpl.getEntityPersister(SessionFactoryImpl.java:597)
at org.hibernate.impl.StatelessSessionImpl.getEntityPersister(StatelessSessionImpl.java:376)
at org.hibernate.impl.StatelessSessionImpl.insert(StatelessSessionImpl.java:80)
at databaseaccess.dao.GenericDAOImpl.insertList(GenericDAOImpl.java:36)
at session.GenericManagerImpl.insertBatch(GenericManagerImpl.java:72)
... 4 more
My Hibernate config file is:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"classpath://org/hibernate/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:#%DB_HOST%:%DB_PORT%:%DB_SID%</property>
<property name="hibernate.connection.username">%DB_USER%</property>
<property name="hibernate.connection.password">%DB_PASS%</property>
<property name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property>
<property name="hibernate.default_schema">%DB_SCHEMA%</property>
<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>
<property name="hibernate.show_sql">false</property>
<property name="hibernate.format_sql">false</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<mapping resource="databaseaccess/entities/Files.hbm.xml"/>
</session-factory>
</hibernate-configuration>
The file databaseaccess/entities/Files.hbm.xml has two different entities:
<hibernate-mapping>
<class name="databaseaccess.entities.Files" table="FILES_PT" entity-name="FilesPT">
<id name="dealId" column="FILE_ID" type="java.lang.String" length="50" />
<property name="filename" column="FILENAME" type="java.lang.String" length="250" />
<property name="folder" column="FOLDER" type="java.lang.String" length="30" />
</class>
<class name="databaseaccess.entities.Files" table="FILES_ES" entity-name="FilesES">
<id name="dealId" column="FILE_ID" type="java.lang.String" length="50" />
<property name="filename" column="FILENAME" type="java.lang.String" length="250" />
<property name="folder" column="FOLDER" type="java.lang.String" length="30" />
</class>
</hibernate-mapping>
To save the data we are using an Stateless session generated from the hibernateUtil:
public void insertList(final String entityName, final Collection entities) {
StatelessSession session = HibernateUtil.openStatelessSession();
try {
Transaction tx = session.beginTransaction();
try {
for (Object entity : entities) {
session.insert(entityName, entity);
}
tx.commit();
} catch (final HibernateException e) {
logger.error("Error inserting " + entities.size() + " rows in database. " + e.getMessage() + ":\n "
+ e.getMessage());
throw e;
} finally {
tx.rollback();
}
} finally {
session.close();
}
}
The hibernate util generate a static session factory
static {
try {
// Create the SessionFactory from config file.
File fileCfgHibernate = new File(ConfigurationManager.getProperty("Global.properties", "HIBERNATE_CFG_FILE"));
logger.info("Opening DB session with configuration from: " + fileCfgHibernate.getPath());
Configuration cfgHibernate = new Configuration().configure(fileCfgHibernate);
sessionFactory = cfgHibernate.buildSessionFactory();
} catch (Throwable ex) {
// Log the exception.
logger.error("DB session creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static StatelessSession openStatelessSession() {
return sessionFactory.openStatelessSession();
}
We have checked that the session factory use the configuration on the hibernate.cfg file but it seems that the session is not getting the configuration. What are we missing?

How to mock the database session for HSQL DB Junit

I have a repository implementation class as below.
public class TesepositoryImpl extends OTPRepositoryBase implements
TestRepository {
public TesepositoryImpl() {
super(RequiresOTPSession.YES);
}
#Override
public int createPreference(AirDetail AirDetail)
throws PersistenceException {
Transaction tx = null;
Session session = null;
try {
session = otpDatabaseSession.openSession();
tx = session.beginTransaction();
session.save(AirDetail);
tx.commit();
} finally {
otpDatabaseSession.closeSession(session);
}
return AirDetail.getAirDetailId().intValue();
}
I have stated writting junit for the above
public class TesRepositoryImplTest {
private EmbeddedDatabase db;
#Before
public void setUp() {
db = new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.HSQL)
.addScript("db/sql/create-db.sql")
.addScript("db/sql/insert-data.sql").build();
}
TesRepository testRepository = new TestRepositoryImpl();
#Test
public void createPreference() throws Exception {
//*setting values** creating preference**/
int airRefereID = testRepository
.createPreference(preference);
}
#After
public void tearDown() {
db.shutdown();
}
i defined hibernate cfg file as below
<?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="connection.driver_class">org.hsqldb.jdbcDriver</property>
<property name="connection.url">jdbc:hsqldb:mem:fcds</property>
<property name="connection.username">SA</property>
<property name="connection.password"></property>
<property name="connection.pool_size">10</property>
<property name="dialect">org.hibernate.dialect.HSQLDialect</property>
<property name="connection.autocommit">true</property>
<property name="hibernate.bytecode.use_reflection_optimizer">false</property>
<property name="hibernate.current_session_context_class">thread</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hibernate.bytecode.use_reflection_optimizer">false</property>
<property name="hibernate.standard_service_registry_builder">false</property>
<mapping class="com.aa.dotc.commons.domain.preference" />
</session-factory>
</hibernate-configuration>
I need to know the below.
When I call testRepository
.createPreference(preference);
I need to override the otpsession to HSQL session.
Kindly help me how to achieve the above using HSQL or share any samples to achieve the same.

Categories