hibernate 根据类获得表名||hibernate 分页

来源:互联网 发布:mac虚拟机共享网络 编辑:程序博客网 时间:2024/05/04 10:34

本来是百度了一下以为能找到对的就懒得写了。
但是百度了一下发现居然有人把hibernate配置文件加载一遍然后去里边找。。
真是。。

然后搜了一下BaseDaoimpl
看了一下找到的代码 findCount里边的参数是String hql.
其实完全不用。

都知道 。我们写hibernate的pojo时,是用注解写了表名的。我们只是需要是读一下这个值就可以了。
比如以最新的hibernate 4.3.8为例 (改用Entity来标注表名了,而不是table,不过别的版本也一样)

@Documented@Target(TYPE)@Retention(RUNTIME)public @interface Entity {    /**     * (Optional) The entity name. Defaults to the unqualified     * name of the entity class. This name is used to refer to the     * entity in queries. The name must not be a reserved literal     * in the Java Persistence query language.     */    String name() default "";}

如何写一个通用的分页代码呢
很简单 只需要四行。

    public List<T> findByPages(Class<T> entity,int pageIndex,int pageSize){        Query q = getSessionFactory().getCurrentSession().createQuery("from "+((Entity)entity.getAnnotation(Entity.class)).name());        q.setFirstResult(pageIndex*pageSize);//设置起始行        q.setMaxResults(pageSize);//每页条数        return  q.list(); //得到每页的数据    }
0 0