mybatis的环境搭建和简单使用

Mybatis的环境搭建和简单使用

什么是 MyBatis ?

MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJO(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。

Mybatis环境搭建及简单实例

Maven依赖##

配置mybatis,mysql,配置文件

 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd">
 3 <configuration>
 4 
 5   <!-- 引入外部配置文件 -->
 6   <properties resource="mysql.properties"></properties>
 7    
 8    <!-- 配置mybatis运行环境 -->
 9      <environments default="cybatis">
10         <environment id="cybatis">
11             <!-- type="JDBC" 代表使用JDBC的提交和回滚来管理事务 -->
12             <transactionManager type="JDBC" />
13             
14             <!-- mybatis提供了3种数据源类型,分别是:POOLED,UNPOOLED,JNDI -->
15             <!-- POOLED 表示支持JDBC数据源连接池 -->
16             <!-- UNPOOLED 表示不支持数据源连接池 -->
17             <!-- JNDI 表示支持外部数据源连接池 -->
18             <dataSource type="POOLED">
19                 <property name="driver" value="${jdbc.driver}" />
20                 <property name="url" value="${jdbc.url}" />
21                 <property name="username" value="${jdbc.username}" />
22                 <property name="password" value="${jdbc.password}" />
23             </dataSource>
24         </environment>
25     </environments> 
26     
27 </configuration>

需要的架包

<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>

<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.0</version>
</dependency>

<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>

<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.12</version>
</dependency>

其中log4j需要一个properties配置文件

# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

.编写主配置文件

<?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>

<!-- 配置myabtis的默认数据源-->
<environments default="devlopment">
<!-- 数据源-->
<environment id="devlopment">
<!--事务管理 -->
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql://localhost:3306/databaseName?characterEncoding=utf-8"></property>
<property name="username" value="username"></property>
<property name="password" value="password"></property>
</dataSource>
</environment>
</environments>

<mappers>
<!--
使用资源的绝对路径
<mapper url=""/>

-->

<!-- 资源的相对路径-->
<mapper resource="User.xml"></mapper>
<!--
Mapper接口的全类名
要求:Mapper接口的名称与映射文件名称一致且必须在同一个目录下
<mapper class="com.qf.mapper.UserMapper"/>
-->

<!-- 加载某个包下的映射文件 (推荐)
要求:Mapper接口的名称与映射文件名称一致且必须在同一个目录下

<package name="com.qf.mapper"/>

-->
</mappers>

</configuration>

如果mapper 标签使用package标签,须在pom文件内加入以下代码

<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>

编写mybatis.xml文件(命名建议与dao接口一致)


<?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="dao接口全类名">
<select id="selectById" parameterType="java.lang.Integer" resultType="com.qf.domain.User">
select * from user where id = #{id}
</insert>
</mapper>

调用Mapper接口方式

//调取对应的接口
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User user1 = mapper.selectById2(38);
System.out.println(user1);

SQL映射文件的几个顶级元素

mapper:映射文件的跟元素节点,只有一个属性namespace(命名空间).其作用如下:
用于区分不同的mapper,全局唯一。绑定DAO接口,即面向接口编程。当namespace绑定某一接口之后,可以不用写该接口的实现类,MyBatis会通过接口的完整限定名查找到对应的mapper配置文件来执行SQL语句。因此namespace的命令必须要跟接口同名。

cache:配置给定命名空间的缓存

cache-ref:从其他命名空间引用缓存配置

resultMap:用来描述数据库结果集和对象的对应关系

sql:可以重用SQL块,也可以被其他语句引用

insert:映射插入语句

resultType和resultMap的区别是什么

返回类型可以用resultType也可以用resultMap
resultType是直接表示返回类型
resultMap则是对外部ResultMap的引用
两者不能同时存在

注解方法传参数

  1. mapper层
    Mapper接口类
    User logon(@Param(“user_name”)String user_name,@Param(“password”)String password);
    Mapper.xml文件

    select

    from sys_user
    where user_name = #{user_name,jdbcType=VARCHAR} and password = #{password,jdbcType=VARCHAR}

    这里主要注意接口传入参数前面加了@Param注解

谈谈对association和collection元素的理解

public class A{
private B b1;
private List b2;
}
在映射b1属性时用association标签, 映射b2时用collection标签,分别是一对一,一对多的关系

动态SQL

动态sql包括那些

if
choose, when, otherwise
trim, where, set
foreach

动态sql的用处

MyBatis 的强大特性之一便是它的动态 SQL。如果你有使用 JDBC 或其它类似框架的经验,你就能体会到根据不同条件拼接 SQL 语句的痛苦。例如拼接时要确保不能忘记添加必要的空格,还要注意去掉列表最后一个列名的逗号。利用动态 SQL 这一特性可以摆脱这种痛苦。

if

动态 SQL 通常要做的事情是根据条件包含 where 子句的一部分。比如:

<select id="selByName" resultType="yuan.yuanmybatis.entity.Account">       select id,name,created,updated from account where 1=1       <if test="name !=null and name !=''">           and name like concat('%',#{name},'%')       </if>    </select>

这条语句提供了一种可选的查找文本功能。如果没有传入“title”,那么所有处于“ACTIVE”状态的BLOG都会返回;反之若传入了“title”,那么就会对“title”一列进行模糊查找并返回 BLOG 结果。

choose, when, otherwise

有时我们不想应用到所有的条件语句,而只想从中择其一项。针对这种情况,MyBatis 提供了 choose 元素,它有点像 Java 中的 switch 语句。

<select id="selByChoose" resultType="yuan.yuanmybatis.entity.Account">      
  select id,name,created,updated,money from account where 1=1        <choose>    
          <when test="name !=null and name !=''">         
                 and name like concat('%',#{name},'%')            </when>        
                     <when test="money !=null and money !=''">                and name =#{money}         
                        </when>    
                                <otherwise>      
                                          and isdeleted=1
                                                      </otherwise>        </choose>   
                                                       </select>

trim, where, set

我们看下面这个例子,如果将“ACTIVE = 1”设置成动态的条件,看看会发生什么。

<select id="selByName" resultType="yuan.yuanmybatis.entity.Account">    select id,name,created,updated from account    <where>    <if test="name !=null and name !=''">        and name like concat('%',#{name},'%')    </if>    </where>    </select>

trim

<select id="selByChoose" resultType="yuan.yuanmybatis.entity.Account">        select id,name,created,updated,money from account        <trim prefix="where" prefixOverrides="and">        <choose>            <when test="name !=null and name !=''">                and name like concat('%',#{name},'%')            </when>            <when test="money !=null and money !=''">                and name =#{money}            </when>            <otherwise>                and isdeleted=1            </otherwise>        </choose>        </trim>    </select>

set

类似的用于动态更新语句的解决方案叫做 set。set 元素可以用于动态包含需要更新的列,而舍去其它的。比如:

<update id="updateAccout" parameterType="yuan.yuanmybatis.entity.Account">     
   update account     
      <set>  
                <if test="name !=null and name !=''">               name=#{name},     
                       </if>         
                          <if test="money!=null and money!=''">               money=#{money}          
                            </if>   
                                 </set>      
                                   where id=#{id}
                                       </update>

这里,set 元素会动态前置 SET 关键字,同时也会删掉无关的逗号,因为用了条件语句之后很可能就会在生成的 SQL 语句的后面留下这些逗号。(译者注:因为用的是“if”元素,若最后一个“if”没有匹配上而前面的匹配上,SQL 语句的最后就会有一个逗号遗留)

若你对 set 元素等价的自定义 trim 元素的代码感兴趣,那这就是它的真面目:
注意这里我们删去的是后缀值,同时添加了前缀值。

foreach

动态 SQL 的另外一个常用的操作需求是对一个集合进行遍历,通常是在构建 IN 条件语句的时候。比如:

<select id="selIn" resultType="yuan.yuanmybatis.entity.Account">        select id,name,created,updated from account where name in        <foreach collection="nameList" index="index" item="name" open="(" separator="," close=")">        #{name}       </foreach>   </select>

foreach 元素的功能非常强大,它允许你指定一个集合,声明可以在元素体内使用的集合项(item)和索引(index)变量。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值