JPA mapped model returns null elements with Composite-Keys

12,523

Solution 1

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.

Solution 2

I had same kind of problem. I had to create backend on existing database, which had some tables without primary keys and with nullable columns (I know!!). This means that Hibernate entities for these kind of tables would have composite primary key consisting of all of the table columns.

When I queried the table rows through JpaRepository's findAll method, I would get a list of results where some of the results would be null values while others would be ok.

I finally found out that if some field of the composite key is null, it would render whole row as null result.

Share:
12,523
Seth M.
Author by

Seth M.

About Me

Updated on June 19, 2022

Comments

  • Seth M.
    Seth M. almost 2 years

    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.