mybatis总结

一、mybatis简介

MyBatis 是支持普通 SQL 查询,存储过程和高级映射的优秀持久层框架。MyBatis 消除了几乎所有的 JDBC 代码和参数的手工设置以
及对结果集的检索封装。MyBatis 可以使用简单的 XML 或注解用于配置和原始映射,将接口和 Java 的 bean映射成数据库中的记录.
 

二、创建一个demo

 

1、加入jar包

 

 

 2、创建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>

<properties resource="db.properties"/>

<environments default="development">
<environment id="development">
<transactionManager type="JDBC" />
<dataSource type="POOLED">

<property name="driver" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/zhiyou100/szx/mapper/UsersMapper.xml"/>
</mappers>
</configuration>

 3、优化Config.xml文件

将数据库的连接信息单独放在一个新的文件中,文件名为,db.properties

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis
jdbc.username=root
jdbc.password=123123

在配置文件中引用。

 

4.添加日志信息

添加jar包。

 

在资源包resources中添加文件log4j.properties。(名字不可改变)下列为内容。

log4j.properties,

log4j.rootLogger=DEBUG, Console

#Console

log4j.appender.Console=org.apache.log4j.ConsoleAppender

log4j.appender.Console.layout=org.apache.log4j.PatternLayout

log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n

log4j.logger.java.sql.ResultSet=INFO

log4j.logger.org.apache=INFO

log4j.logger.java.sql.Connection=DEBUG

log4j.logger.java.sql.Statement=DEBUG

log4j.logger.java.sql.PreparedStatement=DEBUG

5、增删改查

 

 在Mapper.xml文件中,添加标签,实现增删改查功能。

注意点:mapper.xml中的id名必须与dao类中的方法名完全一致!!!!!

1.添加

<insert id="addUser" parameterType="com.zhiyou100.szx.Users">

