Dorado 支援多Hibernate 訪問 同一資料庫(MultiHibernateDao)
DBConfigLocal.properties
driver = oracle.jdbc.driver.OracleDriver
url = jdbc:oracle:thin:@127.0.0.1:1521:ORCL
username = tie
password = tie
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd" >
<hibernate-configuration>
<session-factory>
<property name="connection.url">jdbc:oracle:thin:@127.0.0.1:1521:orcl</property>
<property name="connection.username">tie_jxmg</property>
<property name="connection.password">tie_jxmg</property>
<property name="connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="dialect">org.hibernate.dialect.Oracle10gDialect</property>
<mapping class="com.mini.entity.Forum"/>
</session-factory>
</hibernate-configuration>
MultiHibernateDaoForum.java
package com.mini.dao;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import org.springframework.stereotype.Repository;
import com.bstek.dorado.data.provider.Page;
import com.gs.mcf.common.McfBaseDAO;
import com.mini.entity.Forum;
/***
* MultiHibernateDao 多資料來源支援
* 建立日期: 20151125
* @author like12
* @param <T>
*
*/
@SuppressWarnings("deprecation")
@Repository
public class MultiHibernateDaoForum<T> extends McfBaseDAO<Forum, String> {
//like12 add,20151224,全域性Session
//like12 modified,20170412,改為非static
private Session sessionGlobal = null;
/**
* 儲存
* @param entity
*/
public void saveMulti(T entity) {
String entityName = this.getEntityName(entity);
Session session = this.getSessionMulti();
//like12 modified,20170401,bug,儲存不起,不提交
Transaction tran = session.beginTransaction();
try{
session.saveOrUpdate(entityName, entity);
//提交
tran.commit();
}catch (Exception e){
e.printStackTrace();
//回滾
tran.rollback();
}finally{
//關閉
//like12 modified,bug,20170414,資料庫連線池洩露
//SessionFactory().openSession()開啟的連線,session.close()不行
//要用SessionFactory().close()才能真正釋放資料庫中的連線
//sessionGlobal.close();
sessionGlobal.getSessionFactory().close();
}
}
/**
* 更新
*
* @param hql
* @param params
*/
public void excuteUpdate(final String hql, Object[] params) {
Session session = this.getSessionMulti();
Query query = session.createQuery(hql);
//like12 modified,20170401,bug,儲存不起,不提交
Transaction tran = session.beginTransaction();
try{
if (params != null) {
int i = 0;
for (Object o : params) {
query.setParameter(i, o);
i++;
}
}
query.executeUpdate();
//提交
tran.commit();
}catch (Exception e){
e.printStackTrace();
//回滾
tran.rollback();
}finally{
//關閉
sessionGlobal.getSessionFactory().close();
}
}
/**
* 單個查詢
* @param hql
* @param parameters
* @return
*/
@SuppressWarnings("unchecked")
public <X> X findUniqueMulti(String hql, Map<String, ?> parameters) {
//查詢
X X = (X) createQueryMulti(hql, parameters).uniqueResult();
//關閉
sessionGlobal.getSessionFactory().close();
//返回
return X;
}
/**
* like12 add,20160127
* 全部查詢
* @param hql
* @param parameters
* @return
*/
@SuppressWarnings("unchecked")
public <X> List<X> findMulti(String hql, Map<String, ?> parameters) {
//查詢
List<X> X = createQueryMulti(hql, parameters).list();
//關閉
sessionGlobal.getSessionFactory().close();
//返回
return X;
}
/**
* 分頁查詢
* @param page
* @param hql
* @param parameters
* @return
*/
@SuppressWarnings("unchecked")
public Page<T> findMulti(Page<T> page, String hql, Map<String, ?> parameters) {
notNull(page, "page");
//總條數
long totalCount = countHqlResultMulti(hql, parameters);
//查詢
Query q = this.createQueryMulti(hql, parameters);
page.setEntityCount((int) totalCount);
setPageParameterToQuery(q, page);
page.setEntities(q.list());
//關閉
sessionGlobal.getSessionFactory().close();
//返回
return page;
}
//查詢用
public Query createQueryMulti(String queryString, Map<String, ?> parameters) {
Query query = this.getSessionMulti().createQuery(queryString);
if (parameters != null) {
query.setProperties(parameters);
}
return query;
}
//分頁查詢用
protected long countHqlResultMulti(String hql, Map<String, ?> parameters) {
String countHql = generateCountHqlMulti(hql);
return ((Number) findUniqueMulti(countHql, parameters)).longValue();
}
private String generateCountHqlMulti(String hql) {
hql = "from " + StringUtils.substringAfter(hql, "from");
hql = StringUtils.substringBefore(hql, "order by");
String countHql = "select count(*) " + hql;
return countHql;
}
/**
* 獲取多資料來源Session
* @return
*/
public Session getSessionMulti() {
//方式二:hibernate.cfg.xml
//預設讀取src下hibernate.cfg.xml
SessionFactory sf = new AnnotationConfiguration()
.configure("hibernate.cfg.xml")
.buildSessionFactory();
sessionGlobal = sf.openSession();
//返回
return sessionGlobal;
}
}
ForumServer.java
package com.mini.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.bstek.dorado.data.provider.Page;
import com.mini.dao.ForumDAOMulti;
import com.mini.dao.MultiHibernateDaoForum;
import com.mini.dao.MultiHibernateDaoImage;
import com.mini.entity.Forum;
import com.mini.entity.Image;
import net.sf.json.JSONObject;
public class ForumServer extends HttpServlet {
private static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
//支援中文
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
//引數
String queryMode = request.getParameter("queryMode");
String pageNoStr = request.getParameter("pageNo");
String employeeId = request.getParameter("employeeId");
String forumId = request.getParameter("forumId");
/*System.out.println("---forumServer queryMode=" + queryMode +
" pageNo=" + pageNoStr +
" employeeId=" + employeeId
);*/
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
//分頁查詢
if("byEmployeeId".equals(queryMode) && pageNoStr != null
&& employeeId != null){
//分頁查詢(By時間)
Integer pageSize = 10;//一頁多少條
Integer pageNo = Integer.parseInt(pageNoStr);
if(pageNo == -1){
pageNo = 1;//預設初始查詢第一頁
}
//查
MultiHibernateDaoForum<Forum> daoForum =
new MultiHibernateDaoForum<Forum>();
Page<Forum> page = new Page<Forum>(pageSize, pageNo);
page = daoForum.findMulti(page, "from Forum where " +
" enabledFlag=1 " +
" and employeeId='" + employeeId + "'" +
" order by sortOrder desc ", null);
//取值
Collection<Forum> coll = page.getEntities();
Integer entityCount = page.getEntityCount();
Integer pageTotals = entityCount / pageSize + 1;
//迭代器用於while迴圈
List<JSONObject> listJson = new ArrayList<JSONObject>();
Forum forum = new Forum();
List<Image> listImg = null;
Image img = new Image();
Iterator<Forum> iter = coll.iterator();
String imageOrVideoPre = null;
String imageOrVideoSuf = null;
while(iter.hasNext()){
forum = (Forum)iter.next();
//賦值
JSONObject jsonObject = new JSONObject();
jsonObject.put("sortOrder", forum.getSortOrder());
jsonObject.put("forumTitle", forum.getForumTitle());
jsonObject.put("forumContent", forum.getForumContent());
jsonObject.put("forumId", forum.getForumId());
jsonObject.put("type", forum.getType());
jsonObject.put("employeeId", forum.getEmployeeId());
jsonObject.put("employeeName", forum.getEmployeeName());
jsonObject.put("photo", forum.getPhoto());
jsonObject.put("commentNum", forum.getCommentNum());
jsonObject.put("likeNum", forum.getLikeNum());
jsonObject.put("clickNum", forum.getClickNum());
jsonObject.put("createdDate", df.format(forum.getCreatedDate()));
listJson.add(jsonObject);
}
//第幾頁
JSONObject jsonObject = new JSONObject();
jsonObject.put("entityCount", entityCount);//總條數
jsonObject.put("pageSize", pageSize);//一頁多少條
jsonObject.put("pageTotals", pageTotals);//總頁數
jsonObject.put("pageNo", pageNo);//第幾頁
listJson.add(jsonObject);
//發 返回資訊
PrintWriter out = response.getWriter();
out.append(listJson.toString());
out.close();
}
//按id查詢
else if("byId".equals(queryMode) && forumId != null){
//查詢
MultiHibernateDaoForum<Forum> daoForum =
new MultiHibernateDaoForum<Forum>();
Forum forum = (Forum)daoForum.findUniqueMulti("from Forum where " +
" enabledFlag=1 " +
" and forumId='" + forumId + "'", null);
JSONObject jsonObject = new JSONObject();
if(forum != null){
//賦值
jsonObject.put("sortOrder", forum.getSortOrder());
jsonObject.put("forumTitle", forum.getForumTitle());
jsonObject.put("forumContent", forum.getForumContent());
jsonObject.put("forumId", forum.getForumId());
jsonObject.put("type", forum.getType());
jsonObject.put("employeeId", forum.getEmployeeId());
jsonObject.put("employeeName", forum.getEmployeeName());
jsonObject.put("photo", forum.getPhoto());
jsonObject.put("commentNum", forum.getCommentNum());
jsonObject.put("likeNum", forum.getLikeNum());
jsonObject.put("clickNum", forum.getClickNum());
jsonObject.put("createdDate", df.format(forum.getCreatedDate()));
//查圖片
MultiHibernateDaoImage<Image> daoImg = new MultiHibernateDaoImage<Image>();
List<Image> listImg = daoImg.findMulti("from Image where " +
" enabledFlag=1 " +
" and imageTypeId=1 " +//0首頁 1帖子
" and parentId='" + forum.getForumId() + "' " +//父ID
" order by sortOrder ", null);
if(listImg != null && listImg.size() > 0){
String imageOrVideoPre = null;
String imageOrVideoSuf = null;
Image img = new Image();
for(int i=0; i<listImg.size(); i++){
img = listImg.get(i);
if(img.getImageOrVideo() == 0){//圖片
imageOrVideoPre = "img";
imageOrVideoSuf = "jpg";
}else if(img.getImageOrVideo() == 1){//視訊
imageOrVideoPre = "video";
imageOrVideoSuf = "mp4";
}
jsonObject.put(imageOrVideoPre + i, img.getImageUrl());
jsonObject.put("imgcontent" + i, img.getImageContent());
jsonObject.put("filetype" + i, imageOrVideoSuf);
}
}
}else{
//賦值
jsonObject.put("forumTitle", "不存在的帖子");
}
//發 返回資訊
PrintWriter out = response.getWriter();
out.append(jsonObject.toString());
out.close();
}
//按id查詢
else if("deleteById".equals(queryMode) && forumId != null){
//刪除
MultiHibernateDaoForum<Forum> daoForum =
new MultiHibernateDaoForum<Forum>();
daoForum.excuteUpdate(" update Forum " +
" set enabledFlag=0 where " +
" forumId='" + forumId + "'", null);
//返回
JSONObject jsonObject = new JSONObject();
jsonObject.put("result", "success");
jsonObject.put("msg", "操作成功");
//發 返回資訊
PrintWriter out = response.getWriter();
out.append(jsonObject.toString());
out.close();
}
//無效引數
else{
JSONObject jsonObject = new JSONObject();
jsonObject.put("forumTitle", "無效的引數");
//發 返回資訊
PrintWriter out = response.getWriter();
out.append(jsonObject.toString());
out.close();
}
}
@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
this.doGet(request, response);
}
}