I created hibernate application with using c3p0 for get access to my database,
This is 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>
<session-factory>
<property name="show_sql">true</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/example</property>
<property name="hibernate.connection.username">******</property>
<property name="hibernate.c3p0.min_size">5</property>
<property name="hibernate.c3p0.max_size">20</property>
<property name="hibernate.c3p0.timeout">3000</property>
<property name="hibernate.c3p0.max_statements">50</property>
<property name="hibernate.c3p0.idle_test_period">300</property>
<property name="hibernate.c3p0.testConnectionOnCheckout">true</property>
<property name="hibernate.c3p0.preferredTestQuery">SELECT 1</property>
<property name="hibernate.connection.password">*******</property>
<mapping resource="beans/Reminder.hbm.xml"/>
<mapping resource="beans/StressType.hbm.xml"/>
<mapping resource="beans/Medication.hbm.xml"/>
<mapping resource="beans/ReportType.hbm.xml"/>
<mapping resource="beans/Comobility.hbm.xml"/>
<mapping resource="beans/Report.hbm.xml"/>
</session-factory>
</hibernate-configuration>
And this my HibernateUtil file . I named it as SessionFactoryBuilder.java,
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
public class SessionFactoryBuilder
{
private static SessionFactoryBuilder instance;
private static SessionFactory sessionFactory;
private SessionFactoryBuilder()
{
buildConfig();
System.out.println("hehehehe");
}
private static void buildConfig()
{
Configuration configuration = new Configuration().configure();
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties());
sessionFactory = configuration.buildSessionFactory(builder.build());
}
public static SessionFactoryBuilder getInstance()
{
if(instance == null)
{
instance = new SessionFactoryBuilder();
}
return instance;
}
public SessionFactory getSessionFactory()
{
return sessionFactory;
}
}
When I get access to my database using this SessionFactoryBuilder, I get following , "Too many connections" .
This is an example how I used this,
ReportTypeService reportTypeService = new ReportTypeService();
List<ReportType> list = reportTypeService.getAllReportTypes();
for(int i=0;i<list.size();i++){
out.print("Type - "+list.get(i).getType());
}
This is not coming at all the time .But when it appears the connection to the database is gone.
Have any ideas ?
Related
Mvn clean and Mvn install are successful without warnings and errors.The files hibernate.cfg.xml and App.java are:
The error from console during initialization is:
log4j:WARN No appenders could be found for logger (org.jboss.logging).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Exception in thread "main" org.hibernate.HibernateException: Connection cannot be null when 'hibernate.dialect' not set
at org.hibernate.service.jdbc.dialect.internal.DialectFactoryImpl.determineDialect(DialectFactoryImpl.java:97)
at org.hibernate.service.jdbc.dialect.internal.DialectFactoryImpl.buildDialect(DialectFactoryImpl.java:67)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:170)
at org.hibernate.service.internal.StandardServiceRegistryImpl.configureService(StandardServiceRegistryImpl.java:75)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:159)
at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:131)
at org.hibernate.cfg.Configuration.buildTypeRegistrations(Configuration.java:1797)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1755)
at com.icdab.www.icdab_first.App.init(App.java:33)
at com.icdab.www.icdab_first.App.main(App.java:76)
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.connection.driver.class">oracle.jdbc.OracleDriver</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:#localhost:1521:ORCL</property>
<property name="hibernate.connection.username">system</property>
<property name="hibernate.connection.password">password</property>
<property name="hiberante.dialect">org.hibernate.dialect.Oracle10gDialect</property>
<property name="show_sql">true</property>
<mapping class="com.icdab.www.icdab_first.CompundKey" />
<mapping class="com.icdab.www.icdab_first.Customer" />
<mapping class="com.icdab.www.icdab_first.Employee" />
<mapping class="com.icdab.www.icdab_first.EventPlan" />
<mapping class="com.icdab.www.icdab_first.EventPlanLine" />
<mapping class="com.icdab.www.icdab_first.EventRequest" />
<mapping class="com.icdab.www.icdab_first.Facility" />
<mapping class="com.icdab.www.icdab_first.Location" />
<mapping class="com.icdab.www.icdab_first.ResourceTbl" />
</session-factory>
</hibernate-configuration>
App.java:
package com.icdab.www.icdab_first;
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
/**
* Hello world!
*
*/
public class App
{
private SessionFactory factory;
private void init(){
System.out.println("in init");
Configuration config = new Configuration().configure("hibernate.cfg.xml")
/*.addAnnotatedClass(CompundKey.class)
.addAnnotatedClass(Customer.class)
.addAnnotatedClass(Employee.class)
.addAnnotatedClass(EventPlan.class)
.addAnnotatedClass(EventPlanLine.class)
.addAnnotatedClass(EventRequest.class)
.addAnnotatedClass(Facility.class)
.addAnnotatedClass(Location.class)
.addAnnotatedClass(ResourceTbl.class) */;
// learn why did you use the annotatedclass and configuration.
ServiceRegistry registry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
factory=config.buildSessionFactory(registry);
}
#SuppressWarnings("deprecation")
private void persistAnnotatedLists(){
Session session = factory.getCurrentSession();
session.beginTransaction();
Customer customer = new Customer();
customer.setAddress("address123");
customer.setCity("lansing");
customer.setContact("1632 ne ave");
customer.setCustname("john");
customer.setCustno("1234");
customer.setInternal("internal");
customer.setPhone(122345679);
customer.setState("OR");
customer.setZip(97654);
List<EventRequest> ers = new ArrayList<EventRequest>();
ers.add(new EventRequest(123,new Date(92,5,1),new Date(91,5,1),new Date(93,5,1),"av",123,456,124));
ers.add(new EventRequest(1234,new Date(92,5,2),new Date(91,5,2),new Date(93,5,2),"av",124,457,125));
customer.setEventrequests(ers);
session.save(customer);
session.getTransaction().commit();
System.out.println("done persist");
}
private void retrieveList(){
Session session = factory.getCurrentSession();
session.beginTransaction();
List list = session.createQuery("from com.icdab.www.icdab_first.Customer").list();
for (Object object : list) {
System.out.println("** List items: "+object);
}
session.getTransaction().commit();
System.out.println("Done retrieve");
}
public static void main (String[] args){
App app = new App();
app.init();
app.persistAnnotatedLists();
app.retrieveList();
}
}
And the project structure is:
What i do wrong? After running main class i have view in console like in current screenshot below and the console continues to work and nothing happens.
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="connection.driver_class">org.postgresql.Driver</property>
<property name="connection.url">jdbc:postgresql://localhost:5432/Gillie_PL</property>
<property name="connection.username">postgres</property>
<property name="connection.password">postgres</property>
<property name="dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
</session-factory>
</hibernate-configuration>
hibernateUtil.class:
package hibernateConn;
import org.hibernate.SessionFactory;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cfg.Configuration;
public class HibernateUtil {
private static SessionFactory sessionFactory = null;
static {
Configuration cfg =
new Configuration().configure("/hibernateConn/hibernate.cfg.xml");
StandardServiceRegistryBuilder builder =
new StandardServiceRegistryBuilder()
.applySettings(cfg.getProperties());
sessionFactory = cfg.buildSessionFactory(builder.build());
}
public static SessionFactory getSessionFactory(){
return sessionFactory;
}
}
Main.Class:
package hibernateConn;
import org.hibernate.SessionFactory;
public class Main {
public static void main(String[] args) {
SessionFactory sessionFactory = HibernateUtil.getSessionFactory();
}
}
After I run Main.class I have in console:
And that's all. Nothing more, the program continues to work and nothing happens, as if recursion occurs ... Maybe I did not correctly specify the settings in xml?
I rewrote the HibernateUtil.class :
static {
try{
sessionFactory = new Configuration().configure("/hibernateConn/hibernate.cfg.xml").buildSessionFactory();
}catch(Throwable ex){
System.err.println("++++Initial SessionFactory creation failed.++++: " + ex);
ex.printStackTrace();
}
}
public static SessionFactory getSessionFactory(){
return sessionFactory;
}
and it all worked. The question can be closed.
Image
ERROR:
1) AdminModel.java - Model class.
2) HibernateUtil.java facilitates the Hibernate DB conn.
3) AdminDAO.java - u guyz know what these are...I'll save the pain to explain...and oh yes...m already through days of pain with this bug ...trynna debug...i've got deadlines to meet... if u guyz could help me it'd be a matter of great deal...
public class AdminModel {
private int adminID;
private String username;
private String password;
public int getAdminID() {
return adminID;
}
public void setAdminID(int adminID) {
this.adminID = adminID;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
HibernateUtil.java
public class HibernateUtil {
public static SessionFactory sessionFactory;
static {
try {
/* File f=new File("O:/#workspace/#eclipse/ekatabookstore.com/src/hibernate.cfg.xml");
sessionFactory =new Configuration().configure(f).buildSessionFactory();
*/
/****OR****/
String hibernatePropsFilePath = "O:/#workspace/#eclipse/ekatabookstore.com/src/hibernate.cfg.xml";
File hibernatePropsFile = new File(hibernatePropsFilePath);
Configuration configuration = new Configuration();
configuration.configure(hibernatePropsFile);
configuration.addResource("ekatabookstore.hbm.xml");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
sessionFactory = configuration.buildSessionFactory(serviceRegistry);
} catch (Exception ex) {
System.err.println("Initial SessionFactory creation failed." + ex);
//throw new ExceptionInInitializerError(ex);
}
}
public static Session openSession() {
return HibernateUtil.sessionFactory.openSession();
//return sessionFactory.getCurrentSession();
}
}
AdminDAO.java
public AdminDAO(AdminModel adminUserObj) {
public void createAdmin() {
/*
* CRUD operation of HIBERNATE C-->Create SessionFactory Object is a
* heavy object and takes up huge resources, so it is better to create
* only one object and share it where needed.
*/
SessionFactory sessionFactoryObj = HibernateUtil.sessionFactory;
// System.out.println(sessionFactoryObj.getClass().getName());
Session session = sessionFactoryObj.openSession();
session.beginTransaction();// Transaction Started
session.save(adminObj);// SAVED
session.getTransaction().commit();// Transaction Ended
System.out.println("!!!SUCCESSFUL CREATE!!!");
session.close();// CLOSE session resource of Hibernate
Notification.notificationMsg = "ADMIN CREATE - SUCCESSFUL!";
}
}
hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!--
~ Hibernate, Relational Persistence for Idiomatic Java
~
~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
-->
<!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:3306/ekatabookstoreDB</property>
<property name="connection.username">xyz</property>
<property name="connection.password">xyz</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</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.internal.NoCacheProvider</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<!-- <property name="hbm2ddl.auto">create</property> -->
<property name="hbm2ddl.auto">update</property>
<mapping resource="ekatabookstore.hbm.xml" />
</session-factory>
</hibernate-configuration>
hbn.properties
hiberNateCfgFileName=hibernate.cfg.xml
ekatabookstore.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.ekatabookstore.layer.service.model.AdminModel" table="admin">
<id name="adminID" type="integer" column="id_admin">
<generator class="assigned" />
</id>
<property name="username" type="string" column="username" not-null="true" />
<property name="password" type="string" column="password" not-null="true" />
</class>
</hibernate-mapping>
If you are using spring then, Add autowire on sessionfactory or get it from application context. You can use following code
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class ApplicationContextProvider implements ApplicationContextAware{
private static ApplicationContext context;
public static ApplicationContext getApplicationContext() {
return context;
}
#Override
public void setApplicationContext(ApplicationContext ac)
throws BeansException {
context = ac;
}
}
You can use this class anywhere in your code like
ApplicationContextProvider.getApplicationContext().getBean("sessionFactory");
Please try the following code for creating sessionfactory
final StandardServiceRegistry registry = new StandardServiceRegistryBuilder().configure() // configures settings from hibernate.cfg.xml
.build();
try {
sessionFactory = new MetadataSources( registry).buildMetadata().buildSessionFactory();
}
catch (Exception e) {
StandardServiceRegistryBuilder.destroy( registry );
}
Hope this helps.
Introduction
I am trying to convert a working XML configured spring batch job to javaconfig and I am running into some issues with setting up the session. I want to use a hibernate.cfg.xml file to configure the connection (and I also use it elsewhere, so I do need to keep it).
Given
The working xml configuration looks as following:
<!-- Standard Spring Hibernate Reader -->
<bean id="hibernateItemReader" class="org.springframework.batch.item.database.HibernateCursorItemReader" scope="step">
<property name="sessionFactory" ref="sessionFactory" />
<property name="queryString" value="#{jobExecutionContext[HQL]}" />
<property name="useStatelessSession" value="false"/>
</bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" lazy-init="true">
<property name="configLocation" value="classpath:hibernate.cfg.xml"/>
<property name="cacheableMappingLocations" value="classpath*:META-INF/mapping/*.hbm.xml"/>
</bean>
And the hibernate.cfg.xml looks as following:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE hibernate-configuration SYSTEM "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- Connection to database -->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/SAKILA</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">****</property>
<!-- Conversion from HQL to SQL in log -->
<property name="show_sql">false</property>
<property name="format_sql">true</property>
<property name="use_sql_comments">true</property>
<!-- Session and pool settings -->
<property name="hibernate.current_session_context_class">thread</property>
<property name="hibernate.c3p0.min_size">5</property>
<property name="hibernate.c3p0.max_size">20</property>
<property name="hibernate.c3p0.timeout">1800</property>
<property name="hibernate.c3p0.idle_test_period">1000</property>
<property name="hibernate.c3p0.max_statements">50</property>
</session-factory>
</hibernate-configuration>
The following java config..
#Bean
#Lazy(true)
public SessionFactory sessionFactory(){
LocalSessionFactoryBean session = new LocalSessionFactoryBean();
session.setConfigLocation(hibernateConfig());
session.setCacheableMappingLocations(mappings());
return session.getObject();
}
#Bean
#StepScope
public HibernateCursorItemReader reader(#Value("#{jobExecutionContext[HQL]}") String HQLQuery){
HibernateCursorItemReader reader = new HibernateCursorItemReader<>();
reader.setSessionFactory(sessionFactory());
reader.setQueryString(HQLQuery);
reader.setUseStatelessSession(false);
return reader;
}
Issue
reader.setSessionFactory(sessionFactory());
Throws:
Caused by: java.lang.IllegalStateException: A SessionFactory must be provided
After some research, I think I need to use the LocalSessionFactoryBuilder instead of the LocalSessionFactoryBean.
#Autowired
#Bean
public SessionFactory sessionFactory2(){
LocalSessionFactoryBuilder sessionBuilder = new LocalSessionFactoryBuilder(dataSource());
// ?? sessionBuilder.setConfigLocation(); ??
sessionBuilder.addDirectory(new File(url.toURI()));
}
However, I do not want to provide a datasource because I have all the datasource connection information configured in the hibernate.cfg.xml file.
The accepted answer on How to make hibernate.cfg.xml to a datasource bean suggest to keep the hibernate.cfg.xml file and add Spring configuration.
How do I add hibernate.cfg.xml file to the LocalSessionFactoryBuilder?
I figured it out. I do not want to use the LocalSessionFactoryBuilder at all. In my program I have the following class:
public class HibernateUtil {
private static final SessionFactory SESSIONFACTORY = buildSessionFactory();
private static final String HIBERNATE_CONFIGURATION_LOCATION = "hibernate.cfg.xml";
private static final String MAPPINGS_LOCATION = "src/main/resources/mappings";
private static ServiceRegistry serviceRegistry;
private static SessionFactory buildSessionFactory() {
try {
Configuration configuration = new Configuration();
configuration.configure(HIBERNATE_CONFIGURATION_LOCATION).addDirectory(new File(MAPPINGS_LOCATION));
serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
SessionFactory sessionFactory = configuration.buildSessionFactory(serviceRegistry);
return sessionFactory;
} catch (Exception e) {
System.err.println("Initial SessionFactory creation failed." + e);
throw new ExceptionInInitializerError(e);
}
}
public static SessionFactory getSessionFactory(){
return SESSIONFACTORY;
}
public static void shutdown(){
getSessionFactory().close();
}
}
And calling reader.setSessionFactory(HibernateUtil.getSessionFactory()); did the trick for me!
I'm trying to implement the PreUpdateEventListener of Hibernate in my project, but nothing happens.
My configuration.xml file:
<?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.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/bd_brittos</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">password</property>
<property name="hibernate.show_sql">true</property>
<mapping resource="hibernate/mapeamento/Compra.hbm.xml"/>
<mapping resource="hibernate/mapeamento/CompraHasProduto.hbm.xml"/>
<mapping resource="hibernate/mapeamento/Entidade.hbm.xml"/>
<mapping resource="hibernate/mapeamento/Pesagem.hbm.xml"/>
<mapping resource="hibernate/mapeamento/Produto.hbm.xml"/>
<mapping resource="hibernate/mapeamento/Tabelapesagem.hbm.xml"/>
<mapping resource="hibernate/mapeamento/Venda.hbm.xml"/>
<mapping resource="hibernate/mapeamento/VendaHasProduto.hbm.xml"/>
<mapping resource="hibernate/mapeamento/Contasreceber.hbm.xml"/>
<mapping resource="hibernate/mapeamento/CaixadiarioHasContaspagar.hbm.xml"/>
<mapping resource="hibernate/mapeamento/Contaspagar.hbm.xml"/>
<mapping resource="hibernate/mapeamento/Caixadiario.hbm.xml"/>
<mapping resource="hibernate/mapeamento/CaixadiarioHasContasreceber.hbm.xml"/>
<mapping resource="hibernate/mapeamento/Conf.hbm.xml"/>
<event type="pre-update">
<listener class="br.com.areiasbrittos.persistencia.MyHibernateEventListener" />
</event>
</session-factory>
</hibernate-configuration>
My MyHibernateEventListener class:
import javax.swing.JOptionPane;
import org.hibernate.event.spi.PreUpdateEvent;
import org.hibernate.event.spi.PreUpdateEventListener;
/**
*
* #author Maycon
*/
public class MyHibernateEventListener implements PreUpdateEventListener {
public MyHibernateEventListener() {
this.atencao();
}
public void atencao() {
System.out.println("EEEEUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUUU\n\n");
JOptionPane.showMessageDialog(null, "MyLoadListener");
}
#Override
public boolean onPreUpdate(PreUpdateEvent pue) {
this.atencao();
return true;
}
}
Result: The console didn't show anything.
Perhaps this is no longer relevant, but you had to add the following code:
#PostConstruct
protected void init(){
SessionFactoryImpl sF = emf.unwrap(SessionFactoryImpl.class);
EventListenerRegistry registry = sF.getServiceRegistry().getService(EventListenerRegistry.class);
registry.getEventListenerGroup(EventType.PRE_UPDATE).appendListener(this);
}
Works in Spring