views:

113

answers:

2

I have build my data model using JPA and am using Hibernate's EntityManager 3 to access the data. I used HSQLDB for testing (junit). I am using this configuration for other classes and have had no problems.

However, the latest batch of tables use a composite-key as the primary-key and I am not able to retrieve the populated row from the database when it is implemented. I don't get an error, the query simply returns null objects.

For example if I query (using jsql) "FROM Order o" to return a list of all orders in the table, my list.size() has the proper number of elements (2), but the elements are null.

I am hoping that someone with a sharper eye than I can discern what I am doing wrong. Thanks in advance!

The (simplified) tables are defined as:

CREATE TABLE member (
    member_id INTEGER NOT NULL IDENTITY PRIMARY KEY);

CREATE TABLE orders (
    orders_id INTEGER NOT NULL,
    member_id INTEGER NOT NULL,
    PRIMARY KEY(orders_id, member_id));

ALTER TABLE orders 
    ADD CONSTRAINT fk_orders_member 
    FOREIGN KEY (member_id) REFERENCES member(member_id);

The entity POJOs are defined by:

@Entity
public class Member extends Person implements Model<Integer>{
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="MEMBER_ID", nullable=false)
    private Integer memberId;

    @OneToMany(fetch=FetchType.LAZY, mappedBy="member", cascade=CascadeType.ALL)
    private Set<Order> orderList;
}

@Entity
@Table(name="ORDERS")
@IdClass(OrderPK.class)
public class Order extends GeneralTableInformation implements Model<Integer>{

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="ORDERS_ID", nullable=false)
    private Integer orderId;

    @Id
    @Column(name="MEMBER_ID", nullable=false)
    private Integer memberId;

    @ManyToOne(optional=false, fetch=FetchType.LAZY)
    @JoinColumn(name="MEMBER_ID", nullable=false)
    private Member member;

    @OneToMany(mappedBy="order", fetch=FetchType.LAZY)
    private Set<Note> noteList;
}

OrderPK defines a default constructor and 2 properties (orderId, memberId) along with their get/set methods.

public class OrderPK implements Serializable {
private static final long serialVersionUID = 1L;

private Integer orderId;
private Integer memberId;

public OrderPK() {}

public OrderPK(Integer orderId, Integer memberId) {
    this.orderId = orderId;
    this.memberId = memberId;
}

/**Getters/Setters**/

@Override
public int hashCode() {
    return orderId.hashCode() + memberId.hashCode(); 
}

@Override
public boolean equals(Object obj) {
    if (this == obj) return true;
    if (obj == null) return false;
    if (!(obj instanceof OrderPK))
        return false;

    OrderPK other = (OrderPK) obj;
    if (memberId == null) {
        if (other.memberId != null) return false;
    } else if (!memberId.equals(other.memberId))
        return false;
    if (orderId == null) {
        if (other.orderId != null) return false;
    } else if (!orderId.equals(other.orderId))
        return false;
    return true;
}   

}

(sorry for the length)

the entityManager is instantiated in an abstract class which is then extended by my other DAOs

protected EntityManager em;

@PersistenceContext
public void setEntityManager(EntityManager em) {
    this.em = em;
}

and is configured by a spring context configuration file

<bean id="entityManagerFactory" 
    class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
    p:dataSource-ref="dataSource" 
    p:jpaVendorAdapter-ref="jpaAdapter">
    <property name="loadTimeWeaver">
        <bean class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
    </property>
    <property name="persistenceXmlLocation" value="classpath:META-INF/persistence.xml" />
</bean>

My test class

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class OrderDaoTest {

    @Autowired
    protected OrderDao dao = null;

    @Test
    public void findAllOrdersTest() {
    List<Order> ol = dao.findAll();
    assertNotNull(ol); //pass
        assertEquals(2, ol.size(); //pass
        for (Order o : ol) {
            assertNotNull(o); //fail
            ...
        } 
    }
}

When I strip away the composite-key from the Order class I am able to retrieve data, I am not sure what I am doing incorrectly with my mapping or configuration. Any help is greatly appreciated.

A: 

OrderPK defines a default constructor and 2 properties (orderId, memberId) along with their get/set methods.

I'm not sure this explains everything but... that's not enough. From the JPA 1.0 specification:

2.1.4 Primary Keys and Entity Identity

...

The following rules apply for composite primary keys.

  • The primary key class must be public and must have a public no-arg constructor.
  • If property-based access is used, the properties of the primary key class must be public or protected.
  • The primary key class must be serializable.
  • The primary key class must define equals and hashCode methods. The semantics of value equality for these methods must be consistent with the database equality for the database types to which the key is mapped.
  • A composite primary key must either be represented and mapped as an embeddable class (see Section 9.1.14, "EmbeddedId Annotation") or must be represented and mapped to multiple fields or properties of the entity class (see Section 9.1.15, "IdClass Annotation").
  • If the composite primary key class is mapped to multiple fields or properties of the entity class, the names of primary key fields or properties in the primary key class and those of the entity class must correspond and their types must be the same.

Could you please fix your OrderPK class to comply with the specification and try again?

As a side note, I wonder why you are using the loadTimeWeaver in your Spring configuration (since you're using Hibernate).

Update: I can't reproduce the problem... works as expected for me.

Pascal Thivent
My OrderPK class should satisfy those requirements. I will post it in an update to the original question.
Seth M.
My understanding was that a loadTimeWeaver had to be used. I have removed it without any ill effect. Thank you.
Seth M.
@SethM: Hibernate doesn't rely on weaving (unlike e.g. TopLink) but I don't think that's part of the problem. Unfortunately, I can't reproduce it.
Pascal Thivent
Would it be bad practice to not have the data objects match the relations in the database exactly. for example, the orderId is actually a unique value, but the orders table has an identifying relationship to the member table through memberId.Would it be ok to only use orderId as the PK in the application?
Seth M.
+1  A: 

After struggling with this problem for awhile longer I learned that I was configuring my Id properties in the wrong class.

Originally I was configuring orderId and memberId in the Order class

@Entity
@Table(name="ORDERS")
@IdClass(OrderPK.class)
public class Order extends GeneralTableInformation implements Model<Integer>{

    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name="ORDERS_ID", nullable=false)
    private Integer orderId;

    @Id
    @Column(name="MEMBER_ID", nullable=false)
    private Integer memberId;

However, I learned that if you are using an IdClass OR EmbeddedId that you must make the appropriate field annotations for your Id columns in the ID Class.

@Entity
@Table(name="ORDERS")

@IdClass(OrderPK.class)
public class Order extends GeneralTableInformation implements Model<Integer>{

    @Id
    private Integer orderId;

    @Id
    private Integer memberId;
}

public class OrderPK implements Serializable {
    private static final long serialVersionUID = 1L;

    @Column(name="ORDERS_ID", nullable=false)
    private Integer orderId;

    @Column(name="MEMBER_ID", nullable=false)
    private Integer memberId;
}

With this change I was able to return the expected results with my test.

Seth M.