package com.anxin.dao; import java.util.List; import com.anxin.util.PageListData; public interface BaseDAO { public void save(T entity); public void delete(T entity); public void deleteById(Class entityClass, PK id); public void saveOrUpdate(T entity); public List findAll(Class entityClass); public PageListData findList(Class entityClass, String hql, Object[] params, int currentPage, int pageSize); public List findByProperty(Class entityClass, String propertyName, Object value,int type); public T findById(Class entityClass, PK id); }
BaseDAOImpl.java
package com.anxin.dao.impl; import java.io.Serializable; import java.util.List; import org.hibernate.Query; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.orm.hibernate3.support.HibernateDaoSupport; import com.anxin.dao.BaseDAO; import com.anxin.util.PageListData; public class BaseDAOImpl extends HibernateDaoSupport implements BaseDAO { static Logger logger = LoggerFactory.getLogger(BaseDAOImpl.class); // 保存 public void save(T entity) { try { getHibernateTemplate().save(entity); } catch (RuntimeException re) { throw re; } } // 保存或者更新 public void saveOrUpdate(T entity) { try { getHibernateTemplate().merge(entity); } catch (RuntimeException re) { throw re; } } // 删除 public void delete(T entity) { try { getHibernateTemplate().delete(entity); } catch (RuntimeException re) { throw re; } } // 根据id删除某个对象 public void deleteById(Class entityClass, PK id) { try { getHibernateTemplate().delete(findById(entityClass, id)); } catch (RuntimeException re) { throw re; } } // 根据id加载某个对象 public T findById(Class entityClass, PK id) { try { return (T) getHibernateTemplate().get(entityClass, id); } catch (RuntimeException re) { logger.error("findById " + entityClass.getName() + " failed :{}", re); throw re; } } // 查找所有的对象 public List findAll(Class entityClass) { try { return getHibernateTemplate().loadAll(entityClass); } catch (RuntimeException re) { throw re; } } // 根据某个属性及其值精确或模糊查找对象 public List findByProperty(Class entityClass, String propertyName, Object value, int type) { String queryString = ""; try { if (type == 1) {// type=1是精确查找 queryString = "from " + entityClass.getName() + " as model where model." + propertyName + "= ?"; } else if (type == 2) {// type=2是模糊查找 queryString = "from " + entityClass.getName() + " as model where model." + propertyName + "like ?"; } return getHibernateTemplate().find(queryString, value); } catch (RuntimeException re) { throw re; } } // 根据hql语句及其查询参数,当前页数,每页显示的数目得到分页列表 public PageListData findList(Class entityClass, String hql, Object[] params, int currentPage, int pageSize) { PageListData listdata=null; try { Query query = getSession().createQuery(getCountsHql(hql)); if (null != params && 0 != params.length) { for (int i = 0; i < params.length; i++) { query.setParameter(i, params[i]); } } else { logger.warn("参数为空"); } int total = ((Long) query.uniqueResult()).intValue(); logger.debug("总记录数:", total); query = getSession().createQuery(hql); if (null != params && 0 != params.length) { for (int i = 0; i < params.length; i++) { query.setParameter(i, params[i]); } } if (0 != pageSize) { query.setFirstResult( (currentPage == 0 ? 0 : currentPage - 1) * pageSize) .setMaxResults(pageSize); } List data = query.list(); listdata=new PageListData(total,pageSize,currentPage, data); } catch (RuntimeException re) { throw re; } return listdata; } private String getCountsHql(String hql) { int index = hql.indexOf("from"); if (index != -1) { return "select count(*) " + hql.substring(index); } throw new RuntimeException("sql语句异常" + hql); } }
UserDAO.java
package com.anxin.dao; import com.anxin.bean.User; public interface UserDAO extends BaseDAO{ public User checkLogin(User user); }
UserDAOImpl.java
package com.anxin.dao.impl; import org.hibernate.Query; import com.anxin.bean.User; import com.anxin.dao.UserDAO; public class UserDAOImpl extends BaseDAOImpl implements UserDAO{ public User checkLogin(User user){ String hql="from User u where u.username=? and u.password=?"; Query q=getSession().createQuery(hql); q.setString(0, user.getUsername()).setString(1, user.getPassword()); return q.list()!=null&&q.list().size()>0?(User)q.list().get(0):null; } }
StudentDAO.java
package com.anxin.dao; import com.anxin.bean.Student; public interface StudentDAO extends BaseDAO{ }
StudentDAOImpl.java
package com.anxin.dao.impl; import com.anxin.bean.Student; import com.anxin.dao.StudentDAO; public class StudentDAOImpl extends BaseDAOImpl implements StudentDAO{ }
(2)service层
StudentService.java
package com.anxin.service; import java.util.List; import java.util.Map; import com.anxin.bean.Student; import com.anxin.bean.User; import com.anxin.util.PageListData; public interface StudentService{ public void save(Student stu); public void delete(Student stu); public void deleteById(Integer id); public void update(Student stu); public PageListData findList(Map param, int currentPage, int pageSize); public boolean isExistSameProperty(Map param); public Student findById(Integer id); public List findAll(); public List findByCondition(Map param,int type); }
StudentServiceImpl.java
package com.anxin.service.impl; import java.util.List; import java.util.Map; import com.anxin.bean.Student; import com.anxin.bean.User; import com.anxin.dao.StudentDAO; import com.anxin.dao.UserDAO; import com.anxin.service.StudentService; import com.anxin.service.UserService; import com.anxin.util.PageListData; public class StudentServiceImpl implements StudentService { private StudentDAO dao; public void save(Student stu) { dao.save(stu); } public void delete(Student stu) { dao.delete(stu); } public void deleteById(Integer id) { dao.deleteById(Student.class, id); } public void update(Student stu) { dao.saveOrUpdate(stu); } public PageListData findList(Map param, int pageNum, int pageSize) { String hql = "from Student where 1=1 "; for (Object o : param.keySet()) { hql += " and " + o.toString() + " ? "; } Object params[] = param.values().toArray(); return dao.findList(Student.class, hql, params, pageNum, pageSize); } public boolean isExistSameProperty(Map param) { return true; } public Student findById(Integer id) { return dao.findById(Student.class, id); } public List findAll() { return dao.findAll(Student.class); } public boolean isExistName(String name, String type) { boolean flag=false; if ("add".equals(type)) { List list = dao.findByProperty(Student.class, "name", name, 1); flag=(list != null && list.size() > 0 ? true : false); } else if ("update".equals(type)) { String temp[]=name.split(":"); List list = dao.findByProperty(Student.class, "name", temp[0], 1); if(Boolean.parseBoolean(temp[1])) flag=(list!=null&&list.size()>1?true:false); else flag=(list!=null&&list.size()>0?true:false); } return flag; } public List findByCondition(Map param, int type) { return dao.findByProperty(Student.class, null, null, type); } public StudentDAO getDao() { return dao; } public void setDao(StudentDAO dao) { this.dao = dao; } }
UserService.java
package com.anxin.service; import java.util.List; import java.util.Map; import com.anxin.bean.User; import com.anxin.util.PageListData; public interface UserService{ public void save(User user); public void delete(User user); public void deleteById(Integer id); public void update(User user); public PageListData findList(Map param, int currentPage, int pageSize); public boolean isExistSameProperty(Map param); public User findById(Integer id); public List findAll(); public List findByCondition(Map param,int type); public User checkLogin(User user); }
UserServiceImpl.java
package com.anxin.service.impl; import java.util.List; import java.util.Map; import com.anxin.bean.User; import com.anxin.dao.UserDAO; import com.anxin.service.UserService; import com.anxin.util.PageListData; public class UserServiceImpl implements UserService { private UserDAO dao; public void save(User user) { dao.save(user); } public void delete(User user) { dao.delete(user); } public void deleteById(Integer id) { dao.deleteById(User.class, id); } public void update(User user) { dao.saveOrUpdate(user); } public PageListData findList(Map param, int pageNum, int pageSize) { String hql = "from User"; Object params[] = param.values().toArray(); return dao.findList(User.class, hql, params, pageNum, pageSize); } public boolean isExistSameProperty(Map param) { return true; } public User findById(Integer id) { return dao.findById(User.class, id); } public List findAll() { return dao.findAll(User.class); } public List findByCondition(Map param, int type) { return dao.findByProperty(User.class, null, null, type); } public User checkLogin(User user) { return dao.checkLogin(user); } public UserDAO getDao() { return dao; } public void setDao(UserDAO dao) { this.dao = dao; } }
(3)bean及其Hibernate实体映射文件
Student.java
package com.anxin.bean; public class Student { private int id; private String name; private int age; private String sex; private String address; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } }
User.java
package com.anxin.bean; public class User implements java.io.Serializable { private int id; private String username; private String password; public User(){} public User(String username,String password){ this.username=username; this.password=password; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
Student.hbm.xml
User.hbm.xml
4、逻辑处理Action层
BaseAction.java
package com.anxin.struts.action; import com.anxin.util.OVLoadProperties; import com.anxin.util.PageListData; import com.opensymphony.xwork2.ActionSupport; public class BaseAction extends ActionSupport{ protected PageListData pageListData;//分页组件 protected int currentPage=1;//当前页 protected int pageSize=Integer.parseInt(OVLoadProperties.getInstance().getProperties("pageSize"));//每页显示的数目 protected int querytype;//查询类型 protected String condition;//查询条件 public PageListData getPageListData() { return pageListData; } public void setPageListData(PageListData pageListData) { this.pageListData = pageListData; } public int getCurrentPage() { return currentPage; } public void setCurrentPage(int currentPage) { this.currentPage = currentPage; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public int getQuerytype() { return querytype; } public void setQuerytype(int querytype) { this.querytype = querytype; } public String getCondition() { return condition==null?"":condition.trim(); } public void setCondition(String condition) { this.condition=(condition==null?"":condition.trim()); } }
UserAction.java
package com.anxin.struts.action; import com.anxin.bean.User; import com.anxin.service.UserService; import com.opensymphony.xwork2.ActionContext; public class UserAction extends BaseAction{ private UserService service; private User user; public String login(){ user=service.checkLogin(user); if(user!=null){ ActionContext.getContext().getSession().put("user", user); return "success"; } else{ this.addActionMessage("用户名或密码错误!"); return "input"; } } public UserService getService() { return service; } public void setService(UserService service) { this.service = service; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } }
StudentAction.java
package com.anxin.struts.action; import java.util.HashMap; import java.util.Map; import com.anxin.bean.Student; import com.anxin.service.StudentService; public class StudentAction extends BaseAction { private StudentService service; private Student stu; // 转到增加页面 public String toAdd() { return "add"; } // 添加学生 public String add() { service.save(stu); return "success"; } // 转到修页面 public String toUpdate() { stu = service.findById(stu.getId()); return "update"; } // 更新信息 public String update() { Student temp = service.findById(stu.getId()); temp.setId(stu.getId()); temp.setAddress(stu.getAddress()); temp.setAge(stu.getAge()); temp.setName(stu.getName()); temp.setSex(stu.getSex()); service.update(temp); return "success"; } // 查询列表 public String query() { Map param = new HashMap(); if (!"".equals(condition)) { if (querytype == 1) { param.put("name like", "%" + condition + "%"); } else if (querytype == 2) { param.put("sex =", condition); } } pageListData = service.findList(param, currentPage, pageSize); return "query"; } // 删除学生 public String delete() { service.deleteById(stu.getId()); return "success"; } public StudentService getService() { return service; } public void setService(StudentService service) { this.service = service; } public Student getStu() { return stu; } public void setStu(Student stu) { this.stu = stu; } }
package com.anxin.util; import org.hibernate.FlushMode; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.dao.DataAccessResourceFailureException; import org.springframework.orm.hibernate3.SessionFactoryUtils; public class OpenSessionInViewFilter extends org.springframework.orm.hibernate3.support.OpenSessionInViewFilter { /** * we do a different flushmode than in the codebase * here */ protected Session getSession(SessionFactory sessionFactory) throws DataAccessResourceFailureException { Session session = SessionFactoryUtils.getSession(sessionFactory, true); session.setFlushMode(FlushMode.COMMIT); return session; } /** * we do an explicit flush here just in case * we do not have an automated flush */ protected void closeSession(Session session, SessionFactory factory) { session.flush(); super.closeSession(session, factory); } }
PageListData.java(分页组件)
package com.anxin.util; import java.util.ArrayList; import java.util.List; import java.util.Locale; import javax.servlet.http.HttpServletRequest; public class PageListData { // 分页结果集 private List dataList = null; // 记录总数 private int totalcount = 0; // 每页显示记录数 private int pageSize = 0; // 当前页数 private int currentPage = 1; // 总页数 private int totalPageCount = 1; //分页页脚 private String footer; /*初始化分页组件*/ public PageListData(int totalcount, int pageSize, int currentPage, List dataList) { setTotalcount(totalcount); setPageSize(pageSize); setCurrentPage(currentPage); setDataList(dataList); setFooter(getFooter()); } /** * 封装分页栏函数 必需被包含在某个Form之中 * * @return String pages 当前页号 pageSize 每页显示行数 */ public String getFooter() { StringBuffer pageStr = new StringBuffer(""); pageStr.append("
"); int totalPages = getTotalPageCount(); // 总页数 int prevPage = currentPage - 1; // 上一页 int nextPage = currentPage + 1; // 下一页 pageStr.append("共有" + totalcount + "条记录 "); pageStr.append("第" + currentPage + "页/共" + totalPages + "页 "); if (currentPage > 1) pageStr .append("首页 "); if (currentPage == 1) pageStr .append("首页 "); if (currentPage > 1) pageStr .append("上一页 "); if (currentPage <= 1) pageStr .append("上一页 "); if (currentPage < totalPages) pageStr .append("下一页 "); if (currentPage >= totalPages) pageStr .append("下一页 "); if (currentPage < totalPages) pageStr .append("末页 "); if (currentPage == totalPages) pageStr .append("末页 "); pageStr .append("跳转至第:页"); pageStr.append("
"); pageStr.append(""); pageStr.append(""); return pageStr.toString(); } public List getDataList() { return dataList; } public void setDataList(List dataList) { this.dataList = dataList; } public int getTotalcount() { return totalcount; } public void setTotalcount(int totalcount) { this.totalcount = totalcount; } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public int getCurrentPage() { return currentPage; } public void setCurrentPage(int currentPage) { this.currentPage = currentPage; } //计算总页数,如果为0则置为1 public int getTotalPageCount() { int p; if (totalcount % pageSize == 0) { p=totalcount / pageSize; } else { p=totalcount / pageSize + 1; } return p==0?1:p; } public void setTotalPageCount(int totalPageCount) { this.totalPageCount = totalPageCount; } public void setFooter(String footer) { this.footer = footer; } }
OVLoadProperties.java(读取properties文件的内容)
package com.anxin.util; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Properties; //单例模式实现读取zxc.properties文件的内容 public class OVLoadProperties { // 声明一个自己的实例 private static OVLoadProperties instance = new OVLoadProperties(); final static String fileName = "/config.properties"; // 返回该实例 public static synchronized OVLoadProperties getInstance() { return instance; } // 获取key所对应的值 public String getProperties(String key) { Properties p = new Properties(); InputStream is = null; try { // zxc.properties文件放在src目录的下边 is = OVLoadProperties.class.getResourceAsStream(fileName); if (is == null) is = new FileInputStream(fileName); p.load(is); } catch (Exception e) { System.out.println("加载文件出错啦!" + e.getMessage()); } finally { if (is != null) { try { is.close(); } catch (IOException e) { // TODO Auto-generated catch block System.out.println(e.getMessage()); } } } return p.getProperty(key); } }
声明: 本文只为方便我个人查阅和理解,详细的分析以及源代码请移步 原作者的博客http://chjavach.iteye.com/
public class Singleton {
}
/*
* 懒汉模式。注意,getInstance如果在多线程环境中调用,需要加上synchronized,否则存在线程不安全问题
*/
class LazySingleton
这个月公司安排我一个人做iOS客户端开发,由于急着用,我先发布一个版本,由于第一次发布iOS应用,期间出了不少问题,记录于此。
1、使用Application Loader 发布时报错:Communication error.please use diagnostic mode to check connectivity.you need to have outbound acc
/*
2013年3月15日15:16:24
malloc 就memory(内存) allocate(分配)的缩写
本程序没有实际含义,只是理解使用
*/
# include <stdio.h>
# include <malloc.h>
int main(void)
{
int i = 5; //分配了4个字节 静态分配
int * p
http://wiki.sdn.sap.com/wiki/display/BOBJ/Optimize+query+with+Query+Stripping+in+Web+Intelligence
and a very straightfoward video
http://www.sdn.sap.com/irj/scn/events?rid=/library/uuid/40ec3a0c-936