目录

MyBatis配置文件

# 配置文件

# MyBatis配置文件

以下面配置文件为例:

<?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>  
    <typeAliases>
	    <package name="com.test.mapper"/>
    </typeAliases>
    <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:///testing?"/>  
                <property name="username" value="root"/>  
                <property name="password" value="Lam1134312514"/>  
            </dataSource>        
        </environment>    
    </environments>    
    <mappers>        
	    <mapper resource="com/testbatis/mapper/FirstMapper.xml"/>  
    </mappers>
</configuration>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23

<environments> - 配置数据库连接环境信息,可以配置多个environment,通过default属性切换不同的environment,填写environment的id即可切换 <transactionManager> - 事务管理,将来学了Spring后不需要使用MyBatis管理事务。 <dataSource> - 数据源信息,主要配置登入凭证,将来用到Spring会被接管,因此不需要过多理解。 <typeAliases> - 配置完成后,以后使用到相同包路径时,不需要再填写一长串包名

# 查询

如果我们要根据ID查询对应信息该怎么做?

<select id="selectID" resultType="com.tommy.Brand">  
    select * from tb_brand where id = #{id};  
</select>
1
2
3

在上述例子中,你能看到我们在查询语句里加入了一个替代符#{id},该符号类似于JDBC 防注入的?,然后我们去接口处找到selectID()方法,在方法中填入接收的参数得到select(int ID)然后我们可以调用对应方法进行查询即可。

# 多条件查询

那么倘若我们需要查询同时满足N个条件的,该怎么办呢? ![[Pasted image 20220608225405.png]] 上面的代码中,我们能发现一个新东西。 在接口中,方法的参数多了一个@Param("status"),这又是做什么的呢? 当我们定义接收多个参数时,程序并不知道哪个参数对应哪个替代符,因此我们需要用这种方式告诉他对应关系。@Param()中需要填写替代符的名称,且一定要和查询语句中的替代符名称一致。

# 动态SQL

那么有时用户未必会填入所有条件,例如有三个条件分别是:公司ID,公司名称,母公司。用户只查询ID和名称该怎么办呢?

MyBatis还给我们提供了条件判断

# if
<select id="findActiveBlogWithTitleLike"
     resultType="Blog">
  SELECT * FROM BLOG
  WHERE state = ‘ACTIVE’
  <if test="title != null">
    AND title like #{title}
  </if>
</select>
1
2
3
4
5
6
7
8

在该例子中,你能看到一个新的标签<if test="">该标签是用于判断是否满足test中的描述的。如果描述则拼接if中的语句,否则无视。这样我们就能判断用户是否填入了某个参数。

# choose、when、otherwise

有时候,我们不想使用所有的条件,而只是想从多个条件中选择一个使用。针对这种情况,MyBatis 提供了 choose 元素,它有点像 Java 中的 switch 语句

还是上面的例子,但是策略变为:传入了 “title” 就按 “title” 查找,传入了 “author” 就按 “author” 查找的情形。若两者都没有传入,就返回标记为 featured 的 BLOG(这可能是管理员认为,与其返回大量的无意义随机 Blog,还不如返回一些由管理员精选的 Blog)。

<select id="findActiveBlogLike"
     resultType="Blog">
  SELECT * FROM BLOG WHERE state = ‘ACTIVE’
  <choose>
    <when test="title != null">
      AND title like #{title}
    </when>
    <when test="author != null and author.name != null">
      AND author_name like #{author.name}
    </when>
    <otherwise>
      AND featured = 1
    </otherwise>
  </choose>
</select>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

# trim、where、set

上面的if例子中难免会遇到一个棘手的问题,倘若

<select id="findActiveBlogLike"
     resultType="Blog">
  SELECT * FROM BLOG
  WHERE
  <if test="state != null">
    state = #{state}
  </if>
  <if test="title != null">
    AND title like #{title}
  </if>
  <if test="author != null and author.name != null">
    AND author_name like #{author.name}
  </if>
</select>
1
2
3
4
5
6
7
8
9
10
11
12
13
14

问题:

  1. 假设没有匹配的条件怎么办?
  2. 假设只匹配到第二条件怎么办?

这两个问题都会导致语句语法出错,这显然是不被允许的!

因此我们需要用到where关键词解决该问题,将if放在里面。

<select id="findActiveBlogLike"
     resultType="Blog">
  SELECT * FROM BLOG
  <where>
    <if test="state != null">
         state = #{state}
    </if>
    <if test="title != null">
        AND title like #{title}
    </if>
    <if test="author != null and author.name != null">
        AND author_name like #{author.name}
    </if>
  </where>
</select>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

where元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。

更多使用说明:mybatis – MyBatis 3 | 动态 SQL (opens new window)

# 增加

先前我们在BrandMapper.xml中配置了<select>标签,这是否意味着还有其他标签呢? ![[Pasted image 20220609131958.png]]

没错!在MySQL用到的增删改查都在这,添加对应标签就能使用对应功能了,根据SQL语法也不难猜出在MyBatis中的格式。

<insert id="add">
	insert into mytable values (#{id},#{brand_name},#{company_name})
</insert>
1
2
3

# 获取特定值

有时,我们在添加至于还希望获取所添加项的ID,这该如何是好?

<insert id="add" useGeneratedKeys="true" keyProperty="id">  
    insert into tb_brand (brand_name,company_name,ordered,description,status) values (#{brand_name},#{company_name},#{ordered},#{description},#{status});  
</insert>
1
2
3

我们在<insert>标签处添加useGeneratedKeyskeyProperty即可。

然后以类的方式封装数据并添加进数据库,即:

// 主类
public static void main(String[] args) throws IOException {  
  
    //1. 加载mybatis的核心配置文件,获取SqlSessionFactory  
    String resource = "mybatis-config.xml";  
    InputStream inputStream = Resources.getResourceAsStream(resource);  
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);  
  
    //2. 获取SqlSession对象,用它来执行sql  
    SqlSession sqlSession = sqlSessionFactory.openSession();  
  
    Brand b = new Brand();  
    b.setBrand_name("Mango");  
    b.setCompany_name("Mango OTC.");  
    b.setOrdered(4);  
    b.setDescription("Mango!! NO.1");  
    b.setStatus(1);  
  
    //3. 执行sql  
    BrandMapper um = sqlSession.getMapper(BrandMapper.class);  
    um.add(b);  
  
    sqlSession.commit();  //必须添加这句,否则add不会添加进数据库
    System.out.println(b.getId());  
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
最近更新
01
基本知识
07-18
02
卷积神经网络识别图像
07-18
03
损失函数
07-18
更多文章>