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

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.

Related

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:

Hibernate Mapping Exception : Unknown entity: org.hibernate.test.akashtest.UserDetails

Mapping classes <mapping class="org.hibernate.test.akashtest.UserDetails"/>.
The configuration file is not able to pick the UserDetails class.
Added Annotation Class in configuration, packages location as well.
How can I fix this?
Code:
package org.hibernate.test.akashtest;
import java.lang.annotation.Annotation;
import javax.persistence.*;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.fasterxml.classmate.AnnotationConfiguration;
import com.fasterxml.classmate.AnnotationInclusion;
public class hibernate_1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
UserDetails user=new UserDetails();
user.setuserId(1);
user.setuserName("First User");
SessionFactory sessionFactory= new Configuration().addAnnotatedClass(org.hibernate.test.akashtest.UserDetails.class).configure("/org/hibernate/test/akashtest/hibernate.cfg.xml").buildSessionFactory();
Session session=sessionFactory.openSession();
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
}
}
/// My hibernate.cfg.xml
<!--
~ 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 SYSTEM
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration
>
<session-factory>
<!-- Database connection settings -->
<property name="connection.driver_class">org.postgresql.Driver</property>
<property name="connection.url">jdbc:postgresql://localhost:5432/hibernatedb</property>
<property name="connection.username">postgres</property>
<property name="connection.password">akash5758</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</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>
<mapping package="org.hibernate.test.akashtest"/>
<mapping class="org.hibernate.test.akashtest.UserDetails"/> /*MAPPING CLASS*/
</session-factory>
</hibernate-configuration>
/// My UserDetails.java
package org.hibernate.test.akashtest;
public class UserDetails {
private int userId;
private String userName;
public int getUserId()
{
return userId;
}
public void setuserId(int userId)
{
this.userId=userId;
}
public String getuserName()
{
return userName;
}
public void setuserName(String userName)
{
this.userName=userName;
}
}
You have to add #Entity annotation in your UserDetails class.

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 ?

Hibernate PreUpdateEventListener doesn`t work

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

org.hibernate.HibernateException: two open sessions

I am newbie in hibernate technology and I am struggling with the following exception:
org.hibernate.HibernateException: Illegal attempt to associate a
collection with two open sessions
I get this when I try to make a new line into my DB.
My setting/code:
<?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>
<!-- Paramètres de connexion à la base de données -->
<!-- <property name="connection.driver_class">com.mysql.jdbc.Driver</property> -->
<!-- <property name="connection.url">jdbc:mysql://localhost:3306/bh</property> -->
<!-- <property name="connection.username">root</property> -->
<!-- <property name="connection.password"></property> -->
<!-- <property name="dialect">org.hibernate.dialect.MySQLDialect</property> -->
<property name="connection.driver_class">org.postgresql.Driver</property>
<property name="connection.url">jdbc:postgresql://localhost:5432/projetForum</property>
<property name="connection.username">postgres</property>
<property name="connection.password">esct</property>
<property name="dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<!-- Comportement pour la conservation des tables -->
<property name="hbm2ddl.auto">update</property>
<!-- Activation : affichage en console, commentées et formatées -->
<property name="show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<property name="use_sql_comments">true</property>
<!-- Fichiers à mapper -->
<mapping class="com.forum.beans.Utilisateur" />
<mapping class="com.forum.beans.Topic" />
<mapping class="com.forum.beans.Post" />
</session-factory>
</hibernate-configuration>
A session holder:
package com.forum.utils;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
public class HibernateUtils {
private static final SessionFactory sessionFactory;
// Crée une unique instance de la SessionFactory à partir de
// hibernate.cfg.xml
static {
try {
sessionFactory = new AnnotationConfiguration().configure()
.buildSessionFactory();
} catch (HibernateException ex) {
throw new RuntimeException("Problème de configuration : "
+ ex.getMessage(), ex);
}
}
// Renvoie une session Hibernate
public static Session getSession() throws HibernateException {
return sessionFactory.openSession();
}
}
Code that causes the error :
Transaction tx = null;
try {
s = HibernateUtils.getSession();
tx = s.beginTransaction();
s.persist(u);
tx.commit();
} catch (Exception e) {
if (tx != null)
tx.rollback();
System.out.println(e);
}
Welcome to Hibernate, what I can see from your code:
Instead of using
openSession()
try
getSession()
Similar issue solved at URL

Categories

Resources