Mybatis操作数据库实现单表/多表查询流程

1 创建web工程步骤

1.1 创建数据库及数据库表

通过sqlyog可视化工具,导入外部sql或直接创建

1.2 新建maven下war project
1.3 新建WEB_INF文件夹下web.xml文件并补全其中参数
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    version="2.5">
    <display-name>01_helloWorld</display-name>
    <welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>default.html</welcome-file>
        <welcome-file>default.htm</welcome-file>
        <welcome-file>default.jsp</welcome-file>
    </welcome-file-list>
</web-app>
1.4 配置pom.xml中参数

1.4.1 使用maven的常用插件来配置

<build>
        <finalName>ROOT</finalName>
        <plugins>
    <!--    配置Tomcat插件 -->
            <plugin>
                <groupId>org.apache.tomcat.maven</groupId>
                <artifactId>tomcat7-maven-plugin</artifactId>
                <configuration>
                    <path>/</path>
                    <port>8086</port>
                </configuration>
            </plugin>
<!--    配置JDK版本插件 -->
            <plugin>  
                <groupId>org.apache.maven.plugins</groupId>  
                <artifactId>maven-compiler-plugin</artifactId>  
                <version>3.1</version> 
                <configuration>  
                    <source>1.7</source>  
                    <target>1.7</target> 
                    <encoding>utf-8</encoding> 
                </configuration>  
            </plugin>  
<!--  maven中java项目的源码打包插件 -->
            <plugin>  
                <artifactId>maven-source-plugin</artifactId>  
                <version>2.4</version>  
                <configuration>  
                    <attach>true</attach>  
                </configuration>  
                <executions>  
                    <execution>  
                        <phase>package</phase>  
                        <goals>  
                            <goal>jar-no-fork</goal>  
                        </goals>  
                    </execution>  
                </executions>  
</plugin>  
<!--  maven中java项目依赖源码打包插件 -->
<plugin>
                   <artifactId> maven-assembly-plugin </artifactId>
                   <configuration>
                      <descriptorRefs>
                     <descriptorRef>jar-with-dependencies</descriptorRef>
                      </descriptorRefs>
                        <archive>
                             <manifest>
                                <mainClass>com.cetc.di.App</mainClass>
                             </manifest>
                        </archive>
                   </configuration>
                   <executions>
                        <execution>
                             <id>make-assembly</id>
                             <phase>package</phase>
                             <goals>
                                  <goal>single</goal>
                             </goals>
                        </execution>
                   </executions>
              </plugin>
        </plugins>
    </build>

1.4.2 配置web项目依赖jar包坐标

<dependencies>
    <!—junit注解包-->
     <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <!—mysql连接包-->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.34</version>
    </dependency>
    <!-- mybatis 包 -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.2.7</version>
        </dependency>
    <!—四种日志技术包 -->
    <dependency>
        <groupId>org.bgee.log4jdbc-log4j2</groupId>
        <artifactId>log4jdbc-log4j2-jdbc4.1</artifactId>
        <version>1.16</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.13</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.7.5</version>
    </dependency>
    <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.16</version>
    </dependency>
    <!—servlet,jsp依赖包 -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>2.5</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>jsp-api</artifactId>
        <version>2.1</version>
        <scope>provided</scope>
    </dependency>
</dependencies>

2 mybatis单表增删改查操作步骤

