Question

I am using hibernate criteria api to get data of txn and txn_products table. Below is the mapping.

class Txn :

@Entity
@DynamicUpdate(value=true)
@Table(name="txn")
public class Txn
{
 @OneToMany(fetch=FetchType.LAZY , mappedBy = "transaction" , cascade = CascadeType.ALL)
    Set<TxnProduct> txnProducts = null;

    @Id
    @Column(name="id" , nullable=false)
    private String id;

......
}

class TxnProduct :

@Entity
@DynamicUpdate(true)
@Table(name="txn_product")
public class TxnProduct
{

 @Id
    @Column(name="id" , nullable=false)
    private String id;

  @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="txn_id")
    private Txn transaction ;
.....
}

business logic :

   Session sx = .......... ;
      Criteria Q = sx.createCriteria(Txn.class, "txn");
              Q.createAlias("txn.txnProducts", "txnProducts" , JoinType.INNER_JOIN);

                List<Txn> L = (List<Txn>) Q.list();


                logger.info(L) ;

                for(Txn T : L)
                {
                    logger.info(T);
                    logger.info(T.getTxnProducts());
                }

       sx.close();

While executing business logic List L returns Txn object for each TxnProduct in database, but what I expect from hibernate criteria is to return Txn object for each row in txn table and set Set<TxnProduct> in it.

I tried Q.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); but it was not helpful. Thanks.

No correct solution

OTHER TIPS

Q.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY); should work in most of the cases unless we use pagination on parent entities like setFirstResult and setMaxResult. There might be some problem with either JoinType or FetchMode.

Wrapping the q.list() with a Set will be better alternative irrespective of any fetch modes. Something like Set<Txn> resutls = new HashSet<Txn>(L)); or if you want to return a list again wrap the set with list List<Txn> results = new ArrayList<Txn>(new HashSet<Txn>(L));

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top