在Mybatis的基础使用中,如果想向一个sql语句中传递多个参数,只能将parameterType设置为某个类或者Map,不能直接传入多个参数,接口绑定方案可以实现直接传入多个参数。
Mybatis的接口绑定方案与基本的使用方法不同的地方在于它是使用接口来执行sql语句,使用起来更加方便
1、SqlMapConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- 别名 -->
<typeAliases>
<!-- 为某一个特定的类起别名 -->
<typeAlias type="bean.Flower" alias="fl"/>
<!-- 为某一个包起别名,所有的类的别名直接为类名 -->
<package name="bean"/>
</typeAliases>
<environments default="default">
<environment id="default">
<transactionManager type="JDBC" />
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver" />
<property name="url"
value="jdbc:mysql://localhost:3306/ssm?serverTimezone=UTC" />
<property name="username" value="root" />
<property name="password" value="123456" />
</dataSource>
</environment>
</environments>
<mappers>
<!-- 普通方案 -->
<!-- <mapper resource="mapper/FlowerMapper.xml" /> -->
<!-- 接口绑定方案 -->
<package name="mapper"/>
</mappers>
</configuration>
2、Mapper.xml配置
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="mapper.FlowerMapper">
<select id="selectAll" resultType="fl">
select * from flower
</select>
<select id="selectById2" resultType="fl">
select * from flower where id=#{param1} or id=#{param2}
</select>
</mapper>
Mapper.xml与一般的配置没有什么太大的区别,但必须要保证namespace是接口的 包路径.接口名
;每一个id都在接口中有对应的方法。如果传递的是多参数,则不需要设置parameterType。
在将这个mapper文件加入到主配置文件时也有一些改变,如下:
<mappers>
<!-- 普通方案 -->
<!-- <mapper resource="mapper/FlowerMapper.xml" /> -->
<!-- 接口绑定方案 -->
<package name="mapper"/>
</mappers>
package中设置的是接口的包名
3、配置接口
public interface FlowerMapper {
List<Flower> selectAll();
List<Flower> selectById2(int id1,int id2);
}
接口中的方法selectById2与mapper中的selectById2相对应。
4、执行sql语句
public static void main(String[] args) throws IOException {
InputStream ins=Resources.getResourceAsStream("SqlMapConfig2.xml");
SqlSessionFactory sqlSessionFactory=new SqlSessionFactoryBuilder().build(ins);
SqlSession sqlsession=sqlSessionFactory.openSession();
//mybatis自动实例化接口
FlowerMapper fm=sqlsession.getMapper(FlowerMapper.class);
//实现查询
List<Flower> list=fm.selectAll();
for(Flower f:list){
System.out.println(f.toString());
}
System.out.println("--------------------------");
//多参数传递
list=fm.selectById2(1,2);
for(Flower f:list){
System.out.println(f.toString());
}
System.out.println("--------------------------");
}
最后的输出结果为:
Flower [id=1, name=牡丹, price=3.0, production=无]
Flower [id=2, name=兰花, price=6.0, production=无]
Flower [id=3, name=百合, price=5.0, production=无]
Flower [id=9, name=太阳花, price=9.0, production=ab]
--------------------------
Flower [id=1, name=牡丹, price=3.0, production=无]
Flower [id=2, name=兰花, price=6.0, production=无]
--------------------------