传统Dao开发
1.写一个StudentInterface接口
public interface StudentInterface {
public Student findStudentById(int id);
}
2.写一个StudentInterface接口的实现类
public class StudentImpl implements StudentInterface {
private SqlSessionFactory sessionFactory;
//注入SqlSessionFactory
public StudentImpl(SqlSessionFactory sessionFactory) {
this.sessionFactory =sessionFactory;
}
@Override
public Student findStudentById(int id) {
// 通过工厂生成sqlsessionshi实例,避免了线程不安全问题
SqlSession session = sessionFactory.openSession();
Student student = session.selectOne("Test.selectStudentById",id);
return student;
}
}
需要向dao实现类中通过构造函数注入SqlSessionFactory,在方法体内通过SqlSessionFactory创建SqlSession
3.编写测试代码
public class DaoTest {
SqlSessionFactory sqlSessionFactory=null ;
@Before
public void setUp() throws Exception {
// 读取配置文件
// 全局配置文件的路径
String resource = "SqlMapConfig.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
// 创建SqlSessionFactory
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}
//通过指定id查询
@Test
public void selectStudentById() {
//构造StudentInterface对象
StudentInterface siInterface = new StudentImpl(sqlSessionFactory);
//调用方法
Student student = siInterface.findStudentById(1);
System.out.println(student);
}
}
传统Dao开发问题总结
原始dao开发存在一些问题:
- 存在一定量的模板代码。比如:通过SqlSessionFactory创建SqlSession;调用SqlSession的方法操作数据库;关闭Sqlsession。
- 存在一些硬编码。调用SqlSession的方法操作数据库时,需要指定statement的id,这里存在了硬编码。
Mapper代理开发方式(推荐)
Mapper代理的开发方式,程序员只需要编写mapper接口(相当于dao接口)即可。Mybatis会自动的为mapper接口生成动态代理实现类。
不过要实现mapper代理的开发方式,需要遵循一些开发规范。
开发规范
1、 mapper接口的全限定名要和mapper映射文件的namespace的值相同。
2、 mapper接口的方法名称要和mapper映射文件中的statement的id相同;
3、 mapper接口的方法参数只能有一个,且类型要和mapper映射文件中statement的parameterType的值保持一致。
4、 mapper接口的返回值类型要和mapper映射文件中statement的resultType值或resultMap中的type值保持一致;
定义一个接口StudentMapper
public interface StudentMapper {
public Student selectStudentById(int id)throws Exception;
}
实现类不用编写。直接上测试代码
public class StudentDaoTest {
SqlSessionFactory sqlSessionFactory=null ;
@Before
public void setUp() throws Exception {
// 读取配置文件
// 全局配置文件的路径
String resource = "SqlMapConfig.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
// 创建SqlSessionFactory
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}
@Test
public void testSelectStudentById() throws Exception {
SqlSession session = sqlSessionFactory.openSession();
//拿到代理对象
StudentMapper mapper = session.getMapper(StudentMapper.class);
Student student = mapper.selectStudentById(2);
System.out.println(student);
session.close();
}
}
通过规范式的开发mapper接口,可以解决原始dao开发当中存在的问题:
1、 模板代码已经去掉;
2、 剩下去不掉的操作数据库的代码,其实就是一行代码。这行代码中硬编码的部分,通过第一和第二个规范就可以解决。