JavaEE:MyBatis用法

说明:

对象关系映射框架,操作数据库数据

主要依赖jar包:mybatis-x.x.x.jar、mysql-connector-java-x.x.x.jar
其他依赖jar包:ant-x.x.x.jar、ant-launcher-x.x.x.jar、asm-x.x.jar、cglib-x.x.xx.jar、commons-logging-x.x.jar、javassist-x.x.x-GA.jar、log4j-x.x.x.jar、log4j-api-x.x.x.jar、log4j-core-x.x.x.jar、ognl-x.x.x.jar、slf4j-api-x.x.x.jar、slf4j-log4j12-x.x.x.jar

一、配置连接池、对象映射:

1.配置连接池,加载对象映射配置文件:

(1)新建jdbc.properties,配置连接信息:

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/mydb?serverTimezone=UTC
username=root
password=root

(2)新建mybatis-config.xml,加载jdbc.properties,配置连接池:

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

    <!-- 加载jdbc.properties资源文件 -->
    <properties resource="jdbc.properties"/>

    <environments default="development">
        <!-- development表示开发环境 -->
        <environment id="development">
            <!-- 1.使用JDBC事务管理 -->
            <transactionManager type="JDBC" />
            <!-- 2.配置连接池 -->
            <dataSource type="POOLED">
                <property name="driver" value="{driver}" />
                <property name="url" value="${url}" />
                <property name="username" value="${username}" />
                <property name="password" value="${password}" />
            </dataSource>
        </environment>
    </environments>
</configuration>

(3)加载对象映射配置文件:

第1种,直接加载配置文件方式:

<!-- 3.加载对象映射配置文件 -->
<mappers>
    <mapper resource="user.xml" />
</mappers>

第2种,类扫描方式,自动加载同名配置文件:

<!-- 接口文件与映射文件在同一包下;接口名与映射文件名一致。 -->
<mappers>
    <!-- 类扫描方式,自动加载对象映射配置文件 -->
    <mapper class="com.yyh.hkw.dao.UserMapper" />
</mappers>

2.新建user.xml,配置对象映射文件:

<?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">
<!-- 配置对象关系映射,namespace为名称空间,代码调用时引用 -->
<mapper namespace="">
    <!-- 此处编写sql节点,如<insert></insert> -->
</mapper>

二、普通Dao方式,增删改查:

1.插入数据:

(1)配置插入sql语句,在user.xml文件的<mapper>节点内:

自增主键生成,利用useGeneratedKeys属性:

<!-- 自增主键, useGeneratedKeys使用自增(selectKey二选一), keyProperty为User对象id属性,两者一起使用-->
<insert useGeneratedKeys="true" keyProperty="id"/>

或者,自增主键生成,利用<insert>内部的<selectKey>节点:

<!-- 或者在<insert>节点内加入, (与useGeneratedKeys二选一)keyProperty为User对象id属性,order何时执行(BEFORE之前,AFTER之后)-->
<selectKey keyProperty="id" resultType="int" order="AFTER">
    select last_insert_id()  <!-- 如果要用string类型的id,可以使用select uuid() -->
</selectKey>

插入sql语句配置:

