The problem with JPA Composite primary keys and CascadeType.ALL

Following my previous blog here, I encountered another issue with the use of composite primary keys.

With JPA, we can specify the cascade of relationship to be CascadeType.ALL, so that when we persist the CUSTOMER, all of its PRODUCT are persisted too.

So, the code will be modified as follows:


package com.wordpress.dwuysan;

// imports omitted

@Table(name = "customer")
public class Customer implements Serializable {
    @Column(name = "customer_id")
    private String customerId;

        fetch = FetchType.EAGER,
        mappedBy = "customer",
        cascade = CascadeType.ALL)
    private Set<Product> products = new HashSet<Product>();

    /* the rest of the code omitted */

During unit testing however, when executing the following lines:

    this.entityManager.persist(customer); // customer with child products here
    final Query query = this.entityManager.createQuery("FROM Customer cust");
    return query.getResultList(); // error here

And the error is:

javax.persistence.PersistenceException: org.hibernate.exception.GenericJDBCException: Could not execute JDBC batch update
	at org.hibernate.ejb.AbstractEntityManagerImpl.throwPersistenceException(
	at org.hibernate.ejb.QueryImpl.getResultList(
	at com.wordpress.dwuysan.CustomerServiceBean(
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(
	at java.lang.reflect.Method.invoke(
	at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(
	at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(
	at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(
	at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(

SO, for now, I think I will use another ID for the PRODUCT. Would need to look for the underlying reason.