【Mybatis】Mybatis的使用搭建,SQL映射以及动态SQL如何写

mybatis是一个持久层框架,用java编写的。
它封装了jdbc 操作的很多此劫,使开发者只需要关注sql语句本身,而无需关注注册驱动,创建连接等繁杂过程,
它使用了ORM思想实现了结果集的封装。
接下来就让我们一起学习一下。

搭建

1、创建maven工程并导入坐标

<dependencies>
		<dependency>
            <groupId>org.mybaits</groupId>
            <artifactId>mybaits</artifactId>
            <version>3.4.5</version>
        </dependency>
		<dependency>
	            <groupId>mysql</groupId>
	            <artifactId>mysql-connector-java</artifactId>
	            <version>5.1.6</version>
	     </dependency>
	     <dependency>
	            <groupId>log4j</groupId>
	            <artifactId>log4j</artifactId>
	            <version>1.2.12</version>
	     </dependency>
	      <dependency>
	            <groupId>junit</groupId>
	            <artifactId>junit</artifactId>
	            <version>4.10</version>
	     </dependency>
</dependencies>

2、创建实体类和dao的接口

3、创建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" >
<!--Mybatis的主配置文件-->
<configuration>
    <!-- 配置环境-->
    <environments default="mysql">
        <!-- 配置MySQL的环境-->
        <environment id="mysql">
            <!--配置事务的类型-->
            <transactionManager type="JDBC"></transactionManager>
            <!--配置数据源(连接池)-->
            <dataSource type="POOLED">
                <!--配置连接数据库的4个基本信息-->
                <property name="driver" value="com.mysql.jdbc.Driver"></property>
                <property name="url" value="jdbc:mysql://localhost:3306/eesy_mybatis"></property>
                <property name="username" value="root"></property>
                <property name="password" value="1234"></property>
            </dataSource>
        </environment>
    </environments>
    <!--指定映射配置文件的位置,映射配置文件指的是每个dao独立的配置文件-->
    <mappers>
        <mapper resource="com/itheima/dao/IUserDao.xml"/>
    </mappers>
</configuration>

4、创建映射配置文件

<?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="com.cxh.dao.userDao">
    <select id="findAll" resultType="com.cxh.domain.User">
      	select * from user
    </select>
</mapper>

SQL映射

关键词 意义
cache 给定命名空间的缓存配置
cache-ref 其他命名空间缓存配置的引用。
resultMap 是最复杂也是最强大的元素,用来描述如何从数据库结果集中来加载对象。
sql 可被其他语句引用的可重用语句块。
insert 映射插入语句
update 映射更新语句
delete 映射删除语句
select 映射查询语句

查询语句

<select id="findAll" resultType="com.cxh.domain.User">
		select * from user
<select>

插入语句

<insert id="saveUser" parameterType="com.cxh.domain.User">
		insert into user(username,sex)values(#{userName},#{userSex})
</insert>

更新语句

<update  id="updateUser" parameterType="com.cxh.domain.User">
		update user set username=#{userName},sex=#{userSex} where id=#{userId}
</update>

删除语句

<delete id="deleteUser" parameterType="java.lang.Integer">
		delete from user where id=#{uid}
</delete>

改别名

字段改别名

当代码中的字段和数据库中的字段不一致时,有俩种处理方式
1、改SQL
改别名,执行效率高,因为在数据库层面
2、改Mybatis
改的速度快,因为设置一个匹配,其他地方改下引用resultMap就可以了

<resultMap id="userMap" type="com.cxh.domain.User">
        <id property="userId" column="id"></id>
        <result property="userName" column="username"></result>
        <result property="userAddress" column="address"></result>
        <result property="userSex" column="sex"></result>
        <result property="userBirthday" column="birthday"></result>
</resultMap>
<select id="findAll" resultMap="userMap">
		select * from user
</select>

包改别名

typeAlias 用于配置别名
type属性指定的是实体类全限定类名。
alias属性执行别名,当指定了别名就再区分大小写

    <typeAliases>
        <typeAlias type="com.cxh.damain.User" alias="user"></typeAlias>
    </typeAliases>

package 用于指定配置别名的包,当指定之后,该包下的实体类都会注册别名,并且类名就是别名,不在区分大小写

    <typeAliases>
        <package name="com.cxh.domain"></package>
    </typeAliases>

使用这俩种中的一种方式后
parameterType="com.cxh.domain.User"就可以直接写为parameterType=“User”

动态sql

if标签

有条件地包含 where 子句的一部分

<select id="selectUsersByUserName" resultType="User">
	  select * from user WHERE 1=1
	  <if test="userName!= null">
	    	AND name like #{userName}
	  </if>
</select>

where标签

<select id="selectUsers" resultType="User">
	  select * from user 
	  <where>
	  		<if test="userName!= null">
		   		AND name like #{userName}
		    </if>
		    <if test="userSex!= null">
		   		AND sex like #{userSex}
		    </if>
	  </where>
</select>

foreach标签

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

<select id="selectUsers" resultType="User">
 select * from user
  where id in
  <foreach item="item" index="index" collection="list"
      open="(" separator="," close=")">
        #{item}
  </foreach>
</select>

choose, when, otherwise标签

不用到所有的条件语句,而只想从中择其一二

<select id="findUsersLike" resultType="User"> 
	select * from user where sex= ‘女’ 
	<choose> 
		<when test="username!= null"> 
			AND name like #{username} 
		</when> 
		<when test="user!= null and user.userName != null">
			 AND name like #{user.userName} 
		</when> 
		<otherwise> 
			AND isdelete= 0 
		</otherwise> 
	</choose> 
</select>

bind标签

元素可以从 OGNL 表达式中创建一个变量并将其绑定到上下文

<select id="selectUsersLike" resultType="User"> 
	<bind name="pattern" value="'%' + user.getName() + '%'" /> 
	select * from user
	WHERE nameLIKE #{pattern} 
</select>

抽取相同的sql

<sql id="defaultUser">
	select * from user
</sql>
<select id="findAll" resultMap="userMap">
		<include refid="defaultUser"></include>
</select>

相当于

<select id="findAll" resultMap="userMap">
		select * from user
</select>
发布了236 篇原创文章 · 获赞 103 · 访问量 15万+

猜你喜欢

转载自blog.csdn.net/cxh6863/article/details/103944108