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

1 创建web工程步骤

1.1 创建数据库及数据库表

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

1.2 新建maven下war project

1.3 新建WEB_INF文件夹下web.xml文件并补全其中参数


<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_helloWorlddisplay-name>
    <welcome-file-list>
        <welcome-file>index.htmlwelcome-file>
        <welcome-file>index.htmwelcome-file>
        <welcome-file>index.jspwelcome-file>
        <welcome-file>default.htmlwelcome-file>
        <welcome-file>default.htmwelcome-file>
        <welcome-file>default.jspwelcome-file>
    welcome-file-list>
web-app>

1.4 配置pom.xml中参数

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

<build>
        <finalName>ROOTfinalName>
        <plugins>
    
            <plugin>
                <groupId>org.apache.tomcat.mavengroupId>
                <artifactId>tomcat7-maven-pluginartifactId>
                <configuration>
                    <path>/path>
                    <port>8086port>
                configuration>
            plugin>

            <plugin>  
                <groupId>org.apache.maven.pluginsgroupId>  
                <artifactId>maven-compiler-pluginartifactId>  
                <version>3.1version> 
                <configuration>  
                    <source>1.7source>  
                    <target>1.7target> 
                    <encoding>utf-8encoding> 
                configuration>  
            plugin>  

            <plugin>  
                <artifactId>maven-source-pluginartifactId>  
                <version>2.4version>  
                <configuration>  
                    <attach>trueattach>  
                configuration>  
                <executions>  
                    <execution>  
                        <phase>packagephase>  
                        <goals>  
                            <goal>jar-no-forkgoal>  
                        goals>  
                    execution>  
                executions>  
plugin>  

<plugin>
                   <artifactId> maven-assembly-plugin artifactId>
                   <configuration>
                      <descriptorRefs>
                     <descriptorRef>jar-with-dependenciesdescriptorRef>
                      descriptorRefs>
                        <archive>
                             <manifest>
                                <mainClass>com.cetc.di.AppmainClass>
                             manifest>
                        archive>
                   configuration>
                   <executions>
                        <execution>
                             <id>make-assemblyid>
                             <phase>packagephase>
                             <goals>
                                  <goal>singlegoal>
                             goals>
                        execution>
                   executions>
              plugin>
        plugins>
    build>

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

<dependencies>
    <!—junit注解包-->
     <dependency>
      <groupId>junitgroupId>
      <artifactId>junitartifactId>
      <version>3.8.1version>
      <scope>testscope>
    dependency>
    <!—mysql连接包-->
    <dependency>
        <groupId>mysqlgroupId>
        <artifactId>mysql-connector-javaartifactId>
        <version>5.1.34version>
    dependency>
    
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatisartifactId>
            <version>3.2.7version>
        dependency>
    <!—四种日志技术包 -->
    <dependency>
        <groupId>org.bgee.log4jdbc-log4j2groupId>
        <artifactId>log4jdbc-log4j2-jdbc4.1artifactId>
        <version>1.16version>
    dependency>
    <dependency>
        <groupId>org.slf4jgroupId>
        <artifactId>slf4j-apiartifactId>
        <version>1.7.13version>
    dependency>
    <dependency>
        <groupId>org.slf4jgroupId>
        <artifactId>slf4j-log4j12artifactId>
        <version>1.7.5version>
    dependency>
    <dependency>
        <groupId>log4jgroupId>
        <artifactId>log4jartifactId>
        <version>1.2.16version>
    dependency>
    <!—servlet,jsp依赖包 -->
    <dependency>
        <groupId>javax.servletgroupId>
        <artifactId>servlet-apiartifactId>
        <version>2.5version>
        <scope>providedscope>
    dependency>
    <dependency>
        <groupId>javax.servlet.jspgroupId>
        <artifactId>jsp-apiartifactId>
        <version>2.1version>
        <scope>providedscope>
    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">

    <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>
        <typeAlias type="cn.itcast.mybatis.pojo.User" alias="user"/>
        
typeAliases>

 <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 resource="mapper.xml"/>         
    
    
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语句.



<mapper namespace="cn.itcast.mybatis.demo03.UserMapper">

<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();
        
    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片段


<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 id="baseSql">
    select  id,username,birthday,sex,address from user 
sql>

 <select id="getUserByIn" parameterType="queryVo" resultType="user">
        <include refid="baseSql"/>
    <where>
    
        <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 list=new ArrayList<>();
    list.add(1);
    list.add(10);
    list.add(16);
    vo.setIds(list);
    //将Id集合封装到vo对象中
    List 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对象属性(常用)。


<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"/>

    <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>
 
 <select id="getUserWithOrders1" resultMap="baseUserWithOrders1">
    SELECT * FROM USER u LEFT JOIN orders o ON u.id = o.user_id   WHERE u.id = 1
select>

你可能感兴趣的:(javaweb)