org.hibernate.AnnotationException - Use of @OneToMany or @ManyToMany targeting an unmapped class

I am new to hibernate and I want to use it on a swing application. However I keep getting this:

Exception in thread "AWT-EventQueue-0" org.hibernate.AnnotationException: Use of @OneToMany or @ManyToMany targeting an unmapped class: store.management.models.Invoice.sales[store.management.models.Sales]

Here is my code.
Entity Classes

import java.util.Date;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Temporal;

@Entity
@Table(name="Invoice")
public class Invoice implements java.io.Serializable{
    @Id
    @Column(name="invoiceNumber")
    private int invoiceNumber;
    @Column(name="invoiceDate")
    @Temporal(javax.persistence.TemporalType.DATE)
    private Date invoiceDate;
    @Column(name="totalPrice")
    private double totalPrice;
    @OneToMany(mappedBy="invoice")
    private Set<Sales> sales;
    
    public Invoice(){}
    
    public Invoice(int invoiceNumber){
        this.invoiceNumber = invoiceNumber;
    }

    /**
     * @return the invoiceNumber
     */
    public int getInvoiceNumber() {
        return invoiceNumber;
    }

    /**
     * @param invoiceNumber the invoiceNumber to set
     */
    public void setInvoiceNumber(int invoiceNumber) {
        this.invoiceNumber = invoiceNumber;
    }

    /**
     * @return the invoiceDate
     */
    public Date getInvoiceDate() {
        return invoiceDate;
    }

    /**
     * @param invoiceDate the invoiceDate to set
     */
    public void setInvoiceDate(Date invoiceDate) {
        this.invoiceDate = invoiceDate;
    }

    /**
     * @return the totalPrice
     */
    public double getTotalPrice() {
        return totalPrice;
    }

    /**
     * @param totalPrice the totalPrice to set
     */
    public void setTotalPrice(double totalPrice) {
        this.totalPrice = totalPrice;
    }

    /**
     * @return the sales
     */
    public Set<Sales> getSales() {
        return sales;
    }

    /**
     * @param sales the sales to set
     */
    public void setSales(Set<Sales> sales) {
        this.sales = sales;
    }
    
}

package store.management.models;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;

public class Sales {
    @Id
    @GeneratedValue
    @Column(name="salesId")
    private Integer salesId;
    @JoinColumn(name="invoiceNumber")
    @ManyToOne(cascade=CascadeType.ALL)
    private Invoice invoice;
    @Column(name="productId")
    private String productId;
    @Column(name="description")
    private String desciption;
    @Column(name="quantity")
    private int quantity;
    
    public Sales(){}

    /**
     * @return the salesId
     */
    public Integer getSalesId() {
        return salesId;
    }

    /**
     * @param salesId the salesId to set
     */
    public void setSalesId(Integer salesId) {
        this.salesId = salesId;
    }

    /**
     * @return the desciption
     */
    public String getDesciption() {
        return desciption;
    }

    /**
     * @param description the desciption to set
     */
    public void setDescription(String description) {
        this.desciption = description;
    }

    /**
     * @return the quantity
     */
    public int getQuantity() {
        return quantity;
    }

    /**
     * @param quantity the quantity to set
     */
    public void setQuantity(int quantity) {
        this.quantity = quantity;
    }

    /**
     * @return the productId
     */
    public String getProductId() {
        return productId;
    }

    /**
     * @param productId the productId to set
     */
    public void setProductId(String productId) {
        this.productId = productId;
    }

    /**
     * @return the invoice
     */
    public Invoice getInvoice() {
        return invoice;
    }

    /**
     * @param invoice the invoice to set
     */
    public void setInvoice(Invoice invoice) {
        this.invoice = invoice;
    }
    
}


package store.management.models;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="Product")
public class Product implements java.io.Serializable{
    
    @Id
    @Column(name="productId")
    private String productId;
    @Column(name="productName")
    private String productName;
    @Column(name="sellingPrice")
    private double sellingPrice;
    @Column(name="costPrice")
    private double costPrice;
    @Column(name="quantityAvailable")
    private int quantityAvailable;
    
    public Product(){}
    
    public Product(String productNumber){
        this.productId = productNumber;
    }
    
    public Product(String productId, String productName, double sellingPrice, double costPrice, int quantityAvailable){
        this.productId = productId;
        this.productName = productName;
        this.sellingPrice = sellingPrice;
        this.costPrice = costPrice;
        this.quantityAvailable = quantityAvailable;
    }

    /**
     * @return the productId
     */
    public String getProductId() {
        return productId;
    }

    /**
     * @param productId the productId to set
     */
    public void setProductId(String productId) {
        this.productId = productId;
    }

    /**
     * @return the productName
     */
    public String getProductName() {
        return productName;
    }

    /**
     * @param productName the productName to set
     */
    public void setProductName(String productName) {
        this.productName = productName;
    }

