使用dao接口开发Dao层程序,只需要编写Dao接口与其对应实现类即可。
代码如下:
相关配置文件
底层搭建:详见 http://blog.csdn.net/qq_28796345/article/details/53402808
配置文件:详见 http://blog.csdn.net/qq_28796345/article/details/53427020
Mapper动态代理方式实现Dao:详见 http://blog.csdn.net/qq_28796345/article/details/53427134
1、Dao接口
package com.sw.dao;
import com.sw.po.User;
/*
*@Author swxctx
*@time 2016年12月1日
*@Explain:dao接口(用户管理)
*/
public interface UserDao {
//根据id查询用户的信息
public User findUserById(int id)throws Exception;
//添加用户
public void insertUser(User user)throws Exception;
//删除用户
public void deleteUser(int id)throws Exception;
}
2、实现类
package com.sw.dao;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import com.sw.po.User;
/*
*@Author swxctx
*@time 2016年12月1日
*@Explain:dao层实现类
*/
public class UserDaoImpl implements UserDao{
//向实现类中注入SqlSessionFactory
//通过构造函数注入(未与Spring整合)
//sqlsession线程并不安全,因此不能写在此处,需要写在方法体内
private SqlSessionFactory sqlSessionFactory;
public UserDaoImpl(SqlSessionFactory sqlSessionFactory) {
this.sqlSessionFactory = sqlSessionFactory;
}
@Override
public User findUserById(int id) throws Exception {
// 根据id查询用户信息
SqlSession sqlSession = sqlSessionFactory.openSession();
User user = sqlSession.selectOne("test.findUserById", id);
// 释放资源
sqlSession.close();
return user;
}
@Override
public void insertUser(User user) throws Exception {
//添加用户
SqlSession sqlSession = sqlSessionFactory.openSession();
//插入(User对象)
sqlSession.insert("test.insertUser", user);
//事务提交
sqlSession.commit();
//释放资源
sqlSession.close();
}
@Override
public void deleteUser(int id) throws Exception {
//删除用户
SqlSession sqlSession = sqlSessionFactory.openSession();
//执行操作
sqlSession.delete("test.deleteUser", id);
//释放资源
sqlSession.close();
}
}
3、测试类
package com.sw.daoTest;
import java.io.InputStream;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Before;
import org.junit.Test;
import com.sw.dao.UserDao;
import com.sw.dao.UserDaoImpl;
import com.sw.po.User;
/*
*@Author swxctx
*@time 2016年12月1日
*@Explain:
*/
public class UserDaoImplTest {
private SqlSessionFactory sqlSessionFactory;
@Before
public void setUpBeforeClass() throws Exception {
//执行其他方法前需要创建SqlSessionFactory
// mybatis配置文件
String resource = "SqlMapConfig.xml";
// 得到配置文件流
InputStream inputStream = Resources.getResourceAsStream(resource);
// 创建会话工厂,传入mybatis的配置文件信息
sqlSessionFactory = new SqlSessionFactoryBuilder()
.build(inputStream);
}
@Test
public void testFindUserById() throws Exception {
// 创建UserDao的对象
UserDao userDao = new UserDaoImpl(sqlSessionFactory);
// 调用UserDao的方法
User user = userDao.findUserById(27);
System.out.println(user);
}
}