文章目录
MyBatis简介
MyBatis是一个持久层框架,用来简化JDBC开发。
JDBC开发主要存在两个缺点:
一是硬编码,sql语句写在代码中,不利于修改。
二是操作繁琐,需要手动将查询结果放入实体类(实体类过于繁琐)。
MyBatis通过配置文件,取代手动初始化和连接数据库的代码,同时统一管理sql语句。
通过对应的API简化了几乎所有的JDBC代码。
MyBatis初始配置
在pom.xml中导入jar包
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.11</version>
</dependency>
创建mybatis-config.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">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="org/mybatis/example/BlogMapper.xml"/>
</mappers>
</configuration>
其中,property
是四个关键属性,这里不多赘述。
mapper
填写映射配置文件(xml格式)的路径。
将idea连接数据库,获取sql语句补全
填写对应的数据库名称和密码
Mapper映射
映射是指,一个工程需要很多sql语句,对于每个sql语句单独编写相应的代码,开发效率过低。
mybatis将所有的sql语句写在配置文件中,进行统一管理。
为了精确的定位每个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="org.mybatis.example.BlogMapper">
<select id="selectBlog" resultType="Blog">
select * from Blog where id = #{id}
</select>
</mapper>
其中,命名空间和select标签中的语句需要修改。
上面配置文件的含义是:namespace空间中,有名称为id=selectBlog
的查询语句,这语句返回一个类名为Blog
的类。
注:sql语句中的某些字符写在xml中会报错,例如"<"。解决方案有转义字符(<)和CDATA区。
代理开发
代理开发是创建一个接口,接口的url对应配置文件的namespace,接口的方法对应配置文件中每一个sql语句。
在不使用代理开发时,执行sql语句的代码如下(官网示例):
try (SqlSession session = sqlSessionFactory.openSession()) {
Blog blog = (Blog) session.selectOne("org.mybatis.example.BlogMapper.selectBlog", 101);
}
在使用代理开发时,执行 sql语句的代码如下:
try (SqlSession session = sqlSessionFactory.openSession()) {
BlogMapper mapper = session.getMapper(BlogMapper.class);
Blog blog = mapper.selectBlog(101);
}
可以看出,使用使用代理开发的方法,首先声明了一个映射器类(接口),这个映射器类对应的就是一个XML的mapper标签,然后调用对应的方法(selectBlog)即可。
这种写法避免了强制类型转换,且避免了字符串 没有补全且容易出错的问题。
查询数据的方法:
-
单个占位符:
在mapper中编写sql语句时加上占位符,占位符可以替换成相应的变量<select id="selectByName" resultType="Pojo.student"> select * from student where name=#{name}; </select>
占位符有两种格式,一种是
#{}
,另一种是${}
在mapper接口中添加对应的接口即可public interface studentMapper { // List<student>selectAll(); List<student> selectByName(String name); }
-
多个条件查询:
方法1:
再接口处定义多个参数,通过注解和xml文件映射
sql语句:<select id="selectByCondition" resultType="Pojo.student"> select * from student where name=#{name} and age=#{age} </select>
接口:
//使用@Param注解 List<student> selectByCondition(@Param("name") String name,@Param("age")int age);
调用:
//直接传参即可 List<student>x=mapper.selectByCondition("张三",18);
方法2:
直接传入一个类(JavaBean),表示参数://直接传参即可 List<student>x=mapper.selectByCondition(selectStudent); //selectStudent中的参数会作为查询的参数
方法3
map传参 -
resultMap映射查询结果
为了解决sql表和实体类中名称不一致,可以使用resultMap进行结果映射。
下面代码将sql表上x列的查询结果映射到了y变量上。<resultMap id="map1" type="Pojo.student"> <result column="x" property="y"/> </resultMap> <select id="selectAll" resultMap="map1"> </select>
动态sql语句
动态sql靠Mybatis提供的标签实现,这里介绍<where>
和<if>
标签
where
标签用来替换sql语句中的where关键词
if
标签用来判断sql语句中那些条件需要执行。
例如:
有如下sql代码:
<select id="selectByCondition" resultType="Pojo.student">
select * from student
<where>
<if test="name!=null">and name=#{name}</if>
<if test="age!=null">and age=#{age}</if>
</where>
</select>
在执行sql时,如果两个参数均为null,语句也可以执行。
List<student>x=mapper.selectByCondition(null,null);
添加和修改数据
编写接口:
void insertStudent(student student);
编写sql语句:
<insert id="insertStudent">
insert into student(student_number,name,gender,age,department)
values(#{student_number},#{name},#{gender},#{age},#{department});
</insert>
测试程序:
student st=new student();
//此处给st赋值
mapper.insertStudent(st);
返回添加数据的主键:
<insert useGeneratedKeys="true" keyProperty="student_number">
修改数据使用update
标签即可,动态修改使用set
标签和if
标签
删除数据
-
单个删除
<delete id="deleteStudent"> delete from student where name=#{name} </delete>
-
批量删除
编写xml配置:</delete> <delete id="deleteStudents"> delete from student where name in( <foreach collection="names" item="name" separator=","> #{name} </foreach> ); </delete>
foreach
表示遍历names数组中的每个数值,将所有遍历过的元素替换到sql语句中(替换name),并使用逗号隔开。接口:
传入一个names数组。void deleteStudents(@Param("names") String[] names);
测试类:
String []names=new String[2]; names[0]="张三"; names[1]="张四"; mapper.deleteStudents(names);
注解开发
注解开发是将sql语句写在接口的注解中,从而不需要配置xml配置文件。
注解开发不适用于复杂sql,因此还是配置xml文件比较常用。
常用的有四种注解,分别对应增删查改:
@select
@delete
@update
@insert
示例:
@Select("select * from student")
public Student selectAll();
总结:
MyBatis开发流程:
编写接口->编写sql语句->执行sql语句。
补充:MyBatis其他配置
注意:配置文件标签书写顺序需要遵守
configuration(配置)
properties(属性)
settings(设置)
typeAliases(类型别名)
typeHandlers(类型处理器)
objectFactory(对象工厂)
plugins(插件)
environments(环境配置)
environment(环境变量)
transactionManager(事务管理器)
dataSource(数据源)
databaseIdProvider(数据库厂商标识)
mappers(映射器)
类型别名(typeAliases)
类型别名可为 Java 类型设置一个缩写名字。 它仅用于 XML 配置,意在降低冗余的全限定类名书写。例如:
<typeAliases>
<typeAlias alias="Author" type="domain.blog.Author"/>
<typeAlias alias="Blog" type="domain.blog.Blog"/>
<typeAlias alias="Comment" type="domain.blog.Comment"/>
<typeAlias alias="Post" type="domain.blog.Post"/>
<typeAlias alias="Section" type="domain.blog.Section"/>
<typeAlias alias="Tag" type="domain.blog.Tag"/>
</typeAliases>
当这样配置时,Blog 可以用在任何使用 domain.blog.Blog 的地方。
也可以指定一个包名,MyBatis 会在包名下面搜索需要的 Java Bean,比如:
<typeAliases>
<package name="domain.blog"/>
</typeAliases>
每一个在包 domain.blog 中的 Java Bean,在没有注解的情况下,会使用 Bean 的首字母小写的非限定类名来作为它的别名。 比如 domain.blog.Author 的别名为 author;若有注解,则别名为其注解值。