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);
}
}