Search code examples
javamysqlhibernatehibernate-criteriasessionfactory

Hibernate Criteria returns duplicate entries ( No joins)


    Criteria cr = session.createCriteria(ProductId.class);

    List<ProductId> policyCount2 = cr.list();
    System.out.println(policyCount2.size());

    for(ProductId x : policyCount2) {
        System.out.println(x.getPRODUCT_TEMPLATE_ID());
    }

there are 8 ProductId rows in the table.... Hibernate is able to find 8 records. however, it returns same product templates 8 times.. like this ...

1
1
1
1
1
1
1
1

This is a straight forward select from the table ProductId. there is no JOINS involved in this program.

Here is the ProductId template table

PRODUCT_ID  PRODUCT_TEMPLATE_ID
FDC140012   1
FDC140012   2
FDC140012   3
FDH140012   5
FDH140012   6
FDH140012   12
FDH140012   10
FDH140012   11

Here is the ProductId POJO...

public class ProductId {

private String PRODUCT_ID;
private int PRODUCT_TEMPLATE_ID;



public String getPRODUCT_ID() {
    return PRODUCT_ID;
}
public void setPRODUCT_ID(String pRODUCT_ID) {
    PRODUCT_ID = pRODUCT_ID;
}
public int getPRODUCT_TEMPLATE_ID() {
    return PRODUCT_TEMPLATE_ID;
}
public void setPRODUCT_TEMPLATE_ID(int pRODUCT_TEMPLATE_ID) {
    PRODUCT_TEMPLATE_ID = pRODUCT_TEMPLATE_ID;
}
public String getSTATE_LIST() {
    return STATE_LIST;
}
public void setSTATE_LIST(String sTATE_LIST) {
    STATE_LIST = sTATE_LIST;
}
}

Here is my Mapping file....

<hibernate-mapping>
    <class name="model.ProductId" table="PRODUCT_ID">
        <id name="PRODUCT_ID" type="java.lang.String">
            <column name="PRODUCT_ID" />
            <generator class="assigned" />
        </id>
        <property name="PRODUCT_TEMPLATE_ID" type="int">
            <column name="PRODUCT_TEMPLATE_ID" />
        </property>
        <property name="STATE_LIST" type="java.lang.String">
            <column name="STATE_LIST" />
        </property>
    </class>
</hibernate-mapping>

Solution

  • The reason is you don't have an unique id. All ProductId have FDC140012 as id.

    This means that you have only one column PRODUCT_ID as id.

    <id name="PRODUCT_ID" type="java.lang.String">
      <column name="PRODUCT_ID" />
      <generator class="assigned" />
    </id>
    

    Hibernate gets all other objects from a cache.