Hibernate PreUpdateEventListener doesn`t work - java

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

Related

WARN: HHH000342: Could not obtain connection to query metadata : Communications link failure

I developed a java desktop application using hibernate to connect to my computer's mysql database.
When I run the application on the computer that is the mysql server, it works properly, but when I run it from another computer to connect, I get the error:
WARN: HHH000342: Could not obtain connection to query metadata : Communications link failure
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://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.cj.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://192.168.1.72:3306/factura_registro?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">1</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>
<property name="hbm2ddl.auto">update</property>
<property name="show_sql">false</property>
<property name="hibernate.bytecode.use_reflection_optimizer">false</property>
</session-factory>
</hibernate-configuration>
This is my main class
public class App {
public static Configuration c;
public static ServiceRegistry reg;
public static void main(String[] args) {
try {
c= new Configuration().configure().addAnnotatedClass(Usuario.class).addAnnotatedClass(Unidad.class);
reg= new ServiceRegistryBuilder().applySettings(c.getProperties()).buildServiceRegistry();
SessionFactory sf= c.buildSessionFactory(reg);
Session s= sf.openSession();
//-------------Comenzar interface inicio sesion--------------//
final Dao dao = new Dao(s);
java.awt.EventQueue.invokeLater(new Runnable() {
public void run() {
GUIInicioSesion sesion =new GUIInicioSesion(dao);
sesion.setLocationRelativeTo(null);
sesion.setVisible(true);
}
});
}catch(Exception e) {
JOptionPane.showMessageDialog(null,"Error", "Alerta", 2);
}
}
}
These are de messages
Starting configuration
Warning show
Exception message

java.lang.NoSuchMethodError: org.hibernate.cfg.annotations.reflection.JPAMetadataProvider

i created new simple web app projected with hibernate 5 , Tomcat9 server. when run project it show following error.
Exception
javax.servlet.ServletException: Servlet execution threw an exception
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
Root Cause
java.lang.NoSuchMethodError:
org.hibernate.cfg.annotations.reflection.JPAMetadataProvider.<init>
(Lorg/hibernate/boot/spi/MetadataBuildingOptions;)V
org.hibernate.boot.internal.MetadataBuilderImpl$MetadataBuildingOptionsImpl
.generateDefaultReflectionManager(MetadataBuilderImpl.java:741)
org.hibernate.boot.internal.MetadataBuilderImpl$MetadataBuildingOptionsImpl
.<init>(MetadataBuilderImpl.java:714)
org.hibernate.boot.internal.MetadataBuilderImpl.<init >
(MetadataBuilderImpl.java:126)
org.hibernate.boot.MetadataSources.getMetadataBuilder
(MetadataSources.java:135)
org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:654)
org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:726)
org.serv.Controller.doPost(Controller.java:45)
javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
here is servlet which throws exception
package org.serv;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.pojo.PhoneBook;
#WebServlet("/Controller")
public class Controller extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Controller() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response )throws ServletException, IOException{
doPost(request,response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PhoneBook book = new PhoneBook();
book.setName(request.getParameter("name"));
book.setPhone(Integer.parseInt( request.getParameter("number")));
book.setAddress(request.getParameter("address"));
try {
SessionFactory sf = new Configuration().configure("/hibernate.cfg.xml").buildSessionFactory();
Session sess = sf.openSession();
sess.beginTransaction();
sess.save(book);
sess.close();
}catch(HibernateException e ) {e.printStackTrace();System.err.println("Session problem ");}
}//end doPost
}//servlet
Here are library list which been listed.
and here is hibernate.cfg.xml file structure
<?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:3306/stockdb</property>
<property name="connection.username">root</property>
<property name="connection.password"></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>
<!-- 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>
<!-- Name the Annotated Entity Class -->
<mapping class= "org.pojo.Product"/>
<mapping class= "org.pojo.Catagories"/>
<mapping class= "org.pojo.ProductDetail"/>
<mapping class= "org.pojo.Supplier"/>
<mapping class= "org.pojo.Staff"/>
<mapping class= "org.pojo.Customer"/>
<mapping class= "org.pojo.PurchaseInvoice"/>
<mapping class= "org.pojo.SaleInvoice"/>
<mapping class= "org.pojo.Stock"/>
<mapping class= "org.pojo.PhoneBook"/>
</session-factory>
</hibernate-configuration>
I have been searched everywhere and also search stackover flow but didn't found solution.

Having an error org.hibernate.HibernateException. The error is in the init method (while running the application as java app.)

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:

HibernateException: Too many connections , using c3p0

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 ?

null pointer exception while creating session factory

I am getting null pointer exception at the line
SessionFactory sesionFactory = new Configuration().configure().buildSessionFactory() ;
any suggestion what might be causing it ??
error log says this :
Exception in thread "main" java.lang.NullPointerException
at org.hibernate.service.jdbc.connections.internal.DriverManagerConnectionProviderImpl.getConnection(DriverManagerConnectionProviderImpl.java:214)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl$ConnectionProviderJdbcConnectionAccess.obtainConnection(JdbcServicesImpl.java:242)
at org.hibernate.engine.jdbc.internal.JdbcServicesImpl.configure(JdbcServicesImpl.java:117)
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 org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1840)
at com.hussi.model.Main.main(Main.java:15)
my Main class File :
package com.hussi.model;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class Main {
public static void main(String[] args)
{
User user = new User();
user.setUsername("hussi");
user.setPassword("maria");
SessionFactory sesionFactory = new Configuration().configure().buildSessionFactory() ;
Session session = sesionFactory.openSession();
Transaction tr = session.beginTransaction();
session.save(user);
session.flush();
session.close();
}
}
my model file
package com.hussi.model;
public class User
{
int user_id;
String username;
String password;
public int getUser_id() {
return user_id;
}
public void setUser_id(int user_id) {
this.user_id = user_id;
}
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;
}
public String toString()
{
return "username==>"+this.username+" : password==>"+this.password;
}
}
my user.hbm.xml file
<?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.hussi.model.User" table="users">
<id name="user_id" type="int" column="user_id">
<generator class="increment" />
</id>
<property name="username">
<column name="username"/>
</property>
<property name="password">
<column name="password"/>
</property>
</class>
</hibernate-mapping>
my hibernate 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:3306/my_hibernate_1</property>
<property name="connection.username">root</property>
<property name="connecttion.password">root</property>
<!-- Database connection settings -->
<property name="connection.pool_size">1</property>
<!-- MySql Dialect -->
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">false</property>
<mapping resource="user.hbm.xml"/>
</session-factory>
</hibernate-configuration>
You have given wrong url
below is correct one
jdbc:mysql://localhost:3306/my_hibernate_1
Just replaced jdbc.mysql with jdbc:mysql
Try changing the hibernate config connection.url property to jdbc:myql

Categories

Resources