<mapper namespace="user">
    <!-- 插入sql语句,id唯一标识,parameterType参数类型,#{}类似?占位符,参直接将对象属性值存入对应的同名列中 -->
    <!-- 主键返回, useGeneratedKeys使用自增(selectKey二选一), keyProperty为User对象id属性-->
    <insert id="sql_insert" parameterType="com.yyh.hkw.domain.User" useGeneratedKeys="true" keyProperty="id">
        <!-- 主键返回, (与useGeneratedKeys二选一)keyProperty为User对象id属性,order何时执行(BEFORE之前,AFTER之后)-->
        <selectKey keyProperty="id" resultType="int" order="AFTER">
            select last_insert_id()
        </selectKey>
        insert into user(id,name) values(#{id},#{name})
    </insert>
</mapper>

(2)实现插入数据方法:

private static SqlSessionFactory sFactory;
static {
    try {
        // 1.获取mybatis-config.xml输入流
        InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
        // 2.创建SqlSession工厂类
        sFactory = new SqlSessionFactoryBuilder().build(in);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

// 插入数据
public void insert(User user) throws IOException {
    // 1.创建SqlSession,openSession(true)为开启自动提交事务
    SqlSession session = sFactory.openSession();
    // 2.执行插入语句,user为user.xml中<mapper namespace="use">,sql_insert为<select id="sql_insert">,后面参数为sql语句中的占位参数值
    session.insert("user.sql_insert", user);
    // 3.默认不自动提交事务
    session.commit();
    // 4.关闭连接
    session.close();
}

2.更新数据:

(1)配置更新sql语句,在user.xml文件的<mapper>节点内:

<!-- 更新语句,id唯一标识,parameterType参数类型,#{}类似?占位符 -->
<update id="sql_update" parameterType="com.yyh.hkw.domain.User">
    update user set name=#{name} where id=#{id}
</update>

(2)实现更新数据方法:

// 更新数据
public void update(User user) throws IOException {
    // 1.创建SqlSession,openSession(true)为开启自动提交事务
    SqlSession session = sFactory.openSession(true);
    // 2.执行更新语句,user为user.xml中<mapper namespace="use">,sql_update为<select id="sql_update">,后面参数为sql语句中的占位参数值
    session.update("user.sql_update", user);
    // 3.关闭连接
    session.close();
}

3. 查询单个数据:

(1)配置查询单个sql语句,在user.xml文件的<mapper>节点内:

<!-- 查询单个语句,id唯一标识,parameterType参数类型,resultType返回值类型,#{}类似?占位符 -->
<select id="sql_query" parameterType="string" resultType="com.yyh.hkw.domain.User">
    select * from user where name=#{name}
</select>

(2)实现查询单个数据方法:

// 查询单个数据
public void query(String name) throws IOException {
    // 1.创建SqlSession
    SqlSession session = sFactory.openSession();
    // 2.执行查询语句,user为user.xml中<mapper namespace="use">,sql_query为<select id="sql_query">,后面参数为sql语句中的占位参数值
    User user = session.selectOne("user.sql_query", name);
    // 3.关闭连接
    session.close();
}

4. 查询列表数据:

(1)配置查询List列表sql语句,在user.xml文件的<mapper>节点内:

<!-- 查询List列表语句,id唯一标识,resultType返回值类型,#{}类似?占位符 -->
<select id="sql_query_list" resultType="com.yyh.hkw.domain.User">
    select * from user
</select>

(2)实现查询列表数据方法:

// 查询列表数据
public void queryList() throws IOException {
    // 1.创建SqlSession,openSession(true)为开启自动提交事务
    SqlSession session = sFactory.openSession();
    // 2.执行查询列表语句,user为user.xml中<mapper namespace="use">,sql_query_list为<select id="sql_query_list">,后面参数为sql语句中的占位参数值
    List<User> list = session.selectList("user.sql_query_list");
    // 3.关闭连接
    session.close();
}

5.模糊查询数据:

(1)配置模糊查询sql语句,在user.xml文件的<mapper>节点内:

<!-- 模糊查询List列表语句,id唯一标识,parameterType参数类型,resultType返回值类型,#{}类似?占位符 -->
<select id="sql_query_like" parameterType="string" resultType="com.yyh.hkw.domain.User">
    select * from user where name like %${name}%
</select>

(2)实现模糊查询数据方法:

// 模糊查询数据
public void search(String key) throws IOException {
    // 1.创建SqlSession
    SqlSession session = sFactory.openSession();
    // 2.执行模糊查询语句,user为user.xml中<mapper namespace="use">,sql_query_like为<select id="sql_query_like">,后面参数为sql语句中的占位参数值
    List<User> list = session.selectList("user.sql_query_like", key);
    // 3.关闭连接
    session.close();
}

6.删除数据:

(1)配置删除sql语句,在user.xml文件的<mapper>节点内:

<!-- 删除sql语句,id唯一标识,parameterType参数类型,#{}类似?占位符 -->
<delete id="sql_delete" parameterType="string">
    delete from user where name=#{name}
</delete>

(2)实现删除数据方法:

// 删除数据
public void delete(String name) throws IOException {
    // 1.创建SqlSession,openSession(true)为开启自动提交事务
    SqlSession session = sFactory.openSession(true);
    // 2.执行删除语句,user为user.xml中<mapper namespace="use">,sql_delete为<select id="sql_delete">,后面参数为sql语句中的占位参数值
    session.delete("user.sql_delete", name);
    // 3.关闭连接
    session.close();
}

三、动态代理方式,增删改查:

说明:由系统自动生成Dao实现类。

规则: 
namespace属性值填Dao接口带包名;
Dao接口方法名与<select>等节点的id属性值一致;
Dao接口方法参数与parameterType类型一致;
Dao接口方法返回值与resultType类型一致。

1.Dao接口,会自动生成实现类:

public interface UserMapper {
    // 查询
    public User query(String name);
}

2.配置sql语句(保证方法返回值、参数、方法名和接口定义一致),在user.xml文件的<mapper>节点内:

<!-- 配置对象关系映射,namespace为Dao接口带包名,会自动生成实现类 -->
<mapper namespace="com.yyh.hkw.dao.UserMapper">
    <!-- 查询语句,id属性值要与Dao接口query方法名一致,parameterType要与query方法参数类型一致,resultType要与query方法返回类型一致 -->
    <select id="query" parameterType="string" resultType="com.yyh.hkw.domain.User">
        select * from user where name=#{name}
    </select>
</mapper>

3.实现数据增删改查:

private static SqlSessionFactory sFactory;
static {
    try {
        // 1.获取mybatis-config.xml输入流
        InputStream in = Resources.getResourceAsStream("mybatis-config.xml");
        // 2.创建SqlSession工厂类
        sFactory = new SqlSessionFactoryBuilder().build(in);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

// 测试查询方法
public void testQuery(String name) throws IOException {
    // 1.创建SqlSession
    SqlSession session = sFactory.openSession();
    // 2.获取Dao自动实现类
    UserMapper dao = session.getMapper(UserMapper.class);
    // 3.执行查询语句
    User user = dao.query(name);
    // 4.关闭连接
    session.close();
}

四、别名使用(不区分大小写):

1.单个方式:

(1)定义别名,在mybatis-config.xml的<configuration>节点内:

<!-- 定义别名,后面能直接使用定义的别名 -->
<typeAliases>
    <typeAlias type="com.yyh.hkw.domain.User" alias="user"/>
</typeAliases>

(2)使用别名,在user.xml:

<!-- user是别名,是mybatis-config.xml的<typeAlias>节点alias属性值 -->
<select id="queryList" resultType="user">
    select * from user
</select>

2.包扫描方式:

(1)定义别名,在mybatis-config.xml的<configuration>节点内:

<!-- 包扫描方式定义别名,别名默认为User,后面能直接使用定义的别名 -->
<typeAliases>
    <package name="com.yyh.hkw.domain" />
</typeAliases>

(2)使用别名,在user.xml:

<!-- user是别名,是mybatis-config.xml的<typeAlias>节点alias属性值 -->
<select id="queryList" resultType="user">
    select * from user
</select>

五、resultMap使用:

作用:当列名与属性名不一致时,将列名与属性名关联起来。在单表查询时,列名与属性名一致时不用配置。

1.定义resultMap,在对象映射文件UserMapper.xml的<mapper>节点内:

<!-- 当列名与属性名不一致时,将列名与属性名关联起来 -->
<resultMap type="com.yyh.hkw.domain.User" id="resultMapId">
    <!-- 映射主键列,property为属性名,column为列名 -->
    <id property="id" column="id"/>
    <!-- 映射其他列,property为属性名,column为列名 -->
    <result property="name2" column="name"/>
</resultMap>

2.使用resultMap,在对象映射文件UserMapper.xml的<select>节点中增加resultMap属性:

<!-- 查询List列表语句,resultMap为<resultMap>节点id属性值 -->
<select id="queryList" resultType="com.yyh.hkw.domain.User" resultMap="resultMapId">
    select * from user
</select>

五、动态sql使用(在sql标签内部使用标签):

1.<if>标签使用:

作用:在sql标签内部直接使用if判断。

<select id="queryList" parameterType="com.yyh.hkw.domain.User" resultType="com.yyh.hkw.domain.User">
    select * from user
    <if test="name!= null"> <!-- 如果参数User中的name属性不为空,则给sql加上where条件语句 -->
        where name=#{name}
    </if>
</select>

2.<where>标签使用:

作用:给sql加上where。

<select id="queryList" parameterType="com.yyh.hkw.domain.User" resultType="com.yyh.hkw.domain.User">
    select * from user
    <!-- 给sql加上where条件语句,会自动补上where,等同:where name=#{name} -->
    <where>
        name=#{name}
    </where>
</select>

3.sql片段:

作用:定义通用sql,供其他sql标签中使用。

(1)定义 sql片段:

<!-- 定义sql片段,供其他sql标签内调用 -->
<sql id="sqlId">
    where name=#{name}
</sql>

(2)使用sql片段:

<select id="queryList" parameterType="com.yyh.hkw.domain.User" resultType="com.yyh.hkw.domain.User">
    select * from user
    <!-- 导入sql片段,refid为<sql>标签id属性值 -->
    <include refid="sqlId" />
</select>

4.<foreach>标签使用:

作用:在sql标签中循环赋值,放在<where>内部。

<!-- 查询姓名为范围内的人 -->
<select id="queryList" parameterType="com.yyh.hkw.domain.User" resultType="com.yyh.hkw.domain.User">
    select * from user 
    <where>
        <!-- name in(姓名1, 姓名2, 姓名3)  ,collection为属性名,open为sql开始语句,item为每次循环赋值变量,separator为列表分割符,close为sql结束语句 -->
        <foreach collection="nameList" open="name in(" item="itemName" separator="," close=")">
            #{itemName} <!-- itemName为item中定义的变量名 -->
        </foreach>
    </where>
</select>

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值