Mybatis接口绑定方案

本文介绍如何使用MyBatis将接口与mapper.xml文件关联,实现动态SQL查询。通过创建接口并定义方法,与mapper.xml中的SQL映射,可直接调用接口方法执行SQL。文中详细解释了配置步骤及测试代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

实现创建一个接口后把mapper.xml由mybatis 生成接口的实现类,通过调用接口对象就可以获取 mapper.xml 中编写的 sql.

实现步骤
1.创建一个接口,接口包名和接口名与 mapper.xml 中<mapper>namespace 相同
2.接口中方法名和 mapper.xml 标签的 id 属性相同
3.如果接口中方法为多个参数,可以省略 parameterType

代码步骤如下:
1.在全局配置文件mybatis.xml使用<mappers>使用<package>

<mappers>
	<package name="com.xcy.mapper">
</mappers>

2.在com.xcy.mapper下新建接口

public interface UserMapper{
	List<User> selAll();
}

3.在com.xcy.mapper包下新建UserMapper.xml文件<mapper namespace=“com.xcy.mapper.UserMapper”>,namespace必须和接口全限定路径一致,id值必须和接口中方法名相同,如果接口中方法为多个参数,可以省略 parameterType。

<mapper namespace="com.xcy.mapper.UserMapper"> 
	<select id="selAll" resultType="user"> 
		select * from user 
	</select>
 </mapper>

测试代码:

	InputStream is = Resources.getResourceAsStream("mybatis.xml");
	SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
	SqlSession session = factory.openSession();

	UserMapper userMapper = session.getMapper(UserMapper.class);
	List<User> list = userMapper.selAll();
	for (User user : list) {
		System.out.println(user);
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值