需求:通过mybatis实现对数据库的增删改查(基于接口代理的方式开发

2.1 新建log4j.properties,添加参数
# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
2.2 新建SqlMapConfig.xml,添加参数
<configuration>
<properties resource="db.properties">
<!--有resource配置后,本地value可以随意配置 -->
    <property name="driver" value="com.mysql.jdbc.Driversss"/>
    <property name="url" value="${url}"/>
    <property name="username" value="root"/>
    <property name="password" value="admin"/>
</properties>
<!-- 通过使用typeAliases来命名我们的pojo对象-->
<typeAliases>
        <typeAlias type="cn.itcast.mybatis.pojo.User" alias="user"/>
        <!--<package name="cn.itcast.mybatis.pojo"/>-->
</typeAliases>
<!-- 这个environments定义了我们的数据库的连接操作 -->
 <environments default="development">
        <environment id="development">
          <transactionManager type="JDBC"/>
          <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>
 <!-- 通过mappers映射来指定加载我们对应的mapper文件 -->
<mappers>
    <mapper resource="mapper.xml"/>         
    <!-- mapper class="cn.itcast.mybatis.demo03.UserMapper" -->
    <!-- <package name="cn.itcast.mybatis.demo03"/> -->
</mappers>
</configuration>

注意事项:
(1)sqlMapConfig.xml是mybatis当中的核心配置文件,定义了数据库连接信息,使用数据库连接池的方式来进行数据库的连接
(2)properties、typeAliases、environments、mappers顺序不能改变
(3)resource=”db.properties”引入外部参数会覆盖本地property中内容
(4)起别名:通常用package name=”cn.itcast.pojo”扫描dao包文件形式,只需要拷贝我们指定的包路径就行,别名就是dao类名,而且不区分大小写
(5)Mapper映射package方式,mapper.xml文件与dao接口文件路径和名称都相同
(6)一个数据库表同一时间只能映射一个mapper.xml,否则会报错

2.3 新建外部配置文件db.properties,添加参数
#注意,配置文件中,不要随意打入空格等空字符串
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8
username=root
password=123123
2.4 新建pojo中实体类对象

要与sql表中属性一一对应,导入get,set方法.

2.5 新建Mapper.java接口文件

定义增删改查方法,参数和返回值类型.

2.6 新建Mapper.xml文件

与接口文件路径和名称相同,定义增删改查sql语句.

<?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="cn.itcast.mybatis.demo03.UserMapper">
<!-- namespace用于区分多个mapper.xml -->
<select id="getUserById" parameterType="int" resultType="user">
  select * from user where id = #{id }
</select>
<select id="getUserByAddress" parameterType="string" resultType="user">
  select * from user where address like '%${value}%';
</select>
<insert id="insertUser" parameterType="user" >
    <selectKey keyColumn="id" keyProperty="id" resultType="int" order="AFTER">
        SELECT LAST_INSERT_ID();
        <!-- SELECT UUID(); order用before-->
    </selectKey>
    insert into user values
    (null, #{username} ,#{birthday},#{sex},#{address});
</insert>
<update id="updateUser" parameterType="user" >
    update user set address=#{address } where id=#{id } 
</update>
</mapper>

注意事项:
(1)mapper.xml是mybatis对数据库中表的映射,一张数据库表,映射成一个xml文件。对数据库表的操作,都封装在mapper.xml中
(2)使用接口代理的方式来开发dao操作数据库,namespace一定要指向我们要执行的对应的接口全限名
(3)Sql语句中的id需要与接口中方法名相同,输入和返回值参数类型需要与接口方法中参数类型相同,首字母不区分大小写,dao数据类型需要使用全路径或者别名(sqlmapconfig.xml文件中)
(4)#{ }是占位符:传入单个简单类型值,括号中可以是value或其他名称; 如果是pojo类型, 必须写pojo属性名
(5)${ }是连接符:将传入的内容拼接在sql中且不进行jdbc类型转换。如果其中传输单个简单类型值,括号中只能是value; 如果是pojo类型, 必须写pojo属性名。

2.7 新建测试类
package cn.itcast.mybatis.demo03;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import cn.itcast.mybatis.pojo.User;
public class UserMapperTest {
    SqlSession sqlSession=null;
    @Before
    public void init() throws IOException{
        SqlSessionFactoryBuilder builder=new SqlSessionFactoryBuilder();
        //工厂对象,产生sqlSession,通过resources获取配置文件       SqlSessionFactory sqlSessionFactory=builder.build(Resources.getResourceAsStream("SqlMapConfig.xml"));
        // sqlSession操作数据库的一次sql会话
        sqlSession=sqlSessionFactory.openSession();
    }
    @Test
    public void testName() {
        UserMapper mapper = sqlSession.getMapper(Mapper.class);
        //sqlSession.commit();增删查操作需要手动提交
    }
    @After
    public void after(){
        sqlSession.close();
    }
}

执行流程如下:
(1)sqlSession.getMapper(Mapper.class)使用jdk动态代理的方式,传入接口.class参数,通过getMapper方法获取Mapper接口的代理对象mapper,通过代理对象调用接口中方法,传入参数;
(2)通过方法名对应的sqlid将参数传递到Mapper.xml中对应的sql语句;
(3)sqlConfig中的mapper映射通过namespace对应的接口全限名找到mapper.xml;
(4)mybatis底层连接数据库进行sql语句操作;
(5)返回结果传递给Mapper代理对象接收。

3 mybatis多表关联查询

3.1 输入映射与输出映射

(1)输入映射:通过queryVo来查询对象,queryVo包装类建在pojo包里,封装User类。
(2)输出映射:定义resultMap封装字段,映射关系
type:表示这个resultMap最后封装的结果类型;
id:可以随便写。

3.2 动态sql

四种类型:if,where,foreach,sql片段

<!-- 动态sql -->
<select id="getUserByCond" parameterType="user" resultType="user">
     select * from user
     <where>
        <if test="id !=null and id !='' ">
            and id=#{id }
        </if>
            <if test="address !=null and address != '' ">
            and  address like '%${address}%'
        </if>
     </where>
</select>
<!-- sql片段 -->
 <sql id="baseSql">
    select  id,username,birthday,sex,address from user 
</sql>
<!-- 动态sql之foreach -->
 <select id="getUserByIn" parameterType="queryVo" resultType="user">
        <include refid="baseSql"/>
    <where>
    <!-- 
        collection: 表示我们传入参数里面的集合属性
        open:表示我们的循环sql以什么开头
        close:表示我们的循环sql以什么结尾
        separator:表示我们的循环sql用什么来做为分隔符
        item:变量,表示我们每次循环,集合中的一个元素
     -->
        <foreach collection="ids" open="id in(" close=")" item="id" separator=",">
                #{id}
        </foreach>
    </where>
 </select>

难点:动态foreach获取多个用户id集合,在queryVo中增添一个list user用于接收返回值。

@Test
public void getUserId() throws Exception {
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    QueryVo vo=new QueryVo();
    List<Integer> list=new ArrayList<>();
    list.add(1);
    list.add(10);
    list.add(16);
    vo.setIds(list);
    //将Id集合封装到vo对象中
    List<User> userList=mapper.getUserByIn(vo);
    for (User user : userList) {
        System.out.println(user.getId());
    }
}
3.3 关联查询

3.3.1 一对一关联查询

association javaType属性来定义
(1)新建pojo对象基层javaBean类的方式
(2)自定义resultMap的方式,传入User对象属性(常用)。

<!-- 查询mybatis一对一的关联关系 -->
<resultMap type="orders" id="baseOrderWithUsers">
    <id column="id" property="id"/>
    <result column="user_id" property="userId"/>
    <result column="number" property="number"/>
    <result column="createtime" property="createtime"/>
    <result column="note" property="note"/>
    <association property="user" javaType="user" >
        <result column="id" property="id"/>
        <result column="username" property="username"/>
        <result column="birthday" property="birthday"/>
        <result column="sex" property="sex"/>
        <result column="address" property="address"/>
    </association>
</resultMap>
<select id="getUserWithOrders" resultMap="baseOrderWithUsers">
    SELECT * FROM orders o LEFT  JOIN USER u ON o.user_id = u.id 
</select>

3.3.2 一对多关联查询
connection ofType属性类定义,用自定义resultMap的方式,传入对象属性,返回值为对象列表list。

<resultMap type="user" id="baseUserWithOrders1">
    <id column="id" property="id"/>
    <result column="username" property="username"/>
    <result column="birthday" property="birthday"/>
    <result column="sex" property="sex"/>
    <result column="address" property="address"/>
<!-- 在mybatis一对多的关联关系中,为了表示集合中每一个元素的类型,通常使用ofType来表示 -->
    <collection property="orderList" ofType="orders">
        <result column="user_id" property="userId"/>
        <result column="number" property="number"/>
        <result column="createtime" property="createtime"/>
        <result column="note" property="note"/>
    </collection>
</resultMap>
 <!-- 查询mybatis一对多的关联关系 -->
 <select id="getUserWithOrders1" resultMap="baseUserWithOrders1">
    SELECT * FROM USER u LEFT JOIN orders o ON u.id = o.user_id   WHERE u.id = 1
</select>
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值