mybatis实现查看详情

  • 查看详情

      1.编写接口方法:Mapper接口

        ***参数:id 结果Brand

Brand selectByld(int id);

      2.编写SQL语句:SQL映射文件

      3.执行方法,测试

步骤一:

BrandMapper.java文件里面创建方法名称

 

//BrandMapper.java
//
根据id 查看详情 Brand selectById(int id);

 

步骤二:

通过mybatisx自动生成sql语句,删除resultType属性,修改成为resyltMap的属性

 

参数占位符
1. #{}: 会将其替换成?号
2. ${}: 拼sql。会存在SQL注入问题
Ps.使用时机: * 参数传递的时候:#{}
* 表名或者列名不固定的情况下:${} 会存在SQL注入问题

 

<!--参数类型:parameterType可以省略-->
<select id="selectById"  parameterType="int" resultMap="brandResultMap"> 
select *
from tb_brand where id = #{id};
</select>

步骤三:

在MyBatisTest.java文件中,添加方法 

 //根据id查询详情
    public void selectById() throws IOException {
       //接受参数
         int id = 1; //现在是固定数据,以后会变成动态数据

       //1. 获取SqlSessionFactory
       String resource = "mybatis-config.xml";
       InputStream inputStream = Resources.getResourceAsStream(resource);
       SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
       //2.获取Sqlsession对象
       SqlSession sqlSession = sqlSessionFactory.openSession();

       //3.获取Mapper接口的代理对象
       BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);

       //4.执行方法
       Brand brand = brandMapper.selectById(id);
        System.out.println(brand);

       //5.释放资源
       sqlSession.close();
 }

结果:

 

posted @ 2023-03-25 13:09  YE-  阅读(324)  评论(0编辑  收藏  举报