开发者

What will be the Criteria for following SQL?

开发者 https://www.devze.com 2023-03-28 20:02 出处:网络
Can any one help me out with Criteria for following query : SELECT * From TableA Inner Join TableB On TableA.ID=TableB.ID

Can any one help me out with Criteria for following query :

SELECT * From TableA Inner Join TableB On TableA.ID=TableB.ID

I am trying with the following Criteria

Criteria criter开发者_开发百科ia = session.createCriteria(TableA.class);
criteria.setFetchMode("TableB", FetchMode.JOIN);

The above criteria retrives both the table data.

Also if I need only specific columns from TableA how will the criteria Change ?

Thanks for your time.

Edit: TableA has one-to-many relationship with TableB.


Question doesn't make sense. In hibernate, the 2 Tables should actually be entities in which case they would have a relationship between them. Are you trying to randomly join 2 tables and get a result back? If so you have to use sql and use a ResultTransformer to convert the result into objects.

private ResultTransformer getResultsTransformer()
{
    ResultTransformer transformer = new AliasToBeanResultTransformer(
            MyResultBean.class) {
        @Override
        public Object transformTuple(Object[] values, String[] aliases)
        {
            MyResultBean row = new MyResultBean();
            for (int i = 0; i < aliases.length; i++)
            {
                row.set(aliases[i], values[i]);
            }
            return (row);
        }
    };
    return transformer;
}

Call this as follows:

    Query q = session.createSQLQuery(sql);
    q.setResultTransformer(getResultsTransformer());
    List<MyResultBean> list = q.list();

UPDATE: If Table A has a 1-to-Many with Table B, then I find it easiest to use Alias

Criteria criteria = getSession().createCriteria(TableA.class);
criteria.createAlias("tableB","b");
criteria.add(Restrictions.eqProperty("id", "b.id");
criteria.list();

I hope this helps. Regards,


With JOIN, you need to indicate to Hibernate that you only want the "root entity", whcih is tableA. Add the following to your code:

criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号