1. 定义与SQL映射文件同名的Mapper接口,并且将Mapper接口和SQL映射文件放置在同一目录下。
2. 设置SQL映射文件的namespace属性为Mapper接口的全限定名。
<mapper namespace="com.wxq.mapper.UserMapper">
3.在Mapper的接口中定义方法,方法名就是SQL映射文件中sql语句的id,并保持参数类型和返回值类型一致。
package com.wxq.mapper;
import com.wxq.pojo.User;
public interface UserMapper {
User selectAll();
}
4. 编码
package com.wxq;
import com.wxq.mapper.UserMapper;
import com.wxq.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;
public class MybatisDemo02 {
public static void main(String[] args) throws IOException {
//1. 读取mybatis-config.xml配置文件
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
//2. 构建SqlSessionFactory(框架初始化)
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//3. 打开sqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
/* //4. 执行sql语句
List<User> users = sqlSession.selectList("test.selectAll");*/
//获取UserMapper接口的代理对象
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
List<User> users = userMapper.selectAll();
System.out.println(users);
//释放资源
sqlSession.close();
}
}
文章详细介绍了如何在Mybatis框架中配置Mapper接口与SQL映射文件的关联,包括将接口与映射文件同名并放于同一目录,设置映射文件的namespace为接口全限定名,接口方法名与SQLid对应,以及如何通过SqlSession获取接口的代理对象执行SQL操作。
568

被折叠的 条评论
为什么被折叠?



