⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 basedao.java

📁 ssh分页的一个例子内含数据库文件 在src文件夹下自己找
💻 JAVA
字号:
package com.pagedemo.model.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import com.pagedemo.common.PageResult;
import com.pagedemo.model.util.HibernateSessionFactory;

public class BaseDAO {

	// 执行持久化操作前
	private Session methodBefore() {
		Session session = HibernateSessionFactory.getSession();
		session.beginTransaction();
		return session;
	}

	// 执行持久化操作后
	private void methodAfter(Session session) {
		session.getTransaction().commit();
		session.close();
	}

	// 保存
	public void save(Object object) {
		Session session = this.methodBefore();
		session.save(object);
		this.methodAfter(session);
	}

	// 无参数批量查询
	public List find(String hql) {
		Session session = this.methodBefore();
		Query query = session.createQuery(hql);
		List list = query.list();
		this.methodAfter(session);
		return list;
	}

	// 有参数批量查询
	public List find(String hql, Object[] params) {
		Session session = this.methodBefore();
		Query query = session.createQuery(hql);
		for (int i = 0; i < params.length; i++) {
			query.setParameter(i, params[i]);
		}
		List list = query.list();
		this.methodAfter(session);
		return list;
	}

	// 分页查询
	public void pageList(PageResult pageResult) {
		Session session = this.methodBefore();
		String hql = pageResult.getHql();
		// 获得总记录数
		if (hql.toLowerCase().indexOf("select") != -1) {
			int index = hql.toLowerCase().indexOf("from");
			hql = hql.substring(index);
		}
		if (hql.toLowerCase().indexOf("order by") != -1) {
			int index = hql.toLowerCase().indexOf("order by");
			hql = hql.substring(0, index);
		}
		if (hql.toLowerCase().indexOf("left join") != -1) {
			int index = hql.toLowerCase().indexOf("left join");
			hql = hql.substring(0, index);
		}
		hql = "select count(*) " + hql;
		Query query = session.createQuery(hql);
		Long count = (Long) query.uniqueResult();
		pageResult.setTotalRecord(count.intValue());
		// 获得总页数
		pageResult.getTotalPage();

		int start = (pageResult.getCurrent() - 1) * pageResult.getPageSize();
		int size = pageResult.getPageSize();
		hql = pageResult.getHql();
		query = session.createQuery(hql);
		query.setFirstResult(start);
		query.setMaxResults(size);

		if (query.list().size() < 1) { // 指定编号的页面已经越界
			// 重新定义起始索引
			query.setFirstResult((pageResult.getTotalPage() - 1) * size);
		}
		pageResult.setList(query.list());// 获得区间数据
		this.methodAfter(session);
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -