4.5. 创建数据层: IUsersDAO.java 接口和 UsersDAOImpl.java 类,业务层:IUsersBusiness.java接口和UsersBusinessImpl.java类。
IUsesDAO.java 内容如下:
package com.zlk.dao;
import com.zlk.pojo.Users;
public interface IUsersDao {
/**
* 检测用户名是否存在
*/
public Users getUserByName(String username);
/**
* 判断用户名和密码是否存在
*/
public Users getUser(String username,String password);
/**
* 添加用户
*/
public boolean saveUser(Users users);
}
UsersDAOImpl.java 内容如下:
package com.zlk.dao.impl;
import java.util.List;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.zlk.dao.IUsersDao;
import com.zlk.pojo.Users;
public class UsersDaoImpl extends HibernateDaoSupport implements IUsersDao {
public Users getUserByName(String username) {
// TODO Auto-generated method stub
Users users = null;
try {
String hql = "from Users as u where u.username = ?";
List list = this.getHibernateTemplate().find(hql,username);
if(list!=null && list.size()>0){
users = (Users)list.get(0);
}
} catch (DataAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return users;
}
public Users getUser(String username, String password) {
// TODO Auto-generated method stub
Users users = null;
try {
String hql = "from Users as u where u.username = ? and u.password = ?";
List list = this.getHibernateTemplate().find(hql,new Object[]{username,password});
if(list!=null && list.size()>0){
users = (Users)list.get(0);
}
} catch (DataAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return users;
}
public boolean saveUser(Users users) {
// TODO Auto-generated method stub
boolean flag = false;
try {
this.getHibernateTemplate().save(users);
flag = true;
} catch (DataAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return flag;
}
}
注意:
此处的HibernateDaoSupport 的路径可能有多个(可能导入了许多其它的包),注意此处的父类
为org.springframework.orm.hibernate3.support.HibernateDaoSupport
而不是org.springframework.orm.hibernate.support.HibernateDaoSupport