MyBatis课后练习题——(狂神说系列)

MyBatis课后练习题

1,导入数据库,及配置文件

1,1,导入数据库

1,1,1,smbms_address

CREATE TABLE `smbms_address` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  `contact` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '联系人姓名',
  `addressDesc` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '收货地址明细',
  `postCode` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '邮编',
  `tel` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '联系人电话',
  `createdBy` bigint(20) DEFAULT NULL COMMENT '创建者',
  `creationDate` datetime DEFAULT NULL COMMENT '创建时间',
  `modifyBy` bigint(20) DEFAULT NULL COMMENT '修改者',
  `modifyDate` datetime DEFAULT NULL COMMENT '修改时间',
  `userId` bigint(20) DEFAULT NULL COMMENT '用户ID',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;


1,1,2,smbms_bill

CREATE TABLE `smbms_bill` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  `billCode` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '账单编码',
  `productName` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '商品名称',
  `productDesc` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '商品描述',
  `productUnit` varchar(10) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '商品单位',
  `productCount` decimal(20,2) DEFAULT NULL COMMENT '商品数量',
  `totalPrice` decimal(20,2) DEFAULT NULL COMMENT '商品总额',
  `isPayment` int(10) DEFAULT NULL COMMENT '是否支付(1:未支付 2:已支付)',
  `createdBy` bigint(20) DEFAULT NULL COMMENT '创建者(userId)',
  `creationDate` datetime DEFAULT NULL COMMENT '创建时间',
  `modifyBy` bigint(20) DEFAULT NULL COMMENT '更新者(userId)',
  `modifyDate` datetime DEFAULT NULL COMMENT '更新时间',
  `providerId` int(20) DEFAULT NULL COMMENT '供应商ID',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=19 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;


1,1,3,smbms_provider

CREATE TABLE `smbms_provider` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  `proCode` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '供应商编码',
  `proName` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '供应商名称',
  `proDesc` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '供应商详细描述',
  `proContact` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '供应商联系人',
  `proPhone` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '联系电话',
  `proAddress` varchar(50) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '地址',
  `proFax` varchar(20) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '传真',
  `createdBy` bigint(20) DEFAULT NULL COMMENT '创建者(userId)',
  `creationDate` datetime DEFAULT NULL COMMENT '创建时间',
  `modifyDate` datetime DEFAULT NULL COMMENT '更新时间',
  `modifyBy` bigint(20) DEFAULT NULL COMMENT '更新者(userId)',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;


1,1,4,smbms_role

CREATE TABLE `smbms_role` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  `roleCode` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '角色编码',
  `roleName` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '角色名称',
  `createdBy` bigint(20) DEFAULT NULL COMMENT '创建者',
  `creationDate` datetime DEFAULT NULL COMMENT '创建时间',
  `modifyBy` bigint(20) DEFAULT NULL COMMENT '修改者',
  `modifyDate` datetime DEFAULT NULL COMMENT '修改时间',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;


1,1,5,smbms_user

CREATE TABLE `smbms_user` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
  `userCode` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '用户编码',
  `userName` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '用户名称',
  `userPassword` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '用户密码',
  `gender` int(10) DEFAULT NULL COMMENT '性别(1:女、 2:男)',
  `birthday` date DEFAULT NULL COMMENT '出生日期',
  `phone` varchar(15) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '手机',
  `address` varchar(30) COLLATE utf8_unicode_ci DEFAULT NULL COMMENT '地址',
  `userRole` int(10) DEFAULT NULL COMMENT '用户角色(取自角色表-角色id)',
  `createdBy` bigint(20) DEFAULT NULL COMMENT '创建者(userId)',
  `creationDate` datetime DEFAULT NULL COMMENT '创建时间',
  `modifyBy` bigint(20) DEFAULT NULL COMMENT '更新者(userId)',
  `modifyDate` datetime DEFAULT NULL COMMENT '更新时间',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=16 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;


1,2,配置文件

1,2,1,resources

