Eugene Yu
Eugene Yu

Reputation: 3958

(JPA) cannot implement Many to One relationship properly with hibernate.hbm2ddl.auto

I was trying to build a small project using JPA & EJB but I am already stuck in a very early stage....

Here's the issue.

I have three entities - Customer - Item - Rental

And as you can derive from the names, Customer-Rental(Many to One) and Item-Rental(Many to One). So the Rental entity stores the Ids of Customer and Item entities as Foreign Key.

I implemented this by using hibernate.hbm2ddl.auto property in the persistence.xml

    <persistence-unit name="JPADB">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <jta-data-source>java:/MySQLDS</jta-data-source>
        <exclude-unlisted-classes>false</exclude-unlisted-classes> 
        <properties>
            <property name="hibernate.archive.autodetection" value="class" />
            <property name="hibernate.format_sql" value="true" />
            <property name="showSql" value="true" />
            <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
            <property name="hibernate.hbm2ddl.auto" value="update" />
        </properties>
    </persistence-unit>
</persistence>

Customer

@Entity
public class Customer implements Serializable{
    private static final long serialVersionUID = 1L;
    public Customer() {super();}

    @Id
    @Column(name = "customer_id")
    @GeneratedValue
    private int customerId;
    @Column(name = "customer_name")
    private String customerName;
    @OneToMany(targetEntity=Rental.class, mappedBy="customer", cascade=CascadeType.ALL, fetch=FetchType.EAGER)
    private List<Rental> rentals;

Item

@Entity
public class Item implements Serializable{
    private static final long serialVersionUID = 1L;
    public Item() {super();}

    @Id
    @Column(name = "item_id")
    @GeneratedValue
    private int itemId;
    @Column(name = "item_name")
    private String itemName;
    @OneToMany(targetEntity=Rental.class, mappedBy="item", cascade=CascadeType.ALL, fetch=FetchType.EAGER)
    private List<Rental> rentals;

Rental

@Entity
public class Rental implements Serializable{
    private static final long serialVersionUID = 1L;
    public Rental(){super();}

    @Id
    @Column(name = "rental_id")
    @GeneratedValue
    private int rentalId;
    private String rentalName;
    @ManyToOne(targetEntity = Customer.class)
    @JoinColumn(name="customer_id", nullable = false)
    private Customer customer;
    @ManyToOne(targetEntity = Item.class)
    @JoinColumn(name="item_id", nullable = false)
    private Item item;

And I test it with the code below

@Override
    public void saveCustomer(Customer customer) {
        if(entityManager.contains(customer))
            entityManager.merge(customer);
        else
            entityManager.persist(customer);
    }

The code works fine only if I get rid of relationship between Customer and Rent entity, which is one-to-many by blocking codes that referring private List rentals in Customer entity. If I try this it gives me this error

log4j:WARN No appenders could be found for logger (org.jboss.logging).
log4j:WARN Please initialize the log4j system properly.
Exception in thread "main" java.lang.reflect.UndeclaredThrowableException
    at com.sun.proxy.$Proxy0.retrieveAllItems(Unknown Source)
    at com.hidvd.client.HiDVDApplicationClient.main(HiDVDApplicationClient.java:28)
Caused by: java.lang.ClassNotFoundException: org.hibernate.collection.internal.PersistentBag
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Unknown Source)
    at org.jboss.marshalling.AbstractClassResolver.loadClass(AbstractClassResolver.java:135)
    at org.jboss.marshalling.AbstractClassResolver.resolveClass(AbstractClassResolver.java:116)
    at org.jboss.marshalling.river.RiverUnmarshaller.doReadClassDescriptor(RiverUnmarshaller.java:892)
    at org.jboss.marshalling.river.RiverUnmarshaller.doReadNewObject(RiverUnmarshaller.java:1204)
    at org.jboss.marshalling.river.RiverUnmarshaller.doReadObject(RiverUnmarshaller.java:272)
    at org.jboss.marshalling.river.RiverUnmarshaller.doReadObject(RiverUnmarshaller.java:209)
    at org.jboss.marshalling.river.RiverUnmarshaller.readFields(RiverUnmarshaller.java:1677)
    at org.jboss.marshalling.river.RiverUnmarshaller.doInitSerializable(RiverUnmarshaller.java:1593)
    at org.jboss.marshalling.river.RiverUnmarshaller.doReadNewObject(RiverUnmarshaller.java:1235)
    at org.jboss.marshalling.river.RiverUnmarshaller.doReadObject(RiverUnmarshaller.java:272)
    at org.jboss.marshalling.river.RiverUnmarshaller.doReadObject(RiverUnmarshaller.java:209)
    at org.jboss.marshalling.river.RiverUnmarshaller.doReadCollectionObject(RiverUnmarshaller.java:180)
    at org.jboss.marshalling.river.RiverUnmarshaller.readCollectionData(RiverUnmarshaller.java:771)
    at org.jboss.marshalling.river.RiverUnmarshaller.doReadObject(RiverUnmarshaller.java:649)
    at org.jboss.marshalling.river.RiverUnmarshaller.doReadObject(RiverUnmarshaller.java:209)
    at org.jboss.marshalling.AbstractObjectInput.readObject(AbstractObjectInput.java:37)
    at org.jboss.ejb.client.remoting.MethodInvocationResponseHandler$MethodInvocationResultProducer.getResult(MethodInvocationResponseHandler.java:107)
    at org.jboss.ejb.client.EJBClientInvocationContext.getResult(EJBClientInvocationContext.java:270)
    at org.jboss.ejb.client.TransactionInterceptor.handleInvocationResult(TransactionInterceptor.java:47)
    at org.jboss.ejb.client.EJBClientInvocationContext.getResult(EJBClientInvocationContext.java:272)
    at org.jboss.ejb.client.ReceiverInterceptor.handleInvocationResult(ReceiverInterceptor.java:132)
    at org.jboss.ejb.client.EJBClientInvocationContext.getResult(EJBClientInvocationContext.java:260)
    at org.jboss.ejb.client.EJBClientInvocationContext.awaitResponse(EJBClientInvocationContext.java:399)
    at org.jboss.ejb.client.EJBInvocationHandler.doInvoke(EJBInvocationHandler.java:140)
    at org.jboss.ejb.client.EJBInvocationHandler.doInvoke(EJBInvocationHandler.java:121)
    at org.jboss.ejb.client.EJBInvocationHandler.invoke(EJBInvocationHandler.java:104)
    ... 2 more

I've practiced this using hibernate session before but I need to do this using JPA Annotation and JPA EntityManager.

I included hibernate libraries in the project but no difference.

This is my first attempt to Enterprise Java and I feel frustrated with my learning ability. Hope you guys could help me.

And I will really appreciate if anyone can give me an sample code of EJB+JPA project that implements DVD rental store database. I am doing this to get a job (which I already lost the chance... but I really want to finish this for future opportunity).

The post has got too long. Thanks for reading this. :)

**Here's my list of jar files enter image description here

Upvotes: 0

Views: 923

Answers (1)

Steve Ebersole
Steve Ebersole

Reputation: 9443

You are missing at least one Hibernate jar from your classpath: hibernate-core. At a minimum you'll need hibernate-entitymanager + hibernate-core + .

TBH this is why projects usually employ some form of depenendency management, be that Maven or Gradle or Ivy or...

Upvotes: 1

Related Questions