Mybatis
举个小栗子
mybatis配置文件(XML配置文件)
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
<!--通过这个配置文件,完成mybatis与数据库的连接 -->
<configuration>
<!--mybatis 在实例化的时候,会自动扫描这个包下的所有类,用于后续 sql 语句的 resultType-->
<typeAliases>
<package name="com.iweb.entity"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="url" value="jdbc:mysql://localhost:3306/iweb?characterEncoding=utf-8"/>
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="mapper/user.xml"/>
</mappers>
</configuration>
user.xml(实现增删改查的sql语句)
<?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.iweb.entity">
<select id="listUser" resultType="User">select * from user</select>
<!-- parameterType:表示传入的参数类型,可以是基本数据类型,也可以是引用类型
基本类型中需要注意:如果传入的参数为整型,参数“_int” 表示 int 类型,参数“int” 表示 Integer 类型-->
<insert id="addUser" parameterType="User">insert into user values (#{userId},#{username},#{password})</insert>
<delete id="deleteUser" parameterType="String">delete from user where userId = #{userId}</delete>
<update id="updateUser" parameterType="User">update user set username = #{username},password = #{password} where userId = #{userId}</update>
<select id="getUser" parameterType="String" resultType="User">select * from user where userId = #{userId}</select>
<!-- 模糊查询-->
<select id="listUserByNameLike" parameterType="String" resultType="User">select * from user where username like concat('%',#{0},'%')</select>
<!-- 复杂查询-->
<select id="listUserByIdAndNameLike" parameterType="map" resultType="User">select * from user where userId > #{userId} and username like concat('%',#{username},'%')</select>
</mapper>
使用做sql查询(Test)
public void test1() throws IOException {
private SqlSession sqlSession;
@Before
public void init() throws IOException {
// 输入流读取配置文件信息
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
// 基于配置文件获取 mybatis 的一级缓存对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
// 基于这个一级缓存,创建一个二级缓存
sqlSession = sql