MyBatis-Mapper代理开发
- 注意事项:是在Mybatis快速入门案例基础只上做修改
步骤:
1.定义与SQL映射文件同名的Mapper接口,并且将Mapper接口和SQL映射文件放置在同一目录下
- 在src/java目录下创建com.itheima.mapper软件包
- 创建UserMapper接口
package com.itheima.mapper;
import com.itheima.pojo.User;
public interface UserMapper {
}
- 在resources目录下创建com/itheima/mapper软件包,注意事项:在resources目录下创建包结构不能使用“.”,而应该使用斜杠"/",正确做法:com/itheima/mapper
- 将UserMapper.xml移动到resources下的mapper软件包下
2.设置SQL映射文件的namespace属性为Mapper接口全限定名
- 修改mybatis-config.xml文件,修改成全路径,如果Mapper接口名称和Sql映射文件同名的话,则可以使用包扫描的方式简化SQL映射文件的加载–
<mappers><package name="com.itheima.mapper"></mappers>
或
3.在Mapper接口中定义方法,方法名就是SQL映射文件中sql语句的id,并保持参数类型和返回值类型一致
package com.itheima.mapper;
import com.itheima.pojo.User;
import java.util.List;
public interface UserMapper {
List<User> selectAll();
}
4.编码:
1.通过SqlSession的getMapper方法获取Mapper接口的代理对象
2.调用对应方法完成sql的执行
- 创建第二个案例:MyBatisDemo2.java,直接运行
package com.itheima;
import com.itheima.mapper.UserMapper;
import com.itheima.pojo.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.IOException;
import java.io.InputStream;
import java.util.List;
/**
* Mybatis Mapper代理开发
*/
public class MyBatisDemo2 {
public static void main(String[] args) throws IOException {
//1.加载Mybatis的核心配置文件,获取SqlSessionFactory
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//2.获取对应的SqlSession对象,用它来执行sql
SqlSession sqlSession = sqlSessionFactory.openSession();
//3.执行sql
//查询结果是List集合,参数是名称空间.id
// List<User> users = sqlSession.selectList("test.selectAll");
//查询单个对象
// sqlSession.selectOne()
//3.1获取UserMapper接口的代理对象
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<User> users = userMapper.selectAll();
System.out.println(users);
sqlSession.close();
}
}