1,2,1,1,mybatis-config.xml
<?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核心配置文件-->
<configuration>
    <!--引入外部配置文件-->
    <properties resource="db.properties"/>
    <!--配置日志-->
    <settings>
        <!--标准日志实现-->
        <setting name="logImpl" value="STDOUT_LOGGING"/>
        <!--驼峰命名打开-->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
    <typeAliases>
        <package name="com.zp.pojo"/>
    </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 class="com.zp.dao.UserMapper"/>-->
        <!--<mapper resource="com/zp/dao/*.xml"></mapper>-->
        <package name="com.zp.dao"/>
    </mappers>
</configuration>
1,2,1,2,db.properties
driver:com.mysql.jdbc.Driver
url:jdbc:mysql://localhost:3306/dbtest1?useSSl=true&;useUnicode=true&;characterEncoding=utf-8
username:root
password:123456

1,2,2,utils

1,2,2,1,mybatisUtils
package com.zp.utils;

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 java.io.IOException;
import java.io.InputStream;

//mybatis工具类
//SqlSessionFactory-->SqlSession
public class mybatisUtils {
    
    

    private static SqlSessionFactory sqlSessionFactory;

    static {
    
    
        try {
    
    
            //使用mybatis第一步获取 :SqlSessionFactory对象
            String resource = "mybatis-config.xml";
            InputStream inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
    }
    //既然有了 SqlSessionFactory,顾名思义,我们可以从中获得 SqlSession 的实例。SqlSession
    //提供了在数据库执行 SQL 命令所需的所有方法。你可以通过
    //SqlSession 实例来直接执行已映射的 SQL 语句。例如:
    //opensession=true->自动提交事务
        public static SqlSession getSqlSession() {
    
    
            return sqlSessionFactory.openSession(/*true*/);
        }
    }

1,3,1,pom.xml

pom.xml,只需要取其中的一些jar包即可

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <!--父工程-->
    <groupId>com.zp</groupId>
    <artifactId>test1</artifactId>
    <packaging>pom</packaging>
    <version>1.0-SNAPSHOT</version>
    <modules>
        <module>mybatis-01</module>
        <module>mybatis-02</module>
        <module>mybatis-03</module>
        <module>mybatis-04</module>
        <module>mybatis-05</module>
        <module>Mybatis-06</module>
        <module>mybatis-07</module>
        <module>mybatis-08</module>
        <module>mybatis-09</module>
        <module>mybatis-10</module>
    </modules>


    <!--导入依赖-->
    <dependencies>
        <!--导入lombok-->
            <dependency>
                <groupId>org.projectlombok</groupId>
                <artifactId>lombok</artifactId>
                <version>1.18.4</version>
                <scope>provided</scope>
            </dependency>

        <!--mysql依赖-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>
        <!--mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.3</version>
        </dependency>
        <!--junit-->
        <dependency>
            <groupId>org.junit</groupId>
            <artifactId>com.springsource.org.junit</artifactId>
            <version>4.7.0</version>
        </dependency>
        <!--log4j-->
        <!-- https://mvnrepository.com/artifact/log4j/log4j -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.8.RELEASE</version>
        </dependency>


    </dependencies>
    <build>
        <resources>
            <resource>
                <directory>src/mian/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
            <resource>
                <directory>src/mian/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
    </build>
</project>

2,创建实体类

2,1,Bill

package com.zp.pojo;
import lombok.Data;
import java.math.BigDecimal;
import java.util.Date;

@Data
public class Bill {
    
    
    private Integer id;   //id
    private String billCode; //账单编码
    private String productName; //商品名称
    private String productDesc; //商品描述
    private String productUnit; //商品单位
    private BigDecimal productCount; //商品数量
    private BigDecimal totalPrice; //总金额
    private Integer isPayment; //是否支付
    private Integer providerId; //供应商ID
    private Integer createdBy; //创建者
    private Date creationDate; //创建时间
    private Integer modifyBy; //更新者
    private Date modifyDate;//更新时间
    private String providerName;//供应商名称

}


2,2,Provider

package com.zp.pojo;

import lombok.Data;

import java.util.Date;
@Data

public class Provider {

    private Integer id;   //id
    private String proCode; //供应商编码
    private String proName; //供应商名称
    private String proDesc; //供应商描述
    private String proContact; //供应商联系人
    private String proPhone; //供应商电话
    private String proAddress; //供应商地址
    private String proFax; //供应商传真
    private Integer createdBy; //创建者
    private Date creationDate; //创建时间
    private Integer modifyBy; //更新者
    private Date modifyDate;//更新时间



}



2,3,Role

package com.zp.pojo;
import lombok.Data;

import java.util.Date;
@Data
public class Role {
    
    

