package dao.impl;
import dao.UserDao;
import domain.User;
import domain.User1;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import util.JDBCUtils;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class UserDaoImpl implements UserDao {
private JdbcTemplate template = new JdbcTemplate(JDBCUtils.getDataSource());
@Override
public List<User> findAll() {
//使用Jdbc操作数据库
String sql="select * from user";
List<User> users = template.query(sql, new BeanPropertyRowMapper<User>(User.class));
return users;
}
@Override
public User1 findUserByUsernameAndPassword(String username, String password) {
try {
String sql="select * from user1 where username=?and password=? ";
User1 user1 = template.queryForObject(sql, new BeanPropertyRowMapper<User1>(User1.class), username, password);
return user1;
} catch (DataAccessException e) {
e.printStackTrace();
return null;
}
}
@Override
public void add(User user) {
//1.定义sql
String sql = "insert into user values(null,?,?,?,?,?,?)";
//执行sql
template.update(sql,user.getName(),user.getGender(),user.getAge(),user.getAddress(),user.getQq(),user.getEmail());
}
@Override
public void delete(int parseInt) {
//1.定义sql语句
String sql = "delete from user where id = ?";
//执行sql
template.update(sql,parseInt);
}
@Override
public User findByid(int parseInt) {
//1.sql语句
String sql = "select * from user where id = ?";
return template.queryForObject(sql,new BeanPropertyRowMapper<User>(User.class),parseInt);
}
@Override
public void updateUser(User user) {
//1.sql语句
String sql = "update user set name = ? , gender = ?,age = ?,address = ?,qq=?,email = ? where id = ?";
template.update(sql,user.getName(),user.getGender(),user.getAge(),user.getAddress(),user.getQq(),user.getEmail(),user.getId());
}
@Override
public int finTotalCount(Map<String,String[]> condition) {
//1.定义一个模板初始化sql
String sql = "select count(*) from user where 1 = 1 ";
StringBuilder sb = new StringBuilder(sql);
//2.遍历map
Set<String> keySet = condition.keySet();
//定义参数的集合
ArrayList<Object> params = new ArrayList<>();
for (String key : keySet) {
//排除分页条件参数
if ("currentPage".equals(key)||"rows".equals(key)){
continue;
}
//获取values
String value = condition.get(key)[0];
//判断value是否有值
if (value != null&& !"".equals(value)){
//有值
sb.append(" and "+ key +" like ? ");
params.add("%" + value +"%");//加条件的值
}
}
return template.queryForObject(sb.toString(),Integer.class,params.toArray());
}
@Override
public List<User> finByPage(int strat, int rows,Map<String,String[]> condition) {
String sql = "select * from user limit ? , ?";
return template.query(sql,new BeanPropertyRowMapper<User>(User.class),strat,rows);
}
}