2020-11-16

2020-11-16  本文已影响0人  眼前人心上人_9a6a

mybatis

入门

安装

从 XML 中构建 SqlSessionFactory

从 SqlSessionFactory 中获取 SqlSession

XML 配置

配置

属性(properties)

设置(settings)

对象工厂(objectFactory)

环境配置(environments)

事务管理器(transactionManager)

数据源(dataSource)

数据库厂商标识(databaseIdProvider)

XML 映射文件

XML 映射文件

1.select

  1. insert, update 和 delete
  1. sql
    这个元素可以用来定义可重用的 SQL 代码片段,以便在其它语句中使用。 参数可以静态地(在加载的时候)确定下来,并且可以在不同的 include 元素中定义不同的参数值。比如:
    <sql id="userColumns"> {alias}.id,{alias}.username,{alias}.password </sql> 这个 SQL 片段可以在其它语句中使用,例如: <select id="selectUsers" resultType="map"> select <include refid="userColumns"><property name="alias" value="t1"/></include>, <include refid="userColumns"><property name="alias" value="t2"/></include> from some_table t1 cross join some_table t2 </select> 也可以在 include 元素的 refid 属性或内部语句中使用属性值,例如: <sql id="sometable">{prefix}Table
    </sql>
    <sql id="someinclude">
    from
    <include refid="${include_target}"/>
    </sql>
    <select id="select" resultType="map">
    select
    field1, field2, field3
    <include refid="someinclude">
    <property name="prefix" value="Some"/>
    <property name="include_target" value="sometable"/>
    </include>
    </select>
  2. 之前见到的所有语句都使用了简单的参数形式。但实际上,参数是 MyBatis 非常强大的元素。对于大多数简单的使用场景,你都不需要使用复杂的参数,比如:
    <select id="selectUsers" resultType="User">
    select id, username, password
    from users
    where id = #{id}
    </select>
    上面的这个示例说明了一个非常简单的命名参数映射。鉴于参数类型(parameterType)会被自动设置为 int,这个参数可以随意命名。原始类型或简单数据类型(比如 Integer 和 String)因为没有其它属性,会用它们的值来作为参数。 然而,如果传入一个复杂的对象,行为就会有点不一样了。比如:
    <insert id="insertUser" parameterType="User">
    insert into users (id, username, password)
    values (#{id}, #{username}, #{password})
    </insert>
  3. 结果映射
  4. 自动映射

动态 SQL

  1. <select id="findActiveBlogWithTitleLike"
    resultType="Blog">
    SELECT * FROM BLOG
    WHERE state = ‘ACTIVE’
    <if test="title != null">
    AND title like #{title}
    </if>
    </select>
  2. <select id="findActiveBlogLike"
    resultType="Blog">
    SELECT * FROM BLOG WHERE state = ‘ACTIVE’
    <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>

Java API

上一篇 下一篇

猜你喜欢

热点阅读