文章目录
关于MyBatis
对象关系映射(英语:(Object Relational Mapping,简称ORM)
MySql、Oracle、SqlServer都是关系型数据库
O->R
studentDao.insert(student)
把一个java对象保存到数据库中的一行记录
R->O
Student student = sudentDao.findById(id)
把数据库里面的一行记录封装成一个java对象
mybatis框架运行流程
POJO(Plain Ordinary Java Object)简单的Java对象,实际就是普通JavaBean。
SqlSession就是会话,类似于jdbc里面的Connection,开启了这次会话,就可以发送增删改查的操作,
直到你关闭这个会话。
SqlSessionFactory:生产SqlSession的工厂,作用就是构造返回SqlSession。
mybatis配置
1、SqlMapConfig.xml,此文件作为mybatis的全局配置文件,配置了mybatis的运行环境等信息。
mapper.xml文件即sql映射文件,文件中配置了操作数据库的sql语句。此文件需要在SqlMapConfig.xml中加载。
2、通过mybatis环境等配置信息构造SqlSessionFactory即会话工厂
3、由会话工厂创建sqlSession即会话,操作数据库需要通过sqlSession进行。
4、mybatis底层自定义了Executor执行器接口操作数据库,Executor接口有两个实现,一个是基本执行器、一个是缓存执行器。
5、Mapped Statement也是mybatis一个底层封装对象,它包装了mybatis配置信息及sql映射信息等。mapper.xml文件中一个sql对应一个Mapped Statement对象,sql的id即是Mapped statement的id。
6、Mapped Statement对sql执行输入参数进行定义,包括HashMap、基本类型、pojo,Executor通过Mapped Statement在执行sql前将输入的java对象映射至sql中,输入参数映射就是jdbc编程中对preparedStatement设置参数。
7、Mapped Statement对sql执行输出结果进行定义,包括HashMap、基本类型、pojo,Executor通过Mapped Statement在执行sql后将输出结果映射至java对象中,输出结果映射过程相当于jdbc编程中对结果的解析处理过程。
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">
<configuration>
<environments default="development">
<environment id="development">
<!-- 使用JDBC的事物管理 -->
<transactionManager type="JDBC"/>
<!-- 配饰数据库连接池 -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/java?characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="1234"/>
</dataSource>
</environment>
</environments>
<!-- 加载映射文件 -->
<mappers>
<mapper resource="com/situ/mybatis/entity/StudentMapper.xml"/>
</mappers>
</configuration>
写几个mapper就在“”<mappers.>“”中添加
简单的sql语句
<mapper namespace="student"> //表示名称,最好对应
<!-- 通过id查找学生 -->
<!--parameterType表示输入格式 resultType表示输出格式 -->
<select id="selectById" parameterType="Integer" resultType="com.situ.mybatis.pojo.Student">
select id,name,age,gender,banji_id from student where id=#{id} <!-- #{id}能显示值 -->
</select>
</mapper>
Log4j: 专门用来帮助我们打印日志信息
常见:封装工具类
public class MyBatisUtil {
private static SqlSessionFactory sqlSessionFactory;
static {
String resource = "mybatis.xml";
InputStream inputStream;
try {
inputStream = Resources.getResourceAsStream(resource);
// 创建 SqlSessionFactory Session:会话 (连接数据库后就建立了一次会话,有了会话就可以操作数据库)
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
public static SqlSession getSqlSession() {
// 得到SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession();
return sqlSession;
}
}
@Test
public void testSelectById1() throws IOException {
SqlSession sqlSession = MyBatisUtil.getSqlSession();
// 执行sql语句
Student student = sqlSession.selectOne("student.selectById", 66);
System.out.println(student);
}
起别名
typeAliases类型别名:alias
默认给所有parameterType附加一个cn.itcast.core.bean
在mybatis-config.xml配置别名如下:
<!-- 别名 -->
<typeAliases>
<package name="cn.itcast.core.bean"/>
</typeAliases>
它的作用是让Mapper.xml中的参数找到对应类,如下面parameterType="TestTb">,如果没有配置别名,则要改为parameterType="cn.itcast.core.bean.TestTb">,
基础增删改查操作
<mapper namespace="student">
<!-- public Student selectById(Integer id) {}
parameterType="java.lang.Integer"
resultType="com.situ.mybatis.pojo.Student"
-->
<select id="selectById" parameterType="Integer" resultType="Student">
select id,name,age,gender,banji_id from student where id=#{id}
</select>
<!--public List<Student> selectAll();-->
<select id="selectAll" resultType="Student">
SELECT id,name,age,gender,banji_id FROM student
</select>
<!-- 对于更新类的操作返回的是影响的行数,但是resultType不需要写
public void deleteById(Integer id)
更新类返回影响的行数,在这里不用写返回值类型
-->
<delete id="deleteById" parameterType="Integer">
DELETE FROM student WHERE id=#{id}
</delete>
<!--public void add(Student student)-->
<insert id="add" parameterType="Student">
INSERT INTO
student(name,age,gender,banji_id)
VALUES
(#{name},#{age},#{gender},#{banjiId})
</insert>
<update id="update" parameterType="Student">
UPDATE
student
SET
name=#{name},
age=#{age},
gender=#{gender},
banji_id=#{banjiId}
WHERE
id=#{id}
</update>
</mapper>
resultMap:
如果查询出来的列名和实体类的属性不一致,通过定义一个resultMap对列名和实体类属性名做一个映射关系。
resultMap 元素是 MyBatis 中最重要最强大的元素。
结果集的映射是 MyBatis 最强大的特性,对其有一个很好的理解的话,许多复杂映射的情形都能迎刃而解。使用 resultMap 或 resultType,但不能同时使用。
<!-- resultMap最终是要将结果映射到Student上
当实体类的属性名和表的字段名不一致的时候,必须要写这个映射 -->
<resultMap type="Student" id="studentMap">
<!-- 映射主键属性:如果有多个主键字段,则定义多个id -->
<!-- property:类的属性名 -->
<!-- column:表的字段名 -->
<id column="id" property="id" />
<!-- result定义普通属性 -->
<result column="student_name" property="name" />
<result column="age" property="age" />
<result column="gender" property="gender" />
</resultMap>
<select id="selectAll" resultMap="studentMap">
select id,student_name,age,gender from student
</select>
多表
一对一:
一个学生只属于一个班级。
查询:
SELECT s.id,s.name
,s.age,s.gender,b.id AS banjiId,b.name AS banjiName
FROM student AS s INNER JOIN banji AS b
ON s.banji_id=b.id;
MyBatis中使用association标签解决一对一关联查询,association标签可以使用的属性如下:
*
property:对象属性的名称
*
javaType:对象以昂属性的类型
*
column:数据库中字段的名称(也可能是起的别名)
**column数据库的名,property是类中的,二者映射关系-**
一对多
动态Sql
1:if标签、where标签
(多用于查找)
<select id="selectByCondition" parameterType="Student" resultMap="studentMap">
SELECT <include refid="studentColumns"/>
FROM student
<where>
<if test="name!=null and name!='' ">
AND name LIKE concat('%', #{name} ,'%') 判断不为空,则进行 模糊查找,concat连接前后%,也就是只要含name中的内容就行,首项相同比较年龄,依次推进。
</if>
<if test="age!=null">
AND age=#{age}
</if>
<if test="gender!=null and gender!='' ">
AND gender=#{gender}
</if>
</where>
</select>
2:set标签
(用于部分内容的更新)
<update id="updateCondition" parameterType="Student">
UPDATE student
<set>
<if test="name!=null and name!=''">
name=#{name},
</if>
<if test="age!=null">
age=#{age},
</if>
<if test="gender!=null and gender!=''">
gender=#{gender},
</if>
</set>
WHERE id=#{id}
</update>
3:foreach标签
(处理数组和集合类的)
<delete id="deleteAllByArray" >
DELETE FROM student
WHERE id IN
<foreach collection="array" open="(" item="id" close=")" separator=",">
#{id} <--! 表示array数组内的值一次以separator中,的形式(id1,id2)显示-->
</foreach>
</delete>
<delete id="deleteAllByList" >
DELETE FROM student
WHERE id IN
<foreach collection="list" open="(" item="id" close=")" separator=",">
#{id}
</foreach>
</delete>
4:choose、when、otherwise 标签
(如果用户填写了名字,这个搜索就按照名字来搜索,你即使填写了别的条件也不去拼接,
如果没有填写名字,填写了年龄,就按照年龄来搜索,
如果名字和年龄都没有填写,但是填写了性别就按照性别来查找
name、age、gender搜索时候只能按照其中一个来搜索,但是优先级name>age>gender)
(if----else if----else if ----else)
<select id="selectByCondition" parameterType="Student" resultMap="studentMap">
SELECT
<include refid="studentColumns"/>
FROM
`student`
WHERE
<choose>
<when test="name!=null and name!=''">
name LIKE concat('%', #{name}, '%')
</when>
<when test="age!=null">
age=#{age}
</when>
<when test="gender!=null and gender!=''">
gender=#{gender}
</when>
<otherwise>
</otherwise>
</choose>
</select>```