在spring mvc+hibernate+mysql中,讲解下如何做比如在文本框里输入中文,然后查询的一些套路。
1 MYSQL中,首先要做到的是my.ini的客户编码为UTF8,而数据库中的表,表里的字段也用utf-8来整理
2 在serachcontroller中,如下结构
private ModelAndView searchResultList(HttpServletRequest request) {
try {
request.setCharacterEncoding("utf8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
HttpSession session = request.getSession();
String contextPath = request.getContextPath();
//获得关键字
String keyword = ParamUtil.getString(request,"keyword","").trim();
System.out.println(keyword);
Member mem = new Member();
mem.setName(keyword);
之后调用业务逻辑层
//获得记录条数
int total = this.getMemberFacade().getTotalByMember(mem);
..........................
而在实际的DAO实现层中,这样搞
public int getTotalByMember(final Member mem) {
return getHibernateTemplate().executeFind(new HibernateCallback() {
public Object doInHibernate(Session s) throws HibernateException,
SQLException {
Criteria cr = s.createCriteria(Memberh.class);
cr.add(Expression.like("name", "%" + mem.getName() + "%"));
List list = cr.list();
return list;
}
}).size();
}
1 MYSQL中,首先要做到的是my.ini的客户编码为UTF8,而数据库中的表,表里的字段也用utf-8来整理
2 在serachcontroller中,如下结构
private ModelAndView searchResultList(HttpServletRequest request) {
try {
request.setCharacterEncoding("utf8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
HttpSession session = request.getSession();
String contextPath = request.getContextPath();
//获得关键字
String keyword = ParamUtil.getString(request,"keyword","").trim();
System.out.println(keyword);
Member mem = new Member();
mem.setName(keyword);
之后调用业务逻辑层
//获得记录条数
int total = this.getMemberFacade().getTotalByMember(mem);
..........................
而在实际的DAO实现层中,这样搞
public int getTotalByMember(final Member mem) {
return getHibernateTemplate().executeFind(new HibernateCallback() {
public Object doInHibernate(Session s) throws HibernateException,
SQLException {
Criteria cr = s.createCriteria(Memberh.class);
cr.add(Expression.like("name", "%" + mem.getName() + "%"));
List list = cr.list();
return list;
}
}).size();
}