关于Hql

public class A {
    private Long id;
    private String name;
    private B b;
}
public Class B{
    private Long id;
    private String className;
}

当我们用sql写左连接的时候会有这样的语句.

select a.* from A a left join B b on a.b.id = b.id where b.id = ?

如果B是A的属性,那么当写hql的时候就应该这样写

select a from A a left join a.b c where  a.b.id = c.id and c.id = ?

这里要说的有几点,

1. hql不支持* ,当我们写select a.*的 时候会抛异常,org.hibernate.hql.ast.QuerySyntaxException: expecting IDENT, found '*' near line 1, column 12......

2. 此处左连接不能用on做条件,要用where,否则会抛异常org.hibernate.hql.ast.QuerySyntaxException: unexpected token: on near line 1, column 93......

3. 左连接的右边应该写a.b 而不是写B.也就是说要写A自己的属性b

4. select 条件要写成select a 而不能是select a.id, a.name, a.b from ,这样写不会得到A对象的list,当迭代list使用a对象的时候会抛出类型转换异常 java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to A

你可能感兴趣的:(JOIN,sql,String,list,Class,token)