mybatis编写dao实现类的过程较繁琐,在实际开发中没有意义。此文章仅作为mybatis知识的扩展,并以此了解mybatis通过代理dao定位sql语句的过程,即通过mapper配置文件中namespace和id属性定位sql语句
工程结构目录
在【SSM框架入门】mybatis环境搭建的基础上,新建一个IUserDao的实现类UserDaoImpl
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.ssm.dao.impl;
import com.ssm.dao.IUserDao; import com.ssm.domain.User; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory;
import java.util.List;
public class UserDaoImpl implements IUserDao {
private SqlSessionFactory factory;
public UserDaoImpl(SqlSessionFactory factory){ this.factory = factory; }
@Override public List<User> findAll() { SqlSession session = factory.openSession(); List<User> users = session.selectList("com.ssm.dao.IUserDao.findAll"); session.close(); return users; } }
|
修改Test中的MybatisTest类
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 29 30 31
| package com.ssm.test;
import com.ssm.dao.IUserDao; import com.ssm.dao.impl.UserDaoImpl; import com.ssm.domain.User; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.InputStream; import java.util.List;
public class MybatisTest { public static void main(String[] args)throws Exception { InputStream in = Resources.getResourceAsStream("SqlMapConfig.xml"); SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder(); SqlSessionFactory factory = builder.build(in); IUserDao userDao = new UserDaoImpl(factory); List<User> users = userDao.findAll(); for (User user : users) { System.out.println(user); } in.close(); } }
|
运行结果