Mybatis-Dao层开发之原始dao

来源:互联网 发布:大数据思维与决策 编辑:程序博客网 时间:2024/05/16 19:03

使用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;}@Overridepublic User findUserById(int id) throws Exception {// 根据id查询用户信息SqlSession sqlSession = sqlSessionFactory.openSession();User user = sqlSession.selectOne("test.findUserById", id);// 释放资源sqlSession.close();return user;}@Overridepublic void insertUser(User user) throws Exception {//添加用户SqlSession sqlSession = sqlSessionFactory.openSession();//插入(User对象)sqlSession.insert("test.insertUser", user);//事务提交sqlSession.commit();//释放资源sqlSession.close();}@Overridepublic 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;@Beforepublic void setUpBeforeClass() throws Exception {//执行其他方法前需要创建SqlSessionFactory// mybatis配置文件String resource = "SqlMapConfig.xml";// 得到配置文件流InputStream inputStream = Resources.getResourceAsStream(resource);// 创建会话工厂,传入mybatis的配置文件信息sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);}@Testpublic void testFindUserById() throws Exception {// 创建UserDao的对象UserDao userDao = new UserDaoImpl(sqlSessionFactory);// 调用UserDao的方法User user = userDao.findUserById(27);System.out.println(user);}}

0 0
原创粉丝点击