根据id查询详情数据
先在接口中定义相关的方法
package mapper;import jgdabc.Brand;import java.util.List;public interface BrandMapper {// List<Brand> selectAll();Brand selectByIdBrand(int id);}
然后映射文件里面的sql语句

映射的sql语句
select *from tb_brand where id = #{id};
{}是参数占位符
执行SQL时,会将 #{} 占位符替换为?,将来自动设置参数值。
还有一种占位符是${},但是可能会引起sql注入的问题,所以使用#{}比较安全
然后主要的测试方法
package jgdabc_;import jgdabc.Brand;import mapper.BrandMapper;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;import static jgdabc_.MyBatisTest.testSelectAll;public class MyBatisTest01 {public static void main(String[] args) throws IOException {testSelectById();}public static void testSelectById() throws IOException {//接收参数int id =1;//获取SqlSessionFactoryString resource = "mybatis-config.xml";InputStream inputStream = Resources.getResourceAsStream(resource);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);//获取SqlSessionSqlSession sqlSession = sqlSessionFactory.openSession();//获取Mapper接口代理对象BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);Brand brand = brandMapper.selectByIdBrand(id);System.out.println(brand);//释放资源sqlSession.close();}}
在映射文件中有一些需要注意的转义字符。
比如我们要去id小于某个值得数据,那么在xml映射文件中是不允许这样直接输入小于号的。
可以这样输入大写的cd然后根据idea给出的提示打出输出的转义,然后在里面写小于号。
<select id="selectOnly" resultMap="brandResultMap">select * from tb_brand where id <![CDATA[<#{id_1};]]></select>
在写这个id之前最好在接口中写入,然后可以让接口在这里自动生成这个id,然后根据我们的需要做出一些改动即可。然后还是一样的方式,在测试类中引入这个id,我们班可以认为它是方法。
框架就是这样,你可以认为它很死板,减少一些隐含的操作,但是在你使用它之前,没有基础过渡是绝对不行的。
