1、使用原始dao开发需要编写mapper的接口和实现类
1、编写接口
public interface UserDao { User getUserById(int userId); }
2、编写实现类
public class UserDaoImpl implements UserDao { private SqlSessionFactory sqlSessionFactory; public UserDaoImpl(SqlSessionFactory sqlSessionFactory) { this.sqlSessionFactory = sqlSessionFactory; } @Override public User getUserById(int userId) { SqlSession sqlSession = sqlSessionFactory.openSession(); return sqlSession.selectOne("test.selectUserById", 1); } }
3、编写测试类
public class MybatisTest2 { private SqlSessionFactory sqlSessionFactory; @Before public void getSqlSessionFactory() throws IOException { InputStream in = Resources.getResourceAsStream("sqlMapConfig.xml"); sqlSessionFactory = new SqlSessionFactoryBuilder().build(in); } @Test public void Test() { UserDao userDao = new UserDaoImpl(sqlSessionFactory); User user = userDao.getUserById(1); System.out.println(user); } }
2、在编写代码的过程中逐渐发现所有实现类的方方法体内的代码都是相似的,唯独不同的是调用SQLSession的方法不同。所以推荐使用mybatis的动态代理的方式来开发
3、mybatis动态代理开发有五点要求
1、xml文件和接口必须在同一文件夹(包)下
2、xml中的id和接口的方法名相同
3、xml的namespace要和接口的全类名相同
4、接口的返回值类型要和xml中的一致
5、xml中的参数要和接口的参数相同
4、使用方式
1、xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> <mapper namespace="com.liuxianglin.mybatis.study.mapper.UserMapper"> <select id="getUserById" parameterType="int" resultType="user"> SELECT * FROM `user` WHERE id = #{id}; </select> <select id="listUserByName" parameterType="QueryVo" resultType="userMap"> SELECT * FROM `user` WHERE `username` LIKE CONCAT(‘%‘,#{user.userName},‘%‘); </select> <select id="getUserCount" resultType="int"> SELECT COUNT(1) FROM `user`; </select> </mapper>
2、接口
public interface UserMapper { /** * 通过id查询用户数据 */ User getUserById(int id); /** * 模糊查询数据 */ List<User> listUserByName(QueryVo queryVo); /** * 查询用户条目数 */ Integer getUserCount(); }
3、测试类
public class MybatisTest { private SqlSessionFactory sqlSessionFactory; @Before public void getSqlSession() throws IOException { /*获得文件流*/ InputStream in = Resources.getResourceAsStream("sqlMapConfig.xml"); /*获取SQLSession工厂*/ sqlSessionFactory = new SqlSessionFactoryBuilder().build(in); } @Test public void test() { /*获取SQLSession连接*/ SqlSession sqlSession = sqlSessionFactory.openSession(); /*动态代理获取Mapper实现类*/ UserMapper userMapper = sqlSession.getMapper(UserMapper.class); /*执行方法*/ User user = userMapper.getUserById(1); System.out.println(user); } }
原文地址:https://www.cnblogs.com/l48x4264l46/p/10957735.html
时间: 2024-11-09 07:48:53