    /**
     * @return the sellingPrice
     */
    public double getSellingPrice() {
        return sellingPrice;
    }

    /**
     * @param sellingPrice the sellingPrice to set
     */
    public void setSellingPrice(double sellingPrice) {
        this.sellingPrice = sellingPrice;
    }

    /**
     * @return the costPrice
     */
    public double getCostPrice() {
        return costPrice;
    }

    /**
     * @param costPrice the costPrice to set
     */
    public void setCostPrice(double costPrice) {
        this.costPrice = costPrice;
    }

    /**
     * @return the quantityAvailable
     */
    public int getQuantityAvailable() {
        return quantityAvailable;
    }

    /**
     * @param quantityAvailable the quantityAvailable to set
     */
    public void setQuantityAvailable(int quantityAvailable) {
        this.quantityAvailable = quantityAvailable;
    }
    
}

TransactionHandlerClass

package store.management.db_service;

import java.util.Map;
import java.util.Set;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import store.management.models.*;


public class PurchaseTransaction {
    private SessionFactory getSessionFactory(){
        SessionFactory sessionFactory = new Configuration().configure()
                .addAnnotatedClass(Invoice.class)
                .addAnnotatedClass(Sales.class)
                .addAnnotatedClass(Product.class)
                .buildSessionFactory();
        return sessionFactory;
    }
    public void manageTransaction(Invoice invoice, Set<Sales> sales, Map<String, Product> products){
        Session session = getSessionFactory().openSession();
        Transaction tx = null;
        try{
            tx = session.beginTransaction();
            session.save(invoice);
            sales.stream().forEach((sale) -> {
                Product product = products.get(sale.getProductId());
                int newQunatity = product.getQuantityAvailable() - sale.getQuantity();
                product.setQuantityAvailable(newQunatity);
                session.save(sale);
                session.update(product);
            });
            tx.commit();
        }catch(HibernateException e){
            if(tx != null){
                tx.rollback();
            }
            System.err.println("Hibernate Error: "+ e);
        }finally{
            session.close();
        }
    }
}

Hibernate Config

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
  <session-factory>
    <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/niit</property>
    <property name="hibernate.connection.username">root</property>
    <property name="hibernate.connection.password">anderson</property>
    <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
    <property name="hibernate.show_sql">true</property>
    <property name="hibernate.hbm2ddl.auto">update</property>
    <mapping class="store.management.models.Invoice"/>
    <mapping class="store.management.models.Sales"/>
  </session-factory>
</hibernate-configuration>

Stacktrace

Exception in thread "AWT-EventQueue-0" org.hibernate.AnnotationException: Use of @OneToMany or @ManyToMany targeting an unmapped class: store.management.models.Invoice.sales[store.management.models.Sales]
	at org.hibernate.cfg.annotations.CollectionBinder.bindManyToManySecondPass(CollectionBinder.java:1134)
	at org.hibernate.cfg.annotations.CollectionBinder.bindStarToManySecondPass(CollectionBinder.java:793)
	at org.hibernate.cfg.annotations.CollectionBinder$1.secondPass(CollectionBinder.java:728)
	at org.hibernate.cfg.CollectionSecondPass.doSecondPass(CollectionSecondPass.java:70)
	at org.hibernate.cfg.Configuration.originalSecondPassCompile(Configuration.java:1695)
	at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1424)
	at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1844)
	at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1928)
	at store.management.db_service.ProductHandler.getSessionFactory(ProductHandler.java:26)
	at store.management.db_service.ProductHandler.getProducts(ProductHandler.java:63)
	at store.management.controller.Generator.getTemporyProductStore(Generator.java:24)
	at store.management.view.CashierServiceScreen.loadProducts(CashierServiceScreen.java:29)
	at store.management.view.CashierServiceScreen.initComponents(CashierServiceScreen.java:145)
	at store.management.view.CashierServiceScreen.<init>(CashierServiceScreen.java:25)
	at store.management.view.CashierServiceScreen$8.run(CashierServiceScreen.java:505)
	at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
	at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756)
	at java.awt.EventQueue.access$500(EventQueue.java:97)
	at java.awt.EventQueue$3.run(EventQueue.java:709)
	at java.awt.EventQueue$3.run(EventQueue.java:703)
	at java.security.AccessController.doPrivileged(Native Method)
	at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:80)
	at java.awt.EventQueue.dispatchEvent(EventQueue.java:726)
	at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
	at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
	at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
	at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

Please help me me, I have very little knowledge of hibernate at the moment

You forgot the @Entity annotation on the Sales class.

Instead of this:

public class Sales {
...

do this:

@Entity
@Table(name="Sales")
public class Sales {
...

Thank you. It works fine now. Can’t believed I forgot that part:rofl:

You might get the same error even if your class is all correct - you might have forgotten to register it in persistence.xml file as class element…

1 Like

Thank you Maris.
I had the same issue, I have forgotten to register my Entity in persistence.xml file.