Mybatis-DAO开发方式

Mybatis-原始开发方式的基础上,我们引入通用的DAO(Data Access Object)开发方式,此时DAO接口及DAO实现均需程序员编写。

DAO接口

1
package com.user.dao;
2
3
import com.user.pojo.UserPojo;
4
5
public interface UserDao {
6
    UserPojo selectById(int id) throws Exception;
7
}

DAO实现

1
package com.user.dao;
2
3
import org.apache.ibatis.session.SqlSession;
4
import org.apache.ibatis.session.SqlSessionFactory;
5
6
import com.user.pojo.UserPojo;
7
8
public class UserDaoImpl implements UserDao {
9
10
    private SqlSessionFactory sqlSessionFactory;
11
12
    public UserDaoImpl(SqlSessionFactory sqlSessionFactory) {
13
        this.sqlSessionFactory = sqlSessionFactory;
14
    }
15
16
    @Override
17
    public UserPojo selectById(int id) {
18
        SqlSession sqlSession = null;
19
        UserPojo userPojo = null;
20
        try {
21
            sqlSession = this.sqlSessionFactory.openSession();
22
            userPojo = sqlSession.selectOne("loveReimu.selectById", id);
23
        } finally {
24
            if (null != sqlSession) sqlSession.close(); 
25
        }
26
        return userPojo;
27
    }
28
}

测试类

1
package com;
2
3
import org.apache.ibatis.io.Resources;
4
import org.apache.ibatis.session.SqlSessionFactory;
5
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
6
import org.junit.Before;
7
import org.junit.Test;
8
9
import com.alibaba.fastjson.JSON;
10
import com.user.dao.UserDaoImpl;
11
12
public class MybatisTest {
13
14
    private SqlSessionFactory sqlSessionFactory;
15
16
    @Before
17
    public void init() throws Exception {
18
        this.sqlSessionFactory = new SqlSessionFactoryBuilder()
19
	                         .build(Resources.getResourceAsStream("mybatis/SqlMapConfig.xml"));
20
    }
21
22
    @Test
23
    public void selectById() {
24
        System.out.println(JSON.toJSONString(new UserDaoImpl(this.sqlSessionFactory).selectById(2)));
25
    }
26
}