编写mapper接口
package com. ljh. mapper ;
import com. ljh. pojo. Brand ;
import java. util. List ;
public interface BrandMapper {
public Brand selectById ( int id) ;
}
生成mapper语句
<?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.ljh.mapper.BrandMapper" >
< resultMap id = " brandResultMap" type = " brand" >
< result column = " brand_name" property = " brandName" > </ result>
< result column = " company_name" property = " companyName" > </ result>
</ resultMap>
< select id = " selectById" resultMap = " brandResultMap" >
select *
from tb_brand where id = #{id};
</ select>
</ mapper>
app测试
package com. ljh. test ;
import com. ljh. mapper. BrandMapper ;
import com. ljh. pojo. Brand ;
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 org. junit. Test ;
import java. io. IOException ;
import java. io. InputStream ;
import java. util. List ;
public class MybatisTest {
@Test
public void testSelectAll ( ) throws IOException {
String resource = "mybatis-config" ;
InputStream inputStream = Resources . getResourceAsStream ( resource) ;
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder ( ) . build ( inputStream) ;
SqlSession sqlSession = sqlSessionFactory. openSession ( ) ;
BrandMapper mapper = sqlSession. getMapper ( BrandMapper . class ) ;
int id = 1 ;
Brand brand = mapper. selectById ( id) ;
System . out. println ( brand) ;
sqlSession. close ( ) ;
}
}
运行结果 资源分析 select * from tb_brand where id = #{id}; 对于#{id}:参数占位符/还有
i
d
都可以用。但是
{id}都可以用。但是
i d 都可以用。但是 {id}会存在sql注入问题,不太好 使用时机:参数传递:#{id} 动态查询表:${id}:动态查询要将表名传输给数据库时有用。
parameterType:获取的参数类型:一般不写。因为一般接口方法的形参就给定了。 特殊字符的处理:如<符号会报错
解决办法:< 解决办法:CDATA区