根據Hibernate的方言決定要執行的本地sql

項目產品要求運行在不同的數據庫上,目前暫定爲sqlserver和mysql,要求通過更改配置文件能夠在不同的數據庫之間切換:

CommonDao代碼:

@Resource(name="hibernateTemplate")
	protected HibernateTemplate hibernateTemplate;
	
	/**
	 * 是否mysql數據庫
	 * @return
	 */
	public Boolean isMysql(){
		return getDialect() instanceof MySQLDialect;
	}
	
	/**
	 * 是否sqlserver數據庫
	 * @return
	 */
	public Boolean isSqlserver(){
		return getDialect() instanceof SQLServerDialect;
	}
	
	/**
	 * 獲得方言
	 * @return
	 */
	public Dialect getDialect(){
		if(hibernateTemplate.getSessionFactory() instanceof SessionFactoryImplementor){
			SessionFactoryImplementor sf = (SessionFactoryImplementor)hibernateTemplate.getSessionFactory();			
			return sf.getDialect();	
		}
		return new MySQL5InnoDBDialect();
	}


下面是業務層的使用案例:

/**
	 * 根據部門和操作員查詢客戶郵箱列表
	 * 
	 * @param pi
	 *            分頁信息對象
	 * @param deptId
	 *            部門編號
	 * @param empID
	 *            操作員編號
	 */
	@Override
	public void getCustomerEmailsList(final PageInfo<Object[]> pi,
			final Integer deptId, final Integer empId) {
		
		String sql = "";
		if (super.commonDao.isSqlserver()){
			//sqlserver版本
			sql = "SELECT c.customerid,c.name, "
					+ "		[linkm] = REPLACE((SELECT name AS [data()] "
					+ "			from linkman l where c.customerid = l.customerid "
					+ "			FOR XML PATH('')), ' ', ','), "
					+ "		[email] = REPLACE((SELECT email AS [data()] "
					+ "			from linkman l where c.customerid = l.customerid "
					+ "			FOR XML PATH('')), ' ', ',') "
					+ "		FROM customer AS c left join emp as e on e.empid = c.empid "
					+ "         inner join Dept d on d.DeptID=e.DeptID "
					+ "			where 1=1 {condition} order by c.customerid desc ";	
		}
		if (super.commonDao.isMysql()){
			//mysql版本
			sql  = "select c.customerid, "
				+"		c.name, "
				+"		(select group_concat(name) from linkman as l "
				+"		where c.customerId=l.customerId) as linkm, "
				+"		(select group_concat(email) from linkman as l where c.customerId = l.customerId) as email "
				+"	from customer as c left join emp as e on e.empid=c.empid "
				+"	inner join dept as d on d.deptid=e.deptid "
				+"	where 1=1  {condition}  order by c.customerId desc";	
		}

		String count = "select count(1) from customer as c left join emp as e on e.empid = c.empid inner join Dept d on d.DeptID=e.DeptID where 1=1 {condition} ";

		// 獲取當前登錄的用戶
		Emp emp = (Emp) UserUtil.getLoginedUser();
		Role r = emp.getRole();
		
		// 根據當前登錄用戶的角色,拼接不同的查詢語句
		StringBuilder conditionBuilder = new StringBuilder();
		if (r.getRoleId().intValue() == 1) {
			conditionBuilder.append(" and d.disunderling=1 ");
			if (deptId != null && deptId.intValue() > 0 && empId == null) {
				conditionBuilder.append(" and e.deptid=" + deptId);
			} else if (empId != null && empId.intValue() > 0) {
				conditionBuilder.append(" and e.empid=" + empId);
			}
		} else if (r.getRoleId().intValue() == 2) {
			conditionBuilder.append(" and e.deptid="
					+ emp.getDept().getDeptId());
			if (empId != null && empId.intValue() > 0) {
				conditionBuilder.append(" and e.empid=" + empId);
			}
		} else if (r.getRoleId().intValue() == 3) {
			conditionBuilder.append(" and e.empid=" + emp.getEmpId());
		} else {
			throw new RuntimeException("對不起,您的權限不足!");
		}

		if (conditionBuilder.length() > 0) {
			count = count.replace("{condition}", conditionBuilder.toString());
			sql = sql.replace("{condition}", conditionBuilder.toString());
		} else {
			count = count.replace("{condition}", " ");
			sql = sql.replace("{condition}", " ");
		}

		final String _count = count;
		final String _sql = sql;

		super.commonDao.execute(new IHibernateCallback() {

			private static final long serialVersionUID = 7582287328942457212L;

			@SuppressWarnings("unchecked")
			@Override
			public Object doInHibernate(Session session) {
				
				Object cnt = session.createSQLQuery(_count).uniqueResult();
				
				if (cnt == null)
					return null;

				List<Object[]> list = session.createSQLQuery(_sql)
						.setFirstResult(
								(pi.getPageIndex() - 1) * pi.getPageSize())
						.setMaxResults(pi.getPageSize()).list();
				pi.setRecordCount(Integer.valueOf(cnt.toString()));
				pi.setPageCount((int) Math.ceil((pi.getRecordCount() + 0.0)
						/ pi.getPageSize()));
				pi.setResult(list);
				return null;
			}
		});
	}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章