    private Integer id;   //id
    private String roleCode; //角色编码
    private String roleName; //角色名称
    private Integer createdBy; //创建者
    private Date creationDate; //创建时间
    private Integer modifyBy; //更新者
    private Date modifyDate;//更新时间



}



2,4,User

package com.zp.pojo;
import lombok.Data;

import java.util.Date;
@Data
public class User {
    
    
    private Integer id; //id
    private String userCode; //用户编码
    private String userName; //用户名称
    private String userPassword; //用户密码
    private Integer gender;  //性别
    private Date birthday;  //出生日期
    private String phone;   //电话
    private String address; //地址
    private Integer userRole;    //用户角色
    private Integer createdBy;   //创建者
    private Date creationDate; //创建时间
    private Integer modifyBy;     //更新者
    private Date modifyDate;   //更新时间
    private Integer age;//年龄
    private String userRoleName;    //用户角色名称


    /*public Integer getAge() {
     *//*long time = System.currentTimeMillis()-birthday.getTime();
		Integer age = Long.valueOf(time/365/24/60/60/1000).IntegerValue();*//*
		Date date = new Date();
		Integer age = date.getYear()-birthday.getYear();
		return age;
	}*/

}



3,创建接口和接口实现类,以及测试类

3,1Bill

3,1,1,BillMapper

package com.zp.dao;


import com.zp.pojo.Bill;
import org.apache.ibatis.annotations.Param;

import java.util.List;

/**
 * @author zp
 * @version 1.0
 * @create 2020/10
 */
public interface BillMapper {
    
    
    /**
     * 根据供应商Id查询订单数量
     * @param providerId
     * @return
     */
    //根据供应商Id查询订单数量
    public int getBillCountByProviderId(@Param("providerId") Integer providerId);


    /**
     * //增加订单
     * @param bill
     * @return
     */
    public int add(Bill bill);

    /**
     * 通过查询条件获取供应商列表-getBillList
     * @param productName
     * @param providerId
     * @param isPayment
     * @param startindex
     * @param pageSize
     * @return
     * @throws Exception
     */
    //通过查询条件获取供应商列表-getBillList
    public List<Bill> getBillList(@Param("productName") String productName,
                                  @Param("providerId") String providerId,
                                  @Param("isPayment") String isPayment,
                                  @Param("startindex") Integer startindex,
                                  @Param("pageSize") Integer pageSize)throws Exception;

    //通过条件查询,查询供货商数量,模糊查询
    public int getBillCount(@Param("productName") String productName,
                            @Param("providerId") String providerId,
                            @Param("isPayment") String isPayment)throws Exception;

    //通过delId删除Bill
    public int deleteBillById(@Param("id") Integer id)throws Exception;

    //通过billId获取Bill
    public Bill getBillById(@Param("id") Integer id)throws Exception;

    //修改订单信息
    public int modify(Bill bill)throws Exception;

    //根据供应商Id删除订单信息
    public int deleteBillByProviderId(@Param("providerId") Integer providerId)throws Exception;

}




3,1,2,BillMapper.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">
<mapper namespace="com.zp.dao.BillMapper">

    <!--根据供应商Id查询订单数量-->
    <select id="getBillCountByProviderId" resultType="int">
        select count(*)from smbms.smbms_bill
        where providerId=#{providerId}
    </select>

