MyBatis初识
一、第一个MyBatis程序
1、导入依赖
- Mybatis
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
- Junit
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
2、核心配置文件
<?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">
<!--最前面是xml的头部 用来验证xml 是否正确-->
<configuration>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="${jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC}"/>
<property name="username" value="${root}"/>
<property name="password" value="${452387}"/>
</dataSource>
</environment>
<!-- 这里是连接所需的一些基本信息的配置 事务配置和连接池管理也在这-->
</environments>
<mappers>
<mapper resource="com/lxc/mapper/UserMapper.xml"/>
</mappers>
<!-- 映射器 resource 的值要为全路径名 路径所指定的具体xml文件 包含了 sql代码和映射定义信息-->
</configuration>
我们还可以使用java类来替代配置文件 达到和xml文件一样的效果
3、持久层接口
public interface UserMapper {
ArrayList<User> selectAllUser();
User selectUserById(int id);
int deleteUser(int id);
void update(int id);
void addUser(User user);
}
我们把增删改查都试一遍
6、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.lxc.mapper.UserMapper">
<!-- 在xml文件中都是写全限定类名-->
<select id="selectAllUser" resultMap="java.util.ArrayList">
select * from user
</select>
<!-- 一个搜索语句-->
</mapper>
7.测试
@Test
public void sqlTest() throws IOException {
SqlSessionFactory factory=DbUtilForMybatis.getSqlSessionFac();
try(SqlSession sqlSession=factory.openSession()) {//我们使用带资源的try 语句 在 try 语句体执行完毕后会自动关闭资源
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
//拿到这个mapper 来进行sql 操作
ArrayList<User> users = userMapper.selectAllUser();
//执行接口中的方法
for (User user : users) {
System.out.println(user);
}
}
}
8、出现的问题
1、异常抛出
Cause: org.apache.ibatis.builder.BuilderException: Error parsing SQL Mapper Configuration. Cause: java.io.IOException: Could not find resource com/lxc/mapper/UserMapper.xml
-
因为target 文件中指定目录下没有 UserMapper.xml(xml 映射语句文件) (maven 的静态资源过滤问题)
-
我们把文件直接拷贝进去 但是这样很麻烦,因为后面修改是不会同步的
-
<build> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> </resources> </build>
我们把这个段代码拷贝到 Maven 的pom 文件中 就可以解决了
-
-
sql 语句映射文件的 resultType 结果类型
- 基本类型(包含自定义 引用类型 和 String ) resultType=基本类型
- List resultType=List 集合中元素的类型
- map
- 单条记录 resultType = map
- 多条记录 resultType=map 中 值的类型
二、Mabatis 简单进阶
1、带参数的sql
1.1、select
-
<select id="selectUserById" parameterType="int" resultType="com.lxc.pojo.User"> select * from user where id = #{id} </select>
- parameterType 参数类型
-
User user=userMapper.selectUserById(1); System.out.println(user);
1.2、add
-
<insert id="addUser" parameterType="com.lxc.pojo.User"> insert into user values (#{id}, #{userName}, #{pwd}, ${age}) </insert>
- 插入参数的占位符 需要跟实体类的属性保持名称一致
-
User user = new User(3, "ll", "asdasd", 13); userMapper.addUser(user); sqlSession.commit(); //默认提交事务没有打开 如果不提交事务会回滚
- 需要提交事务
1.3、delete
-
<delete id="deleteUser" parameterType="int"> delete from user where id=#{id} </delete><!-- 删除没有参数么-->
- 删除不能定义返回值的类型 但是 mapper接口中的方法 的返回值还是存在 成功返回 1 失败返回0
-
int result = userMapper.deleteUser(1);sqlSession.commit();System.out.println(result);
1.4、update
-
<update id="update" parameterType="com.lxc.pojo.User"> update user set userName=#{userName}, pwd=#{pwd}, age=#{age} where id = #{id}</update>
- 这样好像不太好 可不可以把Id 单独拿出来呢
-
User user=new User(2,"znLo","asd",19);userMapper.update(user);sqlSession.commit();
2、模糊查询
2.1、代码层拼接通配符
User user1=new User("lx","123",21);User user2=new User("lc","123",21);userMapper.addUser(user1);userMapper.addUser(user2);//拼接通配符ArrayList<User> users = userMapper.fuzzySelectByFirstName("%l%");
- 在java代码层拼接通配符完成模糊查询
2.2、sql映射拼接通配符
-
<!-- 模糊查询--> <select id="fuzzySelectByFirstName" resultType="com.lxc.pojo.User" > select * from user where userName like "%"#{firstName}"%" </select>
-
安全性可能缺失可能会被sql注入
-
select * from user where userName like '%#{firstName}%'<!-- 被拼接成--> select * from user where userName like '%#{(parameter) or 1=1}%'<!-- 会泄露数据库-->
-
三、sql映射参数说明
1、简单类型参数映射
(只有一个参数时可以省略parameterType)
<!-- 简单类型 不使用parameterType--> <select id="getUserById" resultType="com.lxc.pojo.User"> select * from user where id=#{id} </select>
2、复杂参数映射
(java对象)使用parameterType
<update id="update" parameterType="com.lxc.pojo.User"> update user set userName=#{userName}, pwd=#{pwd}, age=#{age} where id = #{id}</update>
(非java对象多个参数)使用注解@Param
3、使用多功能map
当我们需要传入多个参数,因为某些原因而不考虑ParameterType 时我们可以使用map 进行映射参数
<!-- insert 标签内没有attr ResultType--> <insert id="insertUser" parameterType="map"> insert user (id,userName,pwd,age) values (#{id},#{name-},#{pw},#{age111}) </insert>
- 提高了参数命名的灵活性
- 在xml中引用参数时,使用map的key引用 我们根本不用去考虑参数值的类型直接插入