In hibernate 5.4 version with Spring Boot 2.2.7. I am getting below exception.
Exception in thread "restartedMain" java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
Caused by: org.hibernate.PropertyAccessException: IllegalArgumentException occurred calling getter of <Project path>.models.Book.isbn
at org.hibernate.property.access.spi.GetterMethodImpl.get(GetterMethodImpl.java:65)
at org.hibernate.tuple.entity.AbstractEntityTuplizer.getIdentifier(AbstractEntityTuplizer.java:223)
at org.hibernate.persister.entity.AbstractEntityPersister.getIdentifier(AbstractEntityPersister.java:5119)
at org.hibernate.id.Assigned.generate(Assigned.java:31)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:115)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:194)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:179)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:75)
at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:102)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:626)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:619)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:614)
at com.vikas.projects.organicecommerce.jpahibernate.QueryExcecutableFile.test(QueryExcecutableFile.java:29)
at com.vikas.projects.organicecommerce.jpahibernate.OrganicEcommerceJpaHibernateApplication.main(OrganicEcommerceJpaHibernateApplication.java:21)
... 5 more
Caused by: java.lang.IllegalArgumentException: object is not an instance of declaring class
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.hibernate.property.access.spi.GetterMethodImpl.get(GetterMethodImpl.java:42)
I have checked other related link, but Im not able to link those with my use case.
I'm using below configuration and models to persist the Book object.
Book.java
package com.vikas.projects.organicecommerce.jpahibernate.models;
import java.math.BigDecimal;
import java.sql.Date;
import lombok.EqualsAndHashCode;
#EqualsAndHashCode
public class Book {
private String isbn;
private String name;
private Date publishdate;
private BigDecimal price;
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getPublishdate() {
return publishdate;
}
public void setPublishdate(Date publishdate) {
this.publishdate = publishdate;
}
public BigDecimal getPrice() {
return price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
}
book.hbm.xml
<hibernate-mapping>
<class name="...Book"
table="BOOK" lazy="false">
<id name="isbn">
<column name="ISBN" sql-type="varchar(13)" not-null="true" />
</id>
<property name="name">
<column name="NAME" sql-type="varchar(64)" not-null="true"
unique="true" />
</property>
<property name="publishdate">
<column name="PUBLISHDATE" sql-type="date" />
</property>
<property name="price">
<column name="PRICE" sql-type="decimal" precision="8"
scale="2" />
</property>
</class>
</hibernate-mapping>
hibernate.cfg.xml
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class"></property>
<property name="connection.url"></property>
<property name="connection.username"></property>
<property name="connection.password"></property>
<property name="hibernate.dialect"></property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping
resource=".../Book.hbm.xml" />
</session-factory>
</hibernate-configuration>
Method to persist this object
public void test() {
Book book = new Book();
book.setIsbn("1232424");
book.setName("BookName");
book.setPrice(new BigDecimal(23.00));
book.setPublishdate(Date.valueOf("2014-04-04"));
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
session.persist(book);
tx.commit();
session.close();
}
I'm using microsoft sql server. Please let me know if more details required.
Adding more details. From main function, I'm calling test(), via QueryExecutableFile's instance.
#SpringBootApplication
#EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
public class OrganicEcommerceJpaHibernateApplication {
public static void main(String[] args) {
SpringApplication.run(OrganicEcommerceJpaHibernateApplication.class, args);
QueryExcecutableFile queryExcecutableFile = new QueryExcecutableFile(getSessionFactory());
queryExcecutableFile.test();
}
public static SessionFactory getSessionFactory() {
Configuration configuration = new Configuration().configure("hibernate.cfg.xml");
ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
SessionFactory sessionFactory = configuration.buildSessionFactory();
return sessionFactory;
}
}
public class QueryExcecutableFile {
SessionFactory sessionFactory;
public QueryExcecutableFile(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public void test() {
Book book = new Book();
book.setIsbn("1232424");
book.setName("BookName");
book.setPrice(new BigDecimal(23.00));
book.setPublishdate(Date.valueOf("2014-04-04"));
Session session = sessionFactory.openSession();
Transaction tx = session.beginTransaction();
session.persist(book);
tx.commit();
session.close();
}
}
Related
I'm using XML mapping. I tried to make a many to many association between Invoice and Product (an invoice can contain many products and a product can belong to many invoices). My approach was to make an association called "InvoiceLine" that will contain a single product, its quantity and total and this InvoiceLine would belong to a single Invoice.
-An Invoice has many invoiceLines
-An InvoiceLine has many Products and has an attribute which is the Invoice Id that corresponds to the invoice
While searching for a way to make this mapping, I came to know that you can't make a many to many association with an extra column and that I need to make 2 one-to-many associations to replace that many-to-many association.
This is what I tried but I keep getting the error:
19359 [http-nio-8088-exec-3] ERROR org.hibernate.property.BasicPropertyAccessor - IllegalArgumentException in class: model.InvoiceLine, getter method of property: Product
org.hibernate.PropertyAccessException: IllegalArgumentException occurred calling getter of model.InvoiceLine.Product
at org.hibernate.property.BasicPropertyAccessor$BasicGetter.get(BasicPropertyAccessor.java:195)
at org.hibernate.tuple.component.AbstractComponentTuplizer.getPropertyValue(AbstractComponentTuplizer.java:87)
at org.hibernate.tuple.component.AbstractComponentTuplizer.getPropertyValues(AbstractComponentTuplizer.java:93)
at org.hibernate.tuple.component.PojoComponentTuplizer.getPropertyValues(PojoComponentTuplizer.java:109)
at org.hibernate.type.serComponentType.getPropertyValues(ComponentType.java:376)
at org.hibernate.type.ComponentType.getHashCode(ComponentType.java:207)
at org.hibernate.engine.EntityKey.generateHashCode(EntityKey.java:126)
at org.hibernate.engine.EntityKey.<init>(EntityKey.java:70)
at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:184)
at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:144)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:210)
at org.hibernate.event.def.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:56)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:195)
at org.hibernate.event.def.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:50)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:93)
at org.hibernate.impl.SessionImpl.fireSave(SessionImpl.java:562)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:550)
at org.hibernate.impl.SessionImpl.save(SessionImpl.java:546)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.hibernate.context.ThreadLocalSessionContext$TransactionProtectionWrapper.invoke(ThreadLocalSessionContext.java:342)
at com.sun.proxy.$Proxy5.save(Unknown Source)
at dao.GenericDaoHibernateImpl.add(GenericDaoHibernateImpl.java:49)
at dao.InvoiceLineDaoImpl.ajouter(InvoiceLineDaoImpl.java:12)
at services.InvoiceLineServiceImpl.ajouter(InvoiceLineServiceImpl.java:25)
at controller.InvoiceLineServlet.doPost(InvoiceLineServlet.java:123)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:528)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1100)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:687)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1520)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1476)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
Caused by: java.lang.IllegalArgumentException: object is not an instance of declaring class
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.hibernate.property.BasicPropertyAccessor$BasicGetter.get(BasicPropertyAccessor.java:169)
... 50 more
Here are my mapping classes, the association entity and the servlet.
InvoiceLine.hbm.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="model.InvoiceLine" table="INVOICE_LINE">
<composite-id name="id" class="model.InvoiceLine">
<key-many-to-one name="Product" entity-name="model.Product"
column="CODE_PRODUCT" />
<key-many-to-one name="Invoice" entity-name="model.Invoice"
column="ID_INVOICE"/>
</composite-id>
<property name="qte" column="quantity" />
<property name="total" column="TOTAL" />
</class>
</hibernate-mapping>
Product.hbm.xml:
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="model.Product" table="PRODUCT">
<meta attribute="class-description">
</meta>
<id name="codeProduct" column="CODE_PRODUCT">
<generator class="native"/>
</id>
<property name="name" column="NAME" />
<property name="description" column="DESCRIPTION" />
<property name="price" column="PRICE" />
<property name="quantityStock" column="QUANTITY_STOCK" />
<many-to-one name="category" class="model.category" fetch="select" update="true">
<column name="CODE_CATEGORY" not-null="true" />
</many-to-one>
<set name="invoiceline" table="INVOICE_LINE" inverse="true"
fetch="select" cascade="all">
<key>
<column name="CODE_PRODUCT" not-null="true" />
</key>
<one-to-many class="model.InvoiceLine" />
</set>
</class>
</hibernate-mapping>
Invoice.hbm.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="model.Invoice" table="INVOICE">
<meta attribute="class-description">
</meta>
<id name="id" column="ID_INVOICE">
<generator class="native"/>
</id>
<property name="date" column="DATE" />
<property name="total" column="TOTAL" />
<many-to-one name="client" class="model.Client" fetch="select" update="true">
<column name="ID_CLIENT" not-null="true" />
</many-to-one>
<set name="InvoiceLine" table="INVOICE_LINE" inverse="true"
fetch="select" cascade="all">
<key>
<column name="ID_INVOICE" not-null="true" />
</key>
<one-to-many class="model.InvoiceLine" />
</set>
</class>
</hibernate-mapping>
And this is the SERVLET
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
if ((request.getParameter("addInvoiceLine")) != null) {
RequestDispatcher dispatcher = request.getRequestDispatcher("/View/AddInvoiceLine.jsp");
dispatcher.forward(request, response);
//get the InvoiceId from a select list
String[] invoice = request.getParameterValues("invoice");
int codeInvoice = Integer.parseInt(invoice[0]);
//get the ProductId from a select list
String[] product= request.getParameterValues("product");
int codeProd = Integer.parseInt(product[0]);
//get the quantity from a textField and convert it to integer
String stringQuantity = request.getParameter("quantity");
int quantity= Integer.parseInt(stringQuantity);
InvoiceServiceImpl InvoiceService = new InvoiceServiceImpl();
Invoice invoice= invoiceService.return(codeInvoice);
ProductServiceImpl productService = new ProductServiceImpl();
Product product = productService.return(codeProd);
InvoiceLineServiceImpl invoiceLineServiceImpl = new InvoiceLineServiceImpl();
InvoiceLine invoiceLine= new InvoiceLine(quantity);
invoiceLine.setProduct(product);
invoiceLine.setInvoice(invoice);
invoiceLineServiceImpl.add(invoiceLine);
The line that throws the error is:
invoiceLineServiceImpl.add(invoiceLine);
the method add is inherited from this GenericDao:
package dao;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
#SuppressWarnings("unchecked")
public abstract class GenericDaoHibernateImpl<E, PK extends Serializable> implements GenericDao<E, PK> {
/**
* By defining this class as abstract, we prevent Spring from creating
* instance of this class If not defined as abstract,
* getClass().getGenericSuperClass() would return Object. There would be
* exception because Object class does not hava constructor with parameters.
*/
protected Class<? extends E> daoType;
public static SessionFactory sessionFactory;
#SuppressWarnings("rawtypes")
public GenericDaoHibernateImpl() {
Type t = getClass().getGenericSuperclass();
ParameterizedType pt = (ParameterizedType) t;
daoType = (Class) pt.getActualTypeArguments()[0];
}
static {
try {
sessionFactory = new Configuration().configure().buildSessionFactory();
} catch (Throwable t) {
t.printStackTrace();
}
}
public static SessionFactory getSession() {
return sessionFactory;
}
protected Session currentSession() {
return getSession().getCurrentSession();
}
#Override
public void add(E entity) {
currentSession().beginTransaction();
currentSession().save(entity);
currentSession().getTransaction().commit();
}
#Override
public void update(E entity) {
currentSession().beginTransaction();
currentSession().update(entity);
currentSession().getTransaction().commit();
}
#Override
public void remove(E entity) {
currentSession().beginTransaction();
// E oldEntity = (E) currentSession().l;
currentSession().delete(entity);
currentSession().getTransaction().commit();
}
#Override
public E find(PK key) {
currentSession().beginTransaction();
return (E) currentSession().get(daoType, key);
}
#Override
public List<E> getAll() {
currentSession().beginTransaction();
return currentSession().createCriteria(daoType).list();
}
}
Please note that the method add works perfectly for other entities like Product, so that got me thinking that the issue is with the xml mapping of InvoiceLineand not the java code
This is my InvoiceLine entity
package model;
import java.io.Serializable;
public class InvoiceLine implements Serializable{
private long id;
private double total;
public double getTotal() {
return total;
}
public void setTotal(double total) {
this.total = total;
}
public long getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
private Product product;
private Invoice invoice;
private int quantity;
public InvoiceLine() {
super();
}
public InvoiceLine(int quantity) {
super();
this.quantity= quantity;
}
public Product getProduct() {
return product;
}
public void setProduct(Product product) {
this.product = product;
}
public Invoice getInvoice() {
return invoice;
}
public void setInvoice(Invoice invoice) {
this.invoice= invoice;
}
public int getQuantity() {
return quantity;
}
public void setQuantity(int quantity) {
this.quantity= quantity;
}
}
Product entity
package model;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
public class Product implements Serializable{
private int codeProduct;
private String name;
private String description;
private Double price;
private int quantityStock;
private Category category;
private Set<InvoiceLine> invoiceLine= new HashSet<InvoiceLine>();
public Set<InvoiceLine> getInvoiceLine() {
return invoiceLine;
}
public void setInvoiceLine(Set<InvoiceLine> invoiceLine) {
this.invoiceLine= invoiceLine;
}
public Product() {
}
public Product(String name, String description, Double price, int quantityStock) {
this.name = name;
this.description = description;
this.price = price;
this.quantityStock = quantityStock;
}
// getters and setters
public int getCodeProduct() {
return codeProduct;
}
public void setCodeProduct(int codeProduct) {
this.codeProduct = codeProduct;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name= name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price= price;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
public int getQuantityStock() {
return quantityStock;
}
public void setQuantityStock(int quantityStock) {
this.quantityStock = quantityStock;
}
}
try using
<many-to-one name="category" class="model.Category" fetch="select" update="true"> in product.hbm.xml
and
<key-many-to-one name="product" entity-name="model.Product"
column="CODE_PRODUCT" />
in InvoiceLine.hbm.xml
I am not a frequent user of hibernate. I am trying to create Many-to-one mapping, but I get error (subj). I was looking for a mistakes in class declarations, also getter (last error), but everything seems to be correct. Does anyone see any mistakes in my code? Because I am not able to figuew out.
Adres.java
package beans;
public class Adres {
int id;
String adresas;
String adname;
public Adres() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getAdresas() {
return adresas;
}
public void setAdresas(String adresas) {
this.adresas = adresas;
}
public String getAdname() {
return adname;
}
public void setAdname(String adname) {
this.adname = adname;
}
}
Men.java
package beans;
public class Men {
int id;
String name;
Adres adres;
public Men() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Adres getAdd() {
return adres;
}
public void setAdd(Adres adres) {
this.adres = adres;
}
}
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.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/db2</property>
<property name="hibernate.connection.username">user</property>
<property name="hibernate.connection.password">pass</property>
<property name="hibernate.show_sql">true</property>
<mapping resource="hbm/Men.hbm.xml"/>
<mapping resource="hbm/Adres.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Men.hbm.xml
<hibernate-mapping>
<class name="beans.Men" table="MEN">
<id column="id" name="id" type="int">
<generator class="native"/>
</id>
<property column="name" name="name" type="string"/>
<many-to-one class="beans.Adres" column="adres" name="adres" not-null="true"/>
</class>
</hibernate-mapping>
Adres.bbm.xml
<hibernate-mapping>
<class name="beans.Adres" table="ADRES">
<id name="id" type="int" column="id">
<generator class="native"/>
</id>
<property name="adresas" column="adresas" type="string"/>
<property name="adname" column="adname" type="string"/>
</class>
</hibernate-mapping>
Main.java
private static SessionFactory factory;
public static void main(String[] args) {
try {
factory = new Configuration().configure().buildSessionFactory();
} catch (Throwable ex) {
System.err.println("Failed to create sessionFactory object." + ex);
throw new ExceptionInInitializerError(ex);
}
}
Error log
Initial SessionFactory creation failed.org.hibernate.MappingException: Could not get constructor for org.hibernate.persister.entity.SingleTableEntityPersister
Exception in thread "main" java.lang.ExceptionInInitializerError
at main.HibernateUtil.<clinit>(HibernateUtil.java:15)
at main.Main.main(Main.java:17)
Caused by: org.hibernate.MappingException: Could not get constructor for org.hibernate.persister.entity.SingleTableEntityPersister
at org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:123)
at org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:77)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:346)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:444)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:708)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:724)
at main.HibernateUtil.<clinit>(HibernateUtil.java:12)
... 1 more
Caused by: org.hibernate.HibernateException: Unable to instantiate default tuplizer [org.hibernate.tuple.entity.PojoEntityTuplizer]
at org.hibernate.tuple.entity.EntityTuplizerFactory.constructTuplizer(EntityTuplizerFactory.java:91)
at org.hibernate.tuple.entity.EntityTuplizerFactory.constructDefaultTuplizer(EntityTuplizerFactory.java:116)
at org.hibernate.tuple.entity.EntityMetamodel.<init>(EntityMetamodel.java:388)
at org.hibernate.persister.entity.AbstractEntityPersister.<init>(AbstractEntityPersister.java:508)
at org.hibernate.persister.entity.SingleTableEntityPersister.<init>(SingleTableEntityPersister.java:124)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
at org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:96)
... 7 more
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:422)
at org.hibernate.tuple.entity.EntityTuplizerFactory.constructTuplizer(EntityTuplizerFactory.java:88)
... 16 more
Caused by: org.hibernate.PropertyNotFoundException: Could not locate getter method for property [beans.Men#adres]
at org.hibernate.internal.util.ReflectHelper.findGetterMethod(ReflectHelper.java:400)
at org.hibernate.property.access.internal.PropertyAccessBasicImpl.<init>(PropertyAccessBasicImpl.java:41)
at org.hibernate.property.access.internal.PropertyAccessStrategyBasicImpl.buildPropertyAccess(PropertyAccessStrategyBasicImpl.java:27)
at org.hibernate.mapping.Property.getGetter(Property.java:299)
at org.hibernate.tuple.entity.PojoEntityTuplizer.buildPropertyGetter(PojoEntityTuplizer.java:270)
at org.hibernate.tuple.entity.AbstractEntityTuplizer.<init>(AbstractEntityTuplizer.java:145)
at org.hibernate.tuple.entity.PojoEntityTuplizer.<init>(PojoEntityTuplizer.java:63)
... 21 more
You should change your getter and setter for adres property in Men class from
public Adres getAdd() {
return adres;
}
public void setAdd(Adres adres) {
this.adres = adres;
}
to
public Adres getAdres() {
return adres;
}
public void setAdres(Adres adres) {
this.adres = adres;
}
I suggest to give a meaningful variable names and related getters, setters!
I've read multiple posts about NoClassDefFoundError but didn't find satisfying answer.
I've started learning hibernate. I have written simple application to persist Movie object in my db.
I successfuly compiled my code with
javac -classpath ~/cp/hibernate-release-5.0.1.Final/lib/required/hibernate-core-5.0.1.Final.jar -d classes justhibernate/BasicMovieManager.java justhibernate/Movie.java
However when i'm trying to run my code with
java -classpath ./:~/cp/hibernate-release-5.0.1.Final/lib/required/hibernate-core-5.0.1.Final.jar:./classes/ justhibernate.BasicMovieManager
I'm encountering error
Error: A JNI error has occurred, please check your installation and try again
Exception in thread "main" java.lang.NoClassDefFoundError: org/hibernate/service/ServiceRegistry
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)
at java.lang.Class.privateGetMethodRecursive(Class.java:3048)
at java.lang.Class.getMethod0(Class.java:3018)
at java.lang.Class.getMethod(Class.java:1784)
at sun.launcher.LauncherHelper.validateMainClass(LauncherHelper.java:544)
at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:526)
Caused by: java.lang.ClassNotFoundException: org.hibernate.service.ServiceRegistry
at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 7 more
I have hibernate.cfg.xml and Movie.hbm.xml files in ./ directory. Here's my code:
BasicMovieManager.java
package justhibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.MetadataSources;
public class BasicMovieManager
{
private SessionFactory sessionFactory = null;
private void setUp() throws Exception
{
final StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
.configure()
.build();
try
{
sessionFactory = new MetadataSources( registry )
.buildMetadata().buildSessionFactory();
}
catch (Exception e)
{
StandardServiceRegistryBuilder.destroy( registry );
}
}
private void persistMovie(Movie movie)
{
if(sessionFactory == null)
{
try {setUp();}
catch(Exception e){e.printStackTrace();}
}
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(movie);
session.getTransaction().commit();
session.close();
}
public static void main(String[] args)
{
BasicMovieManager bmm = new BasicMovieManager();
Movie m = new Movie();
m.setId(2);
m.setTitle("Harry Potter and the Chamber of Secrets");
m.setDirector("Steve Kloves");
m.setSynopsis("2nd part od thunder-face magician");
bmm.persistMovie(m);
}
}
Movie.java
package justhibernate;
public class Movie
{
private int id = 0;
private String title = null;
private String synopsis = null;
private String director = null;
public void setId(int id)
{
this.id = id;
}
public int getId()
{
return id;
}
public void setTitle(String title)
{
this.title = title;
}
public String getTitle()
{
return title;
}
public void setSynopsis(String synopsis)
{
this.synopsis = synopsis;
}
public String getSynopsis()
{
return synopsis;
}
public void setDirector(String director)
{
this.director = director;
}
public String getDirector()
{
return director;
}
}
hibernate.cfg.xml
<hibernate-configuration>
<session-factory>
<property name="connection.url">
jdbc:mysql://localhost:3306/test
</property>
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="connection.username">
user
</property>
<property name="connection.password">
password
</property>
<property name="dialect">
org.hibernate.dialect.MySQL5Dialect
</property>
<mapping resource="Movie.hbm.xml" />
</session-factory>
</hibernate-configuration>
Movie.hbm.xml
<hibernate-mapping>
<class name="justhibernate.Movie" table="MOVIES">
<id name="id" column="ID">
<generator class="native" />
</id>
<property name="title" column="TITLE" />
<property name="director" column="DIRECTOR" />
<property name="synopsis" column="SYNOPSIS" />
</class>
</hibernate-mapping>
Looks like it's caused by relative (starts with home symbol ~) path to Hibernate library. I tried to run you code with absolute path and it successfully found Hibernate. But note that your code won't run without specifying paths to MySQL JDBC, JBoss logging and other required libraries, full list is here.
This is my first time trying out Hibernate with Eclipse and the following are the things I did:
Created a Java Bean called Student.java which is as follows:
package com.jwt.hibernate;
public class Student {
private long id;
private String name;
private String degree;
private String roll;
private String phone;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDegree() {
return degree;
}
public void setDegree(String degree) {
this.degree = degree;
}
public String getRoll() {
return roll;
}
public void setRoll(String roll) {
this.roll = roll;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
Created a mapping file, Student.hbm.xml as follows:
<hibernate-mapping>
<class name="com.jwt.hibernate.Student" table="student">
<id column="ID" name="id" type="long" />
<property column="name" name="name" type="string" />
<property column="degree" name="degree" type="string" />
<property column="roll" name="roll" type="string" />
<property column="phone" name="phone" type="string" />
</class>
</hibernate-mapping>
3. Created the hibernate configuration file, hibernate.cfg.xml as follows:
<?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.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernatetutorial</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hbm2ddl.auto">create </property>
<mapping resource="com/jwt/hibernate/Student.hbm.xml" />
</session-factory>
</hibernate-configuration>
Created the class SimpleTest.java which is as follows:
package com.jwt.hibernate;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class SimpleTest {
public static void main(String[] args) {
Configuration cfg = new Configuration();
cfg.configure("hibernate.cfg.xml");
SessionFactory factory = cfg.buildSessionFactory();
Session session = factory.openSession();
Student student = new Student();
student.setName("Mukesh");
student.setRoll("101");
student.setPhone("8888");
student.setDegree("B.E");
Transaction tx = session.beginTransaction();
session.save(student);
System.out.println("Object saved successfully.....!!");
tx.commit();
session.close();
factory.close();
}
}
Now, when I try to run SimpleTest, I get the following error:
**INFO: HHH000412: Hibernate Core {4.3.7.Final}
Exception in thread "main" java.lang.ExceptionInInitializerError
at org.hibernate.cfg.Configuration.reset(Configuration.java:326)
at org.hibernate.cfg.Configuration.<init>(Configuration.java:291)
at org.hibernate.cfg.Configuration.<init>(Configuration.java:295)
at com.jwt.hibernate.SimpleTest.main(SimpleTest.java:11)
Caused by: java.lang.NullPointerException
at org.hibernate.internal.util.ConfigHelper.getResourceAsStream(ConfigHelper.java:170)
at org.hibernate.cfg.Environment.<clinit>(Environment.java:221)
... 4 more**
I double checked and made sure that all the configuration and jar files were added to the classpath. So that is not the problem. I would really appreciate some insights as to what may have caused this problem and inturn, how to solve it.
Thanks in advance!
I would recommend updating to later version of SLF4J.
Or
Your Hibernate.cfg.xml is not on classpath. What folder is it in?
Edit :
Caused by: java.lang.NullPointerException
at org.hibernate.internal.util.ConfigHelper.getResourceAsStream(ConfigHelper.java:170)
This is actual exception in your code, If your Hibernate.cfg.xml is loaded then check for SELF4J version, Don't use user library to take your jar files, put all libraries in your lib folder and then configure those in class path.
You may find a Java Configuration of Hibernate to be more friendly. Here is an example of one that I did (Note: there are Spring annotations like #Autowired and #PostConstruct in this class so don't get confused):
public class HibernateConfigBean {
private static final Logger logger = Logger.getLogger(HibernateConfigBean.class);
#Autowired private Environment environment;
private SessionFactory sessionFactory;
private Configuration configuration;
#PostConstruct
private void init(){
configuration = new Configuration();
configuration.setProperty("hibernate.dialect", environment.getProperty("hibernate.dialect"));
configuration.setProperty("hibernate.connection.driver_class", environment.getProperty("hibernate.connection.driver_class"));
configuration.setProperty("hibernate.connection.url", environment.getProperty("hibernate.connection.url"));
configuration.setProperty("hibernate.connection.username", environment.getProperty("db_username"));
configuration.setProperty("hibernate.connection.password", environment.getProperty("db_password"));
//Add additional Annotated Classes here
configuration.addAnnotatedClass(UserEntity.class);
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
sessionFactory = configuration.buildSessionFactory(builder.build());
}
public SessionFactory getSessionFactory(){
return sessionFactory;
}
//This should be visible outside of the package as it's only used by the GenerateDbSchema class
void generateSchema() throws Exception {
try{
new SchemaExport(configuration).create(false, true);
} catch (RuntimeException re){
throw new Exception(re);
}
}
}
Then I just put my values into a properties file :-)
I'm using myeclipse IDE
After executing my code i'm getting the below Exception
log4j:WARN No appenders could be found for logger
(org.hibernate.cfg.Environment).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "main" org.hibernate.MappingException: Unknown entity:info.inetsolv.Emp
at org.hibernate.impl.SessionFactoryImpl.getEntityPersister
(SessionFactoryImpl.java:628)
at org.hibernate.impl.SessionImpl.getEntityPersister
(SessionImpl.java:1366)
at org.hibernate.engine.ForeignKeys.isTransient(ForeignKeys.java:203)
at org.hibernate.event.def.AbstractSaveEventListener.getEntityState
(AbstractSaveEventListener.java:535)
at org.hibernate.event.def.DefaultPersistEventListener.onPersist
(DefaultPersistEventListener.java:93)
at org.hibernate.event.def.DefaultPersistEventListener.onPersist
(DefaultPersistEventListener.java:61)
at org.hibernate.impl.SessionImpl.firePersist(SessionImpl.java:646)
at org.hibernate.impl.SessionImpl.persist(SessionImpl.java:620)
at org.hibernate.impl.SessionImpl.persist(SessionImpl.java:624)
at info.inetsolv.InsertEmprecord.main(InsertEmprecord.java:22)
POJO CLASS
package info.inetsolv;
#SuppressWarnings("serial")
public class Emp implements java.io.Serializable {
// Fields
private Integer eno;
private String name;
private Double salary;
// Constructors
/** default constructor */
public Emp() {
}
/** minimal constructor */
public Emp(Integer eno) {
this.eno = eno;
}
/** full constructor */
public Emp(Integer eno, String name, Double salary) {
this.eno = eno;
this.name = name;
this.salary = salary;
}
// Property accessors
public Integer getEno() {
return this.eno;
}
public void setEno(Integer eno) {
this.eno = eno;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public Double getSalary() {
return this.salary;
}
public void setSalary(Double salary) {
this.salary = salary;
}
}
HibernateSessionFactory.java
package info.inetsolv;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
public class HibernateSessionFactory {
private static final ThreadLocal<Session> threadLocal = new
ThreadLocal<Session>();
private static org.hibernate.SessionFactory sessionFactory;
private static Configuration configuration = new Configuration();
private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";
private static String configFile = CONFIG_FILE_LOCATION;
static {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
private HibernateSessionFactory() {
}
public static Session getSession() throws HibernateException {
Session session = (Session) threadLocal.get();
if (session == null || !session.isOpen()) {
if (sessionFactory == null) {
rebuildSessionFactory();
}
session = (sessionFactory != null) ? sessionFactory.openSession(): null;
threadLocal.set(session);
}
return session;
}
public static void rebuildSessionFactory() {
try {
configuration.configure(configFile);
sessionFactory = configuration.buildSessionFactory();
} catch (Exception e) {
System.err.println("%%%% Error Creating SessionFactory %%%%");
e.printStackTrace();
}
}
public static void closeSession() throws HibernateException {
Session session = (Session) threadLocal.get();
threadLocal.set(null);
if (session != null) {
session.close();
}
}
public static org.hibernate.SessionFactory getSessionFactory() {
return sessionFactory;
}
public static void setConfigFile(String configFile) {
HibernateSessionFactory.configFile = configFile;
sessionFactory = null;
}
public static Configuration getConfiguration() {
return configuration;
}
}
client program to insert record into DB
InsertEmprecord.java
package info.inetsolv;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
public class InsertEmprecord {
public static void main(String[] args) {
Configuration cfg = new Configuration();
cfg.configure();
SessionFactory sf = cfg.buildSessionFactory();
Session hsession = sf.openSession();
Transaction tx = hsession.beginTransaction();
Emp e = new Emp();
e.setEno(6);
e.setName("six");
e.setSalary(1234d);
hsession.persist(e);
tx.commit();
hsession.close();
sf.close();
}
}
And below is my hibernate mapping file
Emp.hbm.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD
3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="info.inetsolv.Emp" table="EMP" schema="HIB">
<id name="eno" type="java.lang.Integer">
<column name="ENO" precision="5" scale="0" />
<generator class="assigned" />
</id>
<property name="name" type="java.lang.String">
<column name="NAME" length="10" />
</property>
<property name="salary" type="java.lang.Double">
<column name="SALARY" precision="10" />
</property>
</class>
</hibernate-mapping>
AND below is 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://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>
<session-factory>
<property name="dialect">
org.hibernate.dialect.Oracle9Dialect
</property>
<property name="connection.url">
jdbc:oracle:thin:#localhost:1521:xe
</property>
<property name="connection.username">hib</property>
<property name="connection.password">abc</property>
<property name="connection.driver_class">
oracle.jdbc.driver.OracleDriver
</property>
<property name="myeclipse.connection.profile">
my oracle drive
</property>
<property name="show_sql">true</property>
</session-factory>
</hibernate-configuration>
You didn't configure mapping for the object Emp. The configuration file hibernate.cfg.xml should contain the mapping to the resource Emp.hbm.xml.
<mapping resource="info/inetsolv/Emp.hbm.xml"/>
I had similar problem for a simple Console application trying to use Hibernate. The solution I arrived to make the add the "packagesToScan" property explicitly for LocalSessionFactoryBean.
<bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="com.mg.learning.spring.orm"/> <--- this SOLVED!
<property name="hibernateProperties">
<props>
<prop key="dialect">org.hibernate.dialect.MySQL5Dialect</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
</props>
</property>
</bean>
#Sandhu Santakumar , answer is absolutely right.
Just adding the reason behind this.
By default the JBoss hibernate reverse engineering tool maps class inside the mapping tab but resource attribute is the required attribute that hibernate.cfg.xml should have.
class attribute is optional.
e.g. if your mapping is like this
resource is mandatory attribute and class is optional attribute.
Hope this additional information helps.