注解方式
回顾前面的PersonDao类,首先我们是通过@Mapper声明这是一个mybatis访问数据库的接口,SQL语句是通过@Select、@Insert、@Delete、@Update注解的方式传递的,这样的方式写SQL语句的的缺点就是不能动态变化。
获取全部用户 select * from person
根据名称获取用户 select * from person where name = #{name}
...
如此类推,我们就要写很多不同的SQL语句来满足我们的需求,这样PersonDao类就很越来越大,
导致很难维护了
xml方式
其实mybatis本身就支持xml的方式来写SQL语句了。首先在application.properties配置mybatis
#xml文件的位置
mybatis.mapperLocations: classpath:/mapper/**/*.xml
#输出日志
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
然后在resources新建一个mapper文件夹,然后再新建一个person文件夹,最后新建一个Person.xml
一般mapper的目录结构都大致如图 目录结构 /mapper/person/person.xml 对应 /mapper/**/*.xml
*号表示任意名称
mapper.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.example.myFirstMaven.dao.PersonDao">
</mapper>
如何在xml写sql
首先我们先了解下什么是mapper.xml文件。被<>包含我们为标签,标签必须以<>开头</>结尾,但是也有例外可以直接一个</>。
mapper.xml:
首行<?xml version="1.0" encoding="utf-8"?>声明编码格式为utf-8
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
声明文档类型dtd, 也就是xml的语法要符合mybatis的xml语法。
接下就是 <mapper></mapper>我们可以将他理解为一个文件夹,对应的我们在文件夹里面就可以添加新的文件夹,例如<mapper><select></select></mapper>,在文件夹了添加文件就比如<mapper><select> select * from person</select></mapper>
那么我们的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.example.myFirstMaven.dao.PersonDao">
<select id="getList" resultType="com.example.myFirstMaven.entity.Person">
select * from person
</select>
</mapper>
- namespace对应Dao类
- select标签,查询语句都有用
<select>标签,id为对应dao的方法,resultType就是放回类型,方法List<Person>getList()返回的一个List,泛型为Person,mybatis会帮我们根据泛型自动封装好List的。
接下来运行下test类,我们先把PersonDao中的@select注解去掉,然后在test类中运行getPersonList类,这样我们就能正常的运行了。
动态SQL
在<select>我们可以编写mybatis提供的逻辑判断标签<where> <if>
为了与之前做区别我们新建一个getListByParams的方法,在PersonDao新建
getListByParams的方法,写上对应的sql
@Test
public void getPersonList(){
Person person = new Person();
person.setName("小马");
System.out.println(personDao.getListByParams(person));
}
<select id="getListByParams" resultType="com.example.myFirstMaven.entity.Person">
select * from person
<where>
<if test="name != null and name != ''">
and name = #{name}
</if>
<if test="age != null and age != ''">
and age = #{age}
</if>
</where>
</select>
当我们传入的有不同的参数时,mybatis就会帮我们动态拼接sql
当我们的参数为age=28时
select * from person WHERE name = ? 变为select * from person WHERE age = ?
如何大家想更进一步的学习mybatis的动态 SQL 可以 点击mybatis的官网 动态 SQL