Mybatis框架-1

1.Mybatis框架:

  Mybatis是一个半自动的对象关系映射(ORM),实现结果集的自动封装,sql写到配置文件中;

  Mybatis使用的是DTD约束。

2.Mybatis模块调用:

    

3.SqlMapConfig.xml :Mybatis框架的核心配置。

    default=“MySql”---> 默认使用MySQL数据库

    映射配置中的resource=“”--> 单个对象的映射文件

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE configuration
 3 PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
 4 "http://mybatis.org/dtd/mybatis-3-config.dtd">
 5 
 6 <configuration>
 7 
 8 <!-- 配置数据源 -->
 9     <environments default="mysql">
10         <environment id="mysql">
11             <transactionManager type="JDBC" />
12             <dataSource type="POOLED">
13                 <property name="driver" value="com.mysql.jdbc.Driver" />
14                 <property name="url" value="jdbc:mysql://localhost:3306/mydb1?characterEncoding=utf-8" />
15                 <property name="username" value="root" />
16                 <property name="password" value="admin" />
17             </dataSource>
18         </environment>
19         
20         <environment id="oracle">
21             <transactionManager type="JDBC" />
22             <dataSource type="POOLED">
23                 <property name="driver" value="oracle.jdbc.driver.OracleDriver" />
24                 <property name="url" value="jdbc:oracle:thin:@127.0.0.1:1521:XE" />
25                 <property name="username" value="ht1602" />
26                 <property name="password" value="htdb" />
27             </dataSource>
28         </environment>
29     </environments>
30     
31     
32     <!-- 映射文件 -->
33     <mappers>
34         <mapper resource="pojo/UserMapper.xml" />
35     </mappers>
36 
37 </configuration>

4.XXXMapper.xml:一张表对应一个对象,则所有关于这张表的增删查改的SQL都写在一个配置文件中。

  resultType="Javabean的全限定名" --> 将结果集自动封装到对象中

  ${ } 和 #{ } 的基本抉择:     

  作用:

    1.含有预编译的效果,能够防止sql注入攻击

    2.为参数添加了一对""号

  注意事项:

    如果sql语句中以列名为参数时,切记使用${Map中的key},必须配置Map一起联用.

  总结

    以列名为参数时使用${},其他的使用#{}

    能用#{}取值,决不用${}

 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE mapper
 3 PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
 4 "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
 5 
 6 <!-- namespace:唯一标识映射文件 -->
 7 <mapper namespace="pojo.UserMapper">
 8 
 9     <!-- resultType: 将结果集自动封装到对象中 -->
10     <select id="find" resultType="pojo.User">
11         select * from account
12     </select>
13     
14     <!-- #{对象的属性} -->
15     <insert id="adduser">
16         insert into account (id,name,money) values (null,#{name},#{money})
17     </insert>
18     
19     <update id="updatauser">
20         update account set money=#{money} where id=#{id}    
21     </update>
22     
23     <!-- ${map中的Key} -->
24     <select id="selectByMoney" resultType="pojo.User">
25         select * from account where money > ${minMoney}  <![CDATA[and money< ${maxMoney} ]]>
26     </select>
27     
28     
29 </mapper>

   <![CDATA[ ... ]]> :大段转义字符;写在中括号内部的字符都将变成字符串输出。这样就避免了xml文件中的关键符号;一般在用xml作为数据传输格式时这个可以方便将整个xml文件输出字符串进行传输      

5.获取数据库连接(SqlSessionFactory):

  1.通过流读取Mybatis核心配置文件;

  2.创建SalSessionFactory对象;

  3.获取数据库连接(SqlSession);

6.执行数据库的CRUD:

  --->openSession()

 1 @Test
 2 public void test1() throws IOException{
 3     
 4     //通过流读取Mybatis核心配置文件
 5     InputStream is = Resources.getResourceAsStream("sqlMapConfig.xml");
 6     
 7     //获取SqlSessionFactory对象
 8     SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
 9     
10     //从数据源中获取连接
11     SqlSession openSession = factory.openSession();
12     
13     //执行sql ---namespace.id
14     List<User> list = openSession.selectList("pojo.UserMapper.find");
15     
16     for (User user : list) {
17         System.out.println(user);
18     }
19     
20 }

 

7.Mybatis中的多值传递问题

  如需求:

    要求查询年龄在18-22之间的人

  问题:在Mybatis中只支持单值的传递.多值传递时没有现成的API

  解决方法:

  可以将多个值转化为单个对象Map

  建议:

    如果是插入操作/更新操作,使用对象.其他的使用MAP

 

8.动态更新操作

  需求:

    如果某些数据只修改特定的值,其他参数不变,这时需要使用动态更新

  基本语法:

1 <update id="dynamicUpdate">
2     update user
3         <set>
4             <if test="name !=null">name=#{name},</if> 
5             <if test="age !=null">age=#{age},</if>
6             <if test="sex !=null">sex=#{sex}</if>
7         </set>
8     where id=#{id}
9 </update>

  set标签的作用:去除where条件前多余的1个逗号     

 

9.动态查询

  需求:

    根据对象中的属性值,查询信息

  方案:使用动态查询

  基本语法:

1 <select id="dynamicFind" resultType="pojo.User">
2     select * from user
3     <where>
4         <if test="id !=null">id=#{id}</if> 
5         <if test="name !=null">and name = #{name}</if>
6         <if test="age !=null">and age = #{age}</if>
7         <if test="sex !=null">and sex = #{sex}</if>
8     </where>
9 </select>

  Where标签的作用:去除where后边多余1个的and      

 

9.动态插入操作

<insert id="addUser">
    insert into user
    <!--trim能够实现拼接 和去除指定的元素  -->
    <trim prefix="("  suffix=")" suffixOverrides=",">        
        id,
        <if test="name !=null">name,</if>
        <if test="age !=null">age,</if>
        <if test="sex !=null">sex</if>
    </trim>    
    values
    <trim prefix="("  suffix=")" suffixOverrides=",">
         null,
         <if test="name !=null">#{name},</if>
         <if test="age !=null"> #{age},</if>
         <if test="sex !=null"> #{sex}</if>
     </trim>    
</insert>

  trim能够实现拼接 和去除指定的元素  

 

 10.批量删除(遍历)

  需求:

    删除ID从20---31的数据

  解决方法:

    使用in关键字实现动态删除

  ** 注意:collection=“...”     --- 数组:array、List集合:list、Map集合:map中的key

<delete id="deleteUser">
    delete from user where id in
    <!--遍历数组  -->
    <foreach collection="array" open="(" close=")" 
    item="id" separator=",">
        #{id}
    </foreach>
</delete>

 

 11.别名标签

  需求:

    当进行结果集映射时,如果包名比较长,这时进行封装比较麻烦.

  解决方法:用别名标签

 

<!--定义别名标签  
    type="需要起别名的类型"
    alias="User" 类名
-->    
<typeAliases>
    <typeAlias type="pojo.User" alias="User"/>
</typeAliases>

 

12.Mybatis中单值传递问题

  说明:Mybaits中如果传递的参数为单值例如 12,"String".通过#{}取值时,参数可以是任意。

 

 13.sql的复用

 

  如果需要多表关联时,sql语句较多,可以使用sql标签进行简化.但是可读性降低了.

 

 

 

 

 

 

 

 

 

 

原文地址:https://www.cnblogs.com/tongxuping/p/7092011.html