package com.neusoft.dao;
import java.util.List;
import com.neusoft.entity.User;
public interface UserDao {
public User getUserById(Integer id);
public int delUser(Integer id);
public int addUser(User user);
public int updateUser(User user);
public List<User> getUsers();
}
package com.neusoft.dao.impl;
import java.util.List;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import com.neusoft.dao.UserDao;
import com.neusoft.entity.User;
Dao层接口
public class UserDaoImpl implements UserDao {
private SqlSessionFactory factory;
public UserDaoImpl() {
}
public UserDaoImpl(SqlSessionFactory factory) {
this.factory = factory;
}
@Override
public User getUserById(Integer id) {
SqlSession session = factory.openSession();
User user = session.selectOne("test.selectUserById", id);
session.close();
return user;
}
@Override
public int delUser(Integer id) {
SqlSession session = factory.openSession();
int result = session.delete("test.delUserById", id);
session.commit();
session.close();
return result;
}
@Override
public int addUser(User user) {
SqlSession session = factory.openSession();
int result = session.insert("test.addUser", user);
session.commit();
session.close();
return result;
}
@Override
public int updateUser(User user) {
SqlSession session = factory.openSession();
int result = session.update("test.updateUser", user);
session.commit();
session.close();
return result;
}
@Override
public List<User> getUsers() {
SqlSession session = factory.openSession();
List<User> users = session.selectList("test.selectAll");
session.commit();
session.close();
return users;
}
}
测试类
package com.neusoft.junit;
import java.util.List;
import org.apache.ibatis.session.SqlSessionFactory;
import org.junit.Test;
import com.neusoft.dao.UserDao;
import com.neusoft.dao.impl.UserDaoImpl;
import com.neusoft.entity.User;
import com.neusoft.factory.MyFactory;
public class Testtest {
SqlSessionFactory factory = MyFactory.getSqlSessionFactory();
UserDao userDao = new UserDaoImpl(factory);
@Test
public void testAdd(){
User user = new User("zzhh","zzhh");
userDao.addUser(user);
}
@Test
public void testDel(){
userDao.delUser(20);
}
@Test
public void testUpdate(){
User user = new User(14,"hhzz","12356");
userDao.updateUser(user);
}
@Test
public void testSelectAll(){
List<User> users = userDao.getUsers();
for(User user:users){
System.out.println(user.getId()+"\t"+user.getUsername()+"\t"+user.getPassword());
}
}
}
添加
修改
删除