insert into users(id,name,sex,age) values(#{id},#{name},#{sex},#{age})

</insert>

 

 parameterType指的是参数类型

id方便dao类调用

resultType指的是返回类型

2.修改

<update id="updateUsers" parameterType="com.zhiyou100.szx.bean.Users">

update users set name=#{name},sex=#{sex},age=#{age} where id=#{id}

</update>

3.删除

<delete id="deleteById" parameterType="int">

delete from users where id=#{id}

</delete>

4.查询

<select id="selectAll" resultType="com.zhiyou100.szx.bean.Users">

select * from users 

</select>

<select id="selectById" parameterType="int" resultType="com.zhiyou100.szx.bean.Users">

select * from users where id=#{id}

</select>

三、解决字段名与实体类属性名不相同的冲突

1.通过在 sql 语句中定义别名

<select id="selectOrder" parameterType="int" resultType="_Order">
select order_id id, order_no orderNo,order_price price from orders where
order_id=#{id}
</select>

2.通过<resultMap>

<select id="selectAll" resultMap="orderMap">

select * from orders 

</select>

<resultMap type="com.zhiyou100.szx.bean.Order" id="orderMap">

<id property="id" column="order_id"/>

<result property="no" column="order_no"/>

 <result property="price" column="order_price"/>

 

</resultMap>

使用resultMap标签,id属性是方便select标签调用。type填写类名。

在select标签中用resultMap=“id”就可以使用了。

四、联表查询

1.多对一

<select id="selectAll" resultMap="clazzMap">

select * from teacher t,class c where c.teacher_id=t.t_id 

</select>

<resultMap type="com.zhiyou100.szx.bean.Clazz" id="clazzMap">

<id property="cid" column="c_id" />

<result property="cname" column="c_name" />

<association property="teacher" column="teacher_id" javaType="com.zhiyou100.szx.bean.Teacher">

<id property="tid" column="t_id" />

<result property="tname" column="t_name" />

</association>

</resultMap>

要在实体类中创建一个新的属性,要连接的表的实例对象。

重点在于association标签,表示连接的表。

property表示属性名,column表示数据库中字段名。

javaType代表实体类名

2.一对多

<select id="selectAll" resultMap="clazzMap">

select * from teacher t,class c,student s where c.teacher_id=t.t_id and c.c_id=s.class_id

</select>

<resultMap type="com.zhiyou100.szx.bean.Clazz" id="clazzMap">

 

<id property="cid" column="c_id" />

<result property="cname" column="c_name" />

<association property="teacher" column="teacher_id" javaType="com.zhiyou100.szx.bean.Teacher">

<id property="tid" column="t_id" />

<result property="tname" column="t_name" />

</association>

<collection property="students" ofType="com.zhiyou100.szx.bean.Student">

<id property="sid" column="s_id" />

<result property="sname" column="s_name" />

</collection>

在多对一过程中,使用collection标签,表示集合中的类名。主要是在实体类中创建一个新的属性,list。

ofType表示代表实体类名(全类名)

 

五、动态SQL

1.   if+where语句       主要是用于条件

<select id="selectUserByUsernameAndSex" resultType="user" parameterType="com.ys.po.User">

select * from user
    <where>
        <if test="username != null">
           username=#{username}
        </if>
         
        <if test="username != null">
           and sex=#{sex}
        </if>
    </where>
</select>
 

2.  if+set语句    主要是用于修改

 
<!-- 根据 id 更新 user 表的数据 -->
<update id="updateUserById" parameterType="com.ys.po.User">
    update user u
        <set>
            <if test="username != null and username != ''">
                u.username = #{username},
            </if>
            <if test="sex != null and sex != ''">
                u.sex = #{sex}
            </if>
        </set>
     
     where id=#{id}
</update>

 3.  choose(when,otherwise)语句

只想选择其中的一个,查询条件有一个满足即可,使用 choose 标签可以解决此类问题,类似于 Java 的 switch 语句

<select id="selectUserByChoose" resultType="com.ys.po.User" parameterType="com.ys.po.User">

      select * from user
      <where>
          <choose>
              <when test="id !='' and id != null">
                  id=#{id}
              </when>
              <when test="username !='' and username != null">
                  and username=#{username}
              </when>
              <otherwise>
                  and sex=#{sex}
              </otherwise>
          </choose>
      </where>
  </select>

 4.  trim语句

trim标记是一个格式化的标记,可以完成set或者是where标记的功能

prefix:把trim中返回的字符串前添加一个新的字符串

prifixOverrides:覆盖trim中返回的字符串的前缀

suffix:在trim中返回的字符串后添加一个指定的字符串

suffixOverrides:覆盖trim中返回的字符串的后缀

<select id="selectUserByUsernameAndSex" resultType="user" parameterType="com.ys.po.User">

        select * from user
        <!-- <where>
            <if test="username != null">
               username=#{username}
            </if>
             
            <if test="username != null">
               and sex=#{sex}
            </if>
        </where>  -->
        <trim prefix="where" prefixOverrides="and | or">
            <if test="username != null">
               and username=#{username}
            </if>
            <if test="sex != null">
               and sex=#{sex}
            </if>
        </trim>
    </select>

5.  SQL片段

为了增加代码的重用性,简化代码,我们需要将这些代码抽取出来,然后使用时直接调用。

<!-- 定义 sql 片段 -->

<sql id="selectUserByUserNameAndSexSQL">
    <if test="username != null and username != ''">
        AND username = #{username}
    </if>
    <if test="sex != null and sex != ''">
        AND sex = #{sex}
    </if>
</sql>
引用SQL片段
<select id="selectUserByUsernameAndSex" resultType="user" parameterType="com.ys.po.User">
    select * from user
    <trim prefix="where" prefixOverrides="and | or">
        <!-- 引用 sql 片段,如果refid 指定的不在本文件中,那么需要在前面加上 namespace -->
        <include refid="selectUserByUserNameAndSexSQL"></include>
        <!-- 在这里还可以引用其他的 sql 片段 -->
    </trim>
</select>

6.foreach语句

字符串的遍历

<select id="selectUserByListId" parameterType="com.ys.vo.UserVo" resultType="com.ys.po.User">

    select * from user
    <where>
        <!--
            collection:指定输入对象中的集合属性
            item:每次遍历生成的对象
            open:开始遍历时的拼接字符串
            close:结束时拼接的字符串
            separator:遍历对象之间需要拼接的字符串
            select * from user where 1=1 and (id=1 or id=2 or id=3)
          -->
        <foreach collection="ids" item="id" open="and (" close=")" separator="or">
            id=#{id}
        </foreach>
    </where>
</select>
 

六、generator逆向工程

http://www.mybatis.org/generator/index.html

在官网上查询xml文件然后粘贴复制修改,然后通过Java运行生成bean,dao,mapper文件

 

 

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">

<generatorConfiguration>
<classPathEntry location="F:/mybatis-generator-core-1.3.5.jar" />

<context id="DB2Tables" targetRuntime="MyBatis3">
<commentGenerator>
<property name="suppressAllComments" value="true" />   ————————————————>填入这个标签可以表示为不必添加各类英文注释,方便我们使用
</commentGenerator>
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3306/mybatis"
userId="root"
password="123123">
</jdbcConnection>

<javaTypeResolver >
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>

<javaModelGenerator targetPackage="com.zhiyou100.szx.bean" targetProject="./src">
<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
</javaModelGenerator>

<sqlMapGenerator targetPackage="com.zhiyou100.szx.mapper" targetProject="./resources">
<property name="enableSubPackages" value="true" />
</sqlMapGenerator>

<javaClientGenerator type="XMLMAPPER" targetPackage="com.zhiyou100.szx.dao" targetProject="./src">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>

<table schema="mybatis" tableName="users" domainObjectName="Users"

enableCountByExample="false" enableSelectByExample="false" enableDeleteByExample="false" enableUpdateByExample="false"
>
<property name="useActualColumnNames" value="true"/>
<generatedKey column="ID" sqlStatement="DB2" identity="true" />
<columnOverride column="DATE_FIELD" property="startDate" />
<ignoreColumn column="FRED" />
<columnOverride column="LONG_VARCHAR_FIELD" jdbcType="VARCHAR" />
</table>

</context>
</generatorConfiguration>

 

 通过Java主函数运行下列代码,可以生成bean,dao,mapper文件

 

http://www.mybatis.org/generator/index.html

引入mybatis-generatorjar

创建generator的配置文件。

运行generator

七、分页助手pagehelper

1.引入相关jar包

版本问题,必须相互兼容。

 

 2.加入插件

 

 在配置文件加入,在标签properties下。

然后在主函数调用或者测试函数测试。

 

 八、#和$的区别

 

#{}
#将传入的数据都当成一个字符串,会对自动传入的数据加一个双引号。

例如:order by #{parameterName} //或取Map中的value#{Key}也是一样操作。

假设传入参数是“Smith”

会解析成:order by "Smith"

${} 
$将传入的数据直接显示生成在sql中。

例如:order by #{parameterName} //或取Map中的value#{Key}也是一样操作。

假设传入参数是“Smith”

会解析成:order by Smith

概念
#方式能够很大程度防止sql注入,$方式无法防止Sql注入。
$方式一般用于传入数据库对象,例如传入表名。
从安全性上考虑,能使用#尽量使用#来传参,因为这样可以有效防止SQL注入的问题。

九、如何获取添加后的主键值

Mybatis在insert和update标签中就提供了这种功能。

useGeneratedKeys: 是否自动生成主键,默认false

keyProperty :返回的主键值赋给哪个属性

keyColumn: 数据库中的自增主键的列名,默认是数据库表的第一列。

posted @ 2019-09-01 14:28  不言而喻okok  阅读(173)  评论(0编辑  收藏  举报