JavaWeb学习--MyBatis框架增删改查案例与动态SQL
MyBatis框架增删改查案例与动态SQL
环境准备
开始之前先装一个mybatisx插件,方便跳转xml和接口方法,和生成对应id
查询
<!--UserMapper.xml-->
<?xml version="1.0" encoding="UTF-8" ?>
<!--sql映射文件-->
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--
namespace:名称空间
-->
<mapper namespace="BrandMapper">
<!--id:唯一标识符 resulttype:POJO类类型-->
<select id="selectAll" resultType="Brand">
select *
from tb_brand;
</select>
</mapper>
//BrandMapper.class
import java.util.List;
public interface UserMapper {
List<User> selectAll();
}
测试类
//测试类
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 {
//1.加载mybatis的核心配置文件,获取sqlsessionfactory
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//2.获取sqlsession对象,用它来执行sql
SqlSession sqlSession = sqlSessionFactory.openSession();
//3.执行sql
BrandMapper brandMapper = sqlSession.getMapper(BrandMapper.class);
//4.执行方法
List<Brand> brands = brandMapper.selectAll();
System.out.println(brands);
//4.释放资源
sqlSession.close();
}
}
最后记得配置文件里加上
<!--加载SQL映射文件-->
<mapper resource="BrandMapper.xml"/>
<!--
*参数占位符:
1.#{}:会将其替换为?,为了防止SQL注入
2.$:拼sql。会存在SQL注入问题
3.使用时机:
*参数传递的时候:#{}
*表名或者列名不固定的情况下:$手会存在SQL注入问题
-->
<select id="selectById" resultMap="brandResultMap">
select *
from tb_brand where id = #{id};
</select>
参数类型与转义字符的处理
CDTAT区
转义字符,不同符号转义字符不一样
动态sql
本文来自博客园,作者:Makondo,转载请注明原文链接:https://www.cnblogs.com/Makondo/p/15836926.html