测试方法

@Test public void testSelectByid() throws IOException { //接收变量 int id = 1; //1、获取sqlSessionFactory String rescource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(rescource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //2、获取SqlSession对象 SqlSession sqlSession = sqlSessionFactory.openSession(); //3、获取Mapper接口的代理对象 BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class); //4、执行方法 Brand brand = new Brand(); brand = brandMapper.selectByid(id); System.out.println(brand); //5、释放资源 sqlSession.close(); } }
sql映射文件

<?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"> <!--namespace:名称空间。写接口给的全类名,相当于告诉MyBatis这个配置文件是实现哪个接口的。--> <mapper namespace="com.avb.Mapper.BrandMapper"> <!--resultType=""指定查询数据封装结果的时候使用自定义封装规则--> <select id="selectAll" resultType="brand"> select * from tb_brand; </select> <select id="selectByid" resultType="brand"> select * from tb_brand where id = #{id}; </select> <!--<!–type指定为哪个javaBean自定义封装规则,id是唯一标识–> <resultMap id="mycat" type="smq.javabean.Cat"> <!–id指定主键列的对应规则,column指定哪一列是主键列,property指定cat的哪个属性封装id这个列数据–> <id column="id" property="id"/> <!–普通列–> <result column="cName" property="name"/> <result column="cgender" property="gender"/> <result column="cAge" property="age"/> </resultMap>--> </mapper>
接口文件

package com.avb.Mapper; import com.avb.pojo.Brand; import com.avb.pojo.User; import java.util.List; public interface BrandMapper { //查询所有 List<Brand> selectAll(); //按照id查询 Brand selectByid(int id); }
接收
参数占位符:
#{}:PreparedStatement,会替换成?,可以放置sql注入
${}:拼接sql,存在sql注入问题
参数传递时尽量使用#{}
参数类型
可以指定参数类型
parameterType
特殊字符处理
1、转义字符
2、CDATA区
浙公网安备 33010602011771号