MyBatis查看详情
-
编写接口方法:Mapper接口。参数:id,结果Brand。
在BrandMapper类下面添加方法
public interface BrandMapper { ? ? ? /** * 查询所有 */ List
selectAll(); ? /** * 查看详情:根据Id查询 */ Brand selectById(int id); ? } -
编写SQL语句:SQL映射文件
在BrandMapper.xml下编写文件
<?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"> ? <mapper namespace="com.uestc.mapper.BrandMapper"> ? ? ? <resultMap id="brandResultMap" type="brand"> <result column="brand_name" property="brandName" /> <result column="company_name" property="companyName" /> ? resultMap> ? <select id="selectAll" resultMap="brandResultMap"> ? select * from tb_brand; ? select> ? ? ? ? ? ? ? ? ? ? <select id="selectById" resultMap="brandResultMap"> select * from tb_brand where id < ]]> #{id}; select> ? mapper>
-
执行方法,测试
编写测试方法MyBatisTesl类
@Test public void testSelectById() 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(); ? }
总结:
1.参数占位符:
(1)#{}:执行SQL时,会将#{}占位符替换为?将来自动设置参数
(2)${}:拼SQL。会存在SQL注入问题。
(3)使用时机:
*参数传递:都使用#{}
*如果要对应表名,列名进行动态设置,只能使用${}进行sql拼接。
2.parameterType:
*用于设置参数类型,该参数可以忽略
3.SQL语句中特殊字符处理:
*转义字符
*