    <!--增加订单-->
    <insert id="add" parameterType="bill">
        insert into smbms.smbms_bill (id,billCode,productName,productDesc,productUnit,productCount
        ,totalPrice,isPayment,providerId,createdBy,creationDate) values
         (#{id},#{billCode},#{productName},#{productDesc},#{productUnit},#{productCount},
         #{totalPrice},#{isPayment},#{providerId},#{createdBy},#{creationDate})
    </insert>

    <!--通过条件查询,查询供货商数量,模糊查询-->
    <select id="getBillList" resultType="bill">
        select * from smbms.smbms_bill
        <where>
            <if test="productName !=null">
                and productName like concat ('%',#{productName},'%')
            </if>
            <if test="providerId !=null">
                and providerId like concat('%',#{providerId},'%')
            </if>
            <if test="isPayment !=null">
                and isPayment like concat ('%',#{isPayment},'%')
            </if>

        </where>
        limit #{startindex},#{pageSize}
    </select>

    <!--通过delId删除Bill-->
    <delete id="deleteBillById" parameterType="int">
        delete from smbms.smbms_bill
        <where>
            id=#{id}
        </where>
    </delete>

    <!--通过billId获取Bill-->
    <select id="getBillById" resultType="bill">
        select * from smbms.smbms_bill
        <where>
            id=#{id}
        </where>
    </select>

    <!--修改订单信息-->
    <update id="modify" parameterType="bill">
        update smbms.smbms_bill
        <set>
            <if test="productName !=null">
                productName=#{productName},
            </if>
            <if test="productDesc !=null">
                productDesc=#{productDesc},
            </if>
            <if test="productCount !=null">
                productCount=#{productCount},
            </if>
        </set>
        <where>
            id=#{id}
        </where>
    </update>
</mapper>

3,1,3,BillTest

package com.zp.dao;
import com.zp.pojo.Bill;
import com.zp.pojo.User;
import com.zp.utils.mybatisUtils;

import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

public class BillTest {
    
    

    //根据供应商Id查询订单数量
    @Test
    public void getBillCountByProviderId(){
    
    
        SqlSession sqlSession = mybatisUtils.getSqlSession();
        BillMapper mapper = sqlSession.getMapper(BillMapper.class);
        int count = mapper.getBillCountByProviderId(3);
        System.out.println("供应商Id为:3的供应"+count+"种商品");
        sqlSession.close();
    }

    //增加订单
    @Test
    public void add(){
    
    
        SqlSession sqlSession = mybatisUtils.getSqlSession();
        BillMapper mapper = sqlSession.getMapper(BillMapper.class);
        Bill bill = new Bill();
        bill.setId(19);
        bill.setBillCode("BILL2016_019");
        mapper.add(bill);
        sqlSession.commit();
        sqlSession.close();
    }

    //通过条件查询,查询供货商数量,模糊查询
    @Test
    public void getBillList()throws Exception{
    
    
        SqlSession sqlSession = mybatisUtils.getSqlSession();
        BillMapper mapper = sqlSession.getMapper(BillMapper.class);
       /* Bill bill = new Bill();
        bill.setProductName("油");
        bill.setBillCode("1");
        bill.setProviderId(2);*/
        List<Bill> billList = mapper.getBillList("油", "1", "1",
                0, 2);
        for (Bill bill : billList) {
    
    
            System.out.println(bill);
        }
        sqlSession.close();
    }

//    通过id,删除
    @Test
    public void deleteBillById()throws Exception{
    
    
        SqlSession sqlSession = mybatisUtils.getSqlSession();
        BillMapper mapper = sqlSession.getMapper(BillMapper.class);
        mapper.deleteBillById(19);
        sqlSession.commit();
        sqlSession.close();

    }

    //通过billId获取Bill
    @Test
    public void getBillById() throws Exception {
    
    
        SqlSession sqlSession = mybatisUtils.getSqlSession();
        BillMapper mapper = sqlSession.getMapper(BillMapper.class);
        Bill bill = mapper.getBillById(2);
        System.out.println(bill);
        sqlSession.close();

    }

    //修改订单信息
    @Test
    public void modify()throws Exception{
    
    
        SqlSession sqlSession = mybatisUtils.getSqlSession();
        BillMapper mapper = sqlSession.getMapper(BillMapper.class);
        Bill bill = new Bill();
        bill.setProductName("爽歪歪");
        bill.setId(18);
        mapper.modify(bill);
        sqlSession.commit();
        sqlSession.close();
    }
}

3,2,Provider

3,2,1,ProviderMapper

package com.zp.dao;


import com.zp.pojo.Provider;
import org.apache.ibatis.annotations.Param;

import java.util.List;

/**
 * @author zp
 * @version 1.0
 * @create 2020/10
 */
public interface ProviderMapper {
    
    
        /**
         * 增加供应商
         * @param provider
         * @return
         * @throws Exception
         */
        public int add(Provider provider)throws Exception;


        /**
         * 通过供应商名称、编码获取供应商列表-模糊查询-providerList
         * @param proName
         * @return
         * @throws Exception
         */
        public List<Provider> getProviderList(@Param("proName") String proName,
                                              @Param("proCode")String proCode)throws Exception;

        /**
         * 通过proId删除Provider
         * @param id
         * @return
         * @throws Exception
         */
        public int deleteProviderById( int id)throws Exception;


        /**
         * 通过proId获取Provider
         * @param id
         * @return
         * @throws Exception
         */
        public Provider getProviderById(String id)throws Exception;

        /**
         * 修改用户信息
         * @param
         * @return
         * @throws Exception
         */
        public int modify(Provider provider)throws Exception;

}

3,2,2,ProviderMapper.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">
<mapper namespace="com.zp.dao.ProviderMapper">

    <insert id="add" parameterType="provider">
        insert into smbms.smbms_provider
        (id,proCode,proName,proDesc)
        values
        (#{id},#{proCode},#{proName},#{proDesc})
    </insert>

    <select id="getProviderList" parameterType="String" resultType="provider">
        select * from smbms.smbms_provider
        <where>
            <if test="proName !=null">
                and proName like concat('%',#{proName},'%')
            </if>
            <if test="proCode !=null">
                and proCode like concat ('%',#{proCode},'%')
            </if>
        </where>
    </select>

    <delete id="deleteProviderById" parameterType="int">
        delete from smbms.smbms_provider
        <where>
            id=#{id}
        </where>
    </delete>

    <select id="getProviderById" parameterType="String" resultType="provider">
        select * from smbms.smbms_provider
        <where>
            id=#{id}
        </where>
    </select>

    <update id="modify" parameterType="provider">
        update smbms.smbms_provider
        <set>
            <if test="proCode !=null">
                proCode=#{proCode},
            </if>
            <if test="proName !=null">
                proName=#{proName},
            </if>
        </set>
        <where>
            id=#{id}
        </where>
    </update>
</mapper>

3,2,3,providerTest

package com.zp.dao;

import com.zp.pojo.Provider;
import com.zp.utils.mybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.List;

public class providerTest {
    
    
    @Test
    public void add() throws Exception {
    
    
        SqlSession sqlSession = mybatisUtils.getSqlSession();
        ProviderMapper mapper = sqlSession.getMapper(ProviderMapper.class);
        Provider provider = new Provider();
        provider.setId(16);
        provider.setProCode("新添加的");
        provider.setProName("张朋");
        provider.setProDesc("主营app");
        mapper.add(provider);
        sqlSession.commit();
        sqlSession.close();
    }

    @Test
    public void getProviderList()throws Exception{
    
    
        SqlSession sqlSession = mybatisUtils.getSqlSession();
        ProviderMapper mapper = sqlSession.getMapper(ProviderMapper.class);
        /*Provider provider = new Provider();
        provider.setProName("张");
        provider.setProCode("新");*/
        List<Provider> providerList = mapper.getProviderList("张","新");
        for (Provider provider : providerList) {
    
    
            System.out.println(provider);
        }
        sqlSession.close();
    }

    @Test
    public void deleteProviderById()throws Exception{
    
    
        SqlSession sqlSession = mybatisUtils.getSqlSession();
        ProviderMapper mapper = sqlSession.getMapper(ProviderMapper.class);
        mapper.deleteProviderById(16);
        sqlSession.commit();
        sqlSession.close();
    }

    @Test
    public void  getProviderById()throws Exception{
    
    
        SqlSession sqlSession = mybatisUtils.getSqlSession();
        ProviderMapper mapper = sqlSession.getMapper(ProviderMapper.class);
        Provider provider = mapper.getProviderById("1");
        System.out.println(provider);
        sqlSession.close();
    }

    @Test
    public void modify()throws Exception{
    
    
        SqlSession sqlSession = mybatisUtils.getSqlSession();
        ProviderMapper mapper = sqlSession.getMapper(ProviderMapper.class);
        Provider provider = new Provider();
        provider.setProCode("修改proCode");
        provider.setProName("修改proName");
        provider.setId(1);
        mapper.modify(provider);
        sqlSession.commit();
        sqlSession.close();
    }
}

3,3,Role

3,3,1,RoleMapper

package com.zp.dao;

import com.zp.pojo.Role;
import org.apache.ibatis.annotations.Param;

import java.util.List;

/**
 * throws Exception这是java内部的异常
 * 一般都是自定义异常类
 * @author zp
 * @version 1.0
 * @create 2020/10
 */
public interface RoleMapper {
    
    

    //获取角色列表
    public List<Role> getRoleList()throws Exception;

    //增加角色信息
    public int add(Role role)throws Exception;

    //通过Id删除Role
    public int deleteRoleById(@Param("id") String Id)throws Exception;

    //修改角色信息
    public int modify(Role role)throws Exception;

    //通过Id获取role
    public Role getRoleById(@Param("id") Integer id)throws Exception;

    //根据roleCode,进行角色编码的唯一性验证(统计count)
    public int roleCodeIsExist(@Param("roleCode") String roleCode)throws Exception;



}

3,3,2,RoleMapper.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">
<mapper namespace="com.zp.dao.RoleMapper">

    <select id="getRoleList" resultType="role">
    select * from smbms.smbms_role
    </select>

    <insert id="add" parameterType="role">
        insert into smbms.smbms_role (id,roleCode,roleName)
        values
        (#{id},#{roleCode},#{roleName})
    </insert>

    <delete id="deleteRoleById" parameterType="int">
        delete from smbms.smbms_role
        <where>
            id=#{id}
        </where>
    </delete>

    <update id="modify" parameterType="role">
        update smbms.smbms_role
        <set>
            <if test="roleCode !=null">
                roleCode=#{roleCode},
            </if>
            <if test="roleName !=null">
                roleName=#{roleName},
            </if>
        </set>
        <where>
            id=#{id}
        </where>
    </update>

    <select id="getRoleById" parameterType="int" resultType="role">
        select *from smbms.smbms_role
        <where>
            id=#{id}
        </where>
    </select>

    <select id="roleCodeIsExist" resultType="int">
        select count(*)from smbms.smbms_role
        <where>
            roleCode=#{roleCode}
        </where>
    </select>
</mapper>



3,3,3,RoleTest

package com.zp.dao;

import com.zp.utils.mybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;
import com.zp.pojo.Role;

import java.util.List;

public class RoleTest {
    
    
    @Test
    public void getRoleList() throws Exception {
    
    
        SqlSession sqlSession = mybatisUtils.getSqlSession();
        RoleMapper mapper = sqlSession.getMapper(RoleMapper.class);
        List<Role> roleList = mapper.getRoleList();
        for (com.zp.pojo.Role role : roleList) {
    
    
            System.out.println(role);
        }
        sqlSession.close();

    }

    @Test
    public void add() throws Exception {
    
    
        SqlSession sqlSession = mybatisUtils.getSqlSession();
        RoleMapper mapper = sqlSession.getMapper(RoleMapper.class);
        Role role = new Role();
        role.setId(4);
        role.setRoleCode("zp");
        role.setRoleName("张Boss");
        mapper.add(role);
        sqlSession.commit();
        sqlSession.close();
    }

    @Test
    public void deleteRoleById() throws Exception {
    
    
        SqlSession sqlSession = mybatisUtils.getSqlSession();
        RoleMapper mapper = sqlSession.getMapper(RoleMapper.class);
        mapper.deleteRoleById("4");//字符串类型和整形都可以?
        sqlSession.commit();
        sqlSession.close();

    }

    @Test
    public void modify() throws Exception {
    
    
        SqlSession sqlSession = mybatisUtils.getSqlSession();
        RoleMapper mapper = sqlSession.getMapper(RoleMapper.class);
        Role role = new Role();
        role.setRoleCode("zpBoss");
        role.setRoleName("张Boss大大");
        role.setId(4);
        mapper.modify(role);
        sqlSession.commit();
        sqlSession.close();
    }

    @Test
    public void getRoleById()throws Exception{
    
    
        SqlSession sqlSession = mybatisUtils.getSqlSession();
        RoleMapper mapper = sqlSession.getMapper(RoleMapper.class);
        Role role = mapper.getRoleById(1);
        System.out.println(role);
        sqlSession.close();
    }

    @Test
    public void roleCodeIsExist()throws Exception{
    
    
        SqlSession sqlSession = mybatisUtils.getSqlSession();
        RoleMapper mapper = sqlSession.getMapper(RoleMapper.class);
        int cout = mapper.roleCodeIsExist("SMBMS_ADMIN");
        System.out.println(cout);
        sqlSession.close();
    }
}

3,4,User

3,4,1,UserMapper

package com.zp.dao;


import com.zp.pojo.User;
import org.apache.ibatis.annotations.Param;

import java.util.List;
import java.util.Map;

/**
 * @author zp
 * @version 1.0
 * @create 2020/10/26
 */
public interface UserMapper {
    
    
    /**
     * @param
     * @param map
     * @return
     * @throws Exception
     */
    //测试数据库是否链接成功
    List<User> getUser(Map<String,Integer>map) throws Exception;

    /**
     * 通过userCode获取User
     *
     * @param userCode
     * @return
     * @throws Exception
     */
    //通过userCode获取User
    public User getLoginUser(@Param("userCode") String userCode) throws Exception;

    /**
     * 增加用户信息
     * insert into
     * @param user
     * @return
     * @throws Exception
     */
    //增加用户信息
    public int add(User user) throws Exception;

    /**
     * 通过条件查询userList,limit分页
     *
     * @param userName
     * @param userRole
     * @return
     * @throws Exception
     */
    //通过条件查询userList,limit分页
    public List<User> getUserList(@Param("userName") String userName,
                                  @Param("userRole") Integer userRole,
                                  @Param("currentPageNO") Integer currentPageNO,
                                  @Param("pageSize") Integer pageSize)throws Exception;

    /**
     *通过条件查询-用户记录数
     * @param userName
     * @param userRole
     * @return
     * @throws Exception
     */
    //通过条件查询-用户记录数
    public int getUserCount(@Param("userName") String userName,
                            @Param("userRole") Integer userRole)throws Exception;

    /**
     * 通过userId删除user
     * delect from
     * @param id
     * @return
     */
    //通过userId删除user
    public int deleteUserById(@Param("id") Integer id);

    /**
     * 通过useId获取user
     * select from
     * @param id
     * @return
     */
    //通过useId获取user
    public User getUserById(@Param("id") Integer id);

    /**
     * 修改用户信息
     * update set
     * @param user
     * @return
     */
    //修改用户信息
    public int modify(User user);

    /**
     * update set
     * @param id
     * @param userPassword
     * @return
     */
    //修改当前用户密码
    public int updatePwd(@Param("id") Integer id, @Param("userPassword") String userPassword);
}





3,4,2,UserMapper.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">
<mapper namespace="com.zp.dao.UserMapper">
    <!--测试数据库链接是否成功-->
    <!--limit是分页,startindex是从什么时候开始
    pagesize是一页多少条数据-->
    <select id="getUser" resultType="user">
        select *from smbms.smbms_user limit #{startindex},#{pagesize};
    </select>

    <!--//通过userCode获取User-->
    <!--<select id="getLoginUser" resultType="user">
        select * from smbms.smbms_user
        where userCode=#{userCode};
        <where>
        userCode=#{userCode}
        </where>
    </select>-->
    <select id="getLoginUser" parameterType="String" resultType="user">
        select * from smbms.smbms_user
        <trim prefix="where" prefixOverrides="and | or">
            <if test="userCode!=null">
                userCode=#{userCode}
            </if>
        </trim>
    </select>

    <!--增加用户信息-->
    <insert id="add" parameterType="user">
        insert into smbms.smbms_user (userCode,userName,userPassword,gender,birthday,phone,
        address,userRole,createdBy,creationDate)
         values (#{userCode},#{userName},#{userPassword},#{gender},#{birthday},
         #{phone},#{address},#{userRole},#{createdBy},#{creationDate});
    </insert>

    <!--通过条件查询userList-->
    <select id="getUserList" parameterType="String" resultType="user">
        select * from smbms.smbms_user
        <where>
            <if test="userName !=null">
                and userName=#{userName}
            </if>
            <if test="userRole !=null">
                and userRole=#{userRole}
            </if>
        </where>
        limit #{currentPageNO},#{pageSize}
    </select>

    <!--通过条件查询-用户表记录数 String userName, int userRole-->
    <select id="getUserCount" parameterType="String" resultType="int">
        select count(*)from smbms.smbms_user
        <where>
            userName = #{userName} and userRole = #{userRole}
        </where>
    </select>
    <!--删除用户,通过id-->
    <delete id="deleteUserById">
        delete from smbms.smbms_user where id=#{id}
    </delete>

    <!--通过useId获取user-->
    <select id="getUserById" resultType="user">
        select * from smbms.smbms_user
        <where>
            id=#{id}
        </where>
    </select>

    <!--修改用户信息   User user   set会自动去掉逗号-->
    <update id="modify" parameterType="user">
        update smbms.smbms_user
        <set>
            <if test="userCode !=null">
                userCode=#{userCode},
            </if>
            <if test="userName !=null">
                userName=#{userName},
            </if>
            <if test="phone !=null">
                phone=#{phone}
            </if>
        </set>
        <where>
            id=#{id}
        </where>
    </update>

    <!--修改当前用户密码-->
    <update id="updatePwd" parameterType="String">
        update smbms.smbms_user
        <set>
            <if test="userPassword !=null">
                userPassword=#{userPassword},
            </if>
        </set>
        <where>
            id=#{id}
        </where>
    </update>


</mapper>


3,4,3,UserTest

package com.zp.dao;

import com.zp.pojo.User;
import com.zp.utils.mybatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Test;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class UserTest {
    
    
    //测试数据库是否链接成功
    @Test
    public void UserTest() throws Exception {
    
    
        SqlSession sqlSession = mybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        HashMap<String, Integer> map = new HashMap<String, Integer>();
        map.put("startindex", 0);
        map.put("pagesize", 5);
        List<User> userList = mapper.getUser(map);
        for (User user : userList) {
    
    
            System.out.println(user);
        }
        sqlSession.close();
    }

    //通过userCode获取User
    @Test
    public void getLoginUser() throws Exception {
    
    
        SqlSession sqlSession = mybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = mapper.getLoginUser("admin");
        System.out.println(user);
        sqlSession.close();
    }

    //增加用户信息
    @Test
    public void add() throws Exception {
    
    
        SqlSession sqlSession = mybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
//        int add = mapper.add(new User());
        User user = new User();
        user.setId(16);
        user.setUserCode("zp");
        mapper.add(user);
        sqlSession.commit();
        sqlSession.close();
    }

    //通过条件查询userList,limit分页
    @Test
    public void getUserList() throws Exception {
    
    
        SqlSession sqlSession = mybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> admin = mapper.getUserList("李明", 2, 0, 4);
        for (User user : admin) {
    
    
            System.out.println(user);
        }
        sqlSession.close();
    }

    //通过条件查询-用户表记录数
    @Test
    public void getUserCount() throws Exception {
    
    
        SqlSession sqlSession = mybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        int userCount = mapper.getUserCount("张华", 3);
        System.out.println(userCount);
        sqlSession.close();
    }

    //删除用户,通过id
    @Test
    public void deleteUserById() {
    
    
        SqlSession sqlSession = mybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        mapper.deleteUserById(16);
        sqlSession.commit();
        sqlSession.close();
    }

    //通过id查询用户
    @Test
    public void getUserById() {
    
    
        SqlSession sqlSession = mybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = mapper.getUserById(1);
        System.out.println(user);
        sqlSession.commit();
    }

    //通过id修改用户信息
    @Test
    public void modify() {
    
    
        SqlSession sqlSession = mybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        User user = new User();
        user.setUserName("修改用户");
        user.setId(5);
        user.setUserCode("hahha");
//      user.setPhone("11111111111");
        mapper.modify(user);
        sqlSession.commit();
        sqlSession.close();
    }

    //修改当前用户密码
    @Test
    public void updatePwd(){
    
    
        SqlSession sqlSession = mybatisUtils.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        mapper.updatePwd(1,"123456");
        sqlSession.commit();
        sqlSession.close();
    }
}

猜你喜欢

转载自blog.csdn.net/dearand/article/details/109338317