Mybatis-DAO开发方式

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

DAO接口

1
2
3
4
5
6
7
package com.user.dao;

import com.user.pojo.UserPojo;

public interface UserDao {
UserPojo selectById(int id) throws Exception;
}

DAO实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package com.user.dao;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import com.user.pojo.UserPojo;

public class UserDaoImpl implements UserDao {

private SqlSessionFactory sqlSessionFactory;

public UserDaoImpl(SqlSessionFactory sqlSessionFactory) {
this.sqlSessionFactory = sqlSessionFactory;
}

@Override
public UserPojo selectById(int id) {
SqlSession sqlSession = null;
UserPojo userPojo = null;
try {
sqlSession = this.sqlSessionFactory.openSession();
userPojo = sqlSession.selectOne("loveReimu.selectById", id);
} finally {
if (null != sqlSession) sqlSession.close();
}
return userPojo;
}
}

测试类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package com;

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.alibaba.fastjson.JSON;
import com.user.dao.UserDaoImpl;

public class MybatisTest {

private SqlSessionFactory sqlSessionFactory;

@Before
public void init() throws Exception {
this.sqlSessionFactory = new SqlSessionFactoryBuilder()
.build(Resources.getResourceAsStream("mybatis/SqlMapConfig.xml"));
}

@Test
public void selectById() {
System.out.println(JSON.toJSONString(new UserDaoImpl(this.sqlSessionFactory).selectById(2)));
}
}
0%