Mybatis 自学笔记【全结尾狂神说练习29道】

Mybatis

简介

什么是mybatis

MyBatis 是一款优秀的持久层框架,它支持自定义 SQL、存储过程以及高级映射。MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集的工作。MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java Objects,普通老式 Java 对象)为数据库中的记录。

中文文档官网:https://mybatis.org/mybatis-3/zh/index.html

英文文档官网:https://mybatis.org/mybatis-3/

源码地址:https://github.com/mybatis/mybatis-3

maven

<!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.5.0</version>
</dependency>
持久化

数据持久化

  • 持久化就是将程序的数据在持久状态和瞬时状态转化的过程
  • 内存:断电即失
  • 数据库(jdbc),io文件持久化
  • 生活:冷藏,罐头。

为什么需要持久化?

- 有一些对象,不能让他丢掉。
- 内存太贵了
持久层

Dao层,Service层,Controller层…

  • 完成持久化工作的代码块
  • 层界限十分明显。
为什么需要Mybatis?
  • 帮助程序员将数据存入到数据库中。
  • 方便。
  • 传统的jdbc代码太复杂了。简化。框架。自动化。
  • 不用Mybatis也可以。更容易上手。技术没有高低之分。
  • 优点:
    • 简单易学:本身就很小且简单。没有任何第三方依赖,最简单安装只要两个jar文件+配置几个sql映射文件易于学习,易于使用,通过文档和源代码,可以比较完全的掌握它的设计思路和实现。
    • 灵活:mybatis不会对应用程序或者数据库的现有设计强加任何影响。 sql写在xml里,便于统一管理和优化。通过sql语句可以满足操作数据库的所有需求。
    • 解除sql与程序代码的耦合:通过提供DAO层,将业务逻辑和数据访问逻辑分离,使系统的设计更清晰,更易维护,更易单元测试。sql和代码的分离,提高了可维护性。
    • 提供映射标签,支持对象与数据库的orm字段关系映射
    • 提供对象关系映射标签,支持对象关系组建维护
    • 提供xml标签,支持编写动态sql。

第一个Mybatis程序

思路:搭建环境–>导入Mybatis–>测试!

搭建环境
<dependencies>
        <!--mysql驱动-->
        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.38</version>
        </dependency>

        <!--mybatis-->
        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.0</version>
        </dependency>

        <!--junit-->
        <!-- https://mvnrepository.com/artifact/junit/junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
创建模块
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?usSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>

mybatis工具类

public class MybatisUtils {
    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            String resource = "mybatis-config.xml";
            InputStream  inputStream = Resources.getResourceAsStream(resource);
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static SqlSession getSqlSession(){
        SqlSession sqlSession = sqlSessionFactory.openSession();
        return sqlSession;
    }
}
编写代码
  • 实体类

    public class User {
        private int id;
        private String name;
        private String pwd;
    
        public User() {
        }
    
        public User(int id, String name, String pwd) {
            this.id = id;
            this.name = name;
            this.pwd = pwd;
        }
    
        public int getId() {
            return id;
        }
    
        public void setId(int id) {
            this.id = id;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public String getPwd() {
            return pwd;
        }
    
        public void setPwd(String pwd) {
            this.pwd = pwd;
        }
    
        @Override
        public String toString() {
            return "User{" +
                    "id=" + id +
                    ", name='" + name + '\'' +
                    ", pwd='" + pwd + '\'' +
                    '}';
        }
    }
    
  • Dao接口

    public interface UserDao {
        List<User> getUserList();
    }
    
  • 接口实现类由原来的UserDaoImpl转变为一个Mapper配置文件。

    <?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.ramelon.pojo.User">
        <select id="getUserList" resultType="com.ramelon.pojo.User">
            select * from user
        </select>
    </mapper>
    
测试

Could not find resource com/ramelon/dao/UserMapper.xml

出现类似问题需要配置maven资源配置

<!--maven 资源配置-->
<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
        </resource>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.properties</include>
                <include>**/*.xml</include>
            </includes>
        </resource>
    </resources>
</build>

org.apache.ibatis.binding.BindingException: Type interface com.ramelon.dao.UserDao is not known to the MapperRegistry.

出现类似问题需要配置MapperRegistry

<mappers>
    <mapper resource="com/ramelon/dao/UserMapper.xml"/>
</mappers>

junit 测试

public class UserDaoTest {

    @Test
    public void t1(){
        // 获取SqlSession对象
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        // 执行SQL
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        List<User> userList = mapper.getUserList();
        for(User user: userList){
            System.out.println(user);
        }

        sqlSession.close();
    }
}

问题:

  • 配置文件没有注册
  • 绑定接口错误
  • 方法名不对
  • 返回类型不对
  • Maven导出资源问题

CRUD

namespace

namespace中的包名要和Dao/Mapper接口包名一致!

select

选择,查询语句;

  • id:就是对应的namespace中的方法名。
  • resultType:Sql语句执行的返回值!
  • parameterType:参数类型!
<select id="getUserById" resultType="com.ramelon.pojo.User" parameterType="int">
    select * from user where id = #{id}
</select>
insert
  • 编写接口
  • 编写对应的mapper中sql语句
  • 测试(sqlsession.commit())
  • 下同
<insert id="addUser" parameterType="com.ramelon.pojo.User">
    insert into user (id, name, pwd) values (#{id},#{name},#{pwd})
</insert>
update
<update id="updateUser" parameterType="com.ramelon.pojo.User">
    update user set name=#{name},pwd = #{pwd} where id = #{id}
</update>
delete
<delete id="deleteUser" parameterType="int">
    delete from user where id = #{id}
</delete>
万能Map

假设,我们的实体类,或者数据库中的表,字段或者参数过多,我们应当考虑使用Map

<insert id="addUser2" parameterType="map">
    insert into user (id, name, pwd) values (#{userid},#{username},#{userpwd})
</insert>

Map传递参数,直接在sql取出key即可!【parameterType=“map”】

对象传递参数,直接在sql中取出对象的属性即可!【parameterType=“Object”】

只有一个基本类型参数的情况下,可以直接在sql中取到!

多个参数用Map,或者注解!

模糊查询
  • java代码执行的时候,通配符% %

    String value = "%小%";
    List<User> users = mapper.getUserLike(value);
    
  • 在sql拼接中使用通配符

    <select id="getUserLike" resultType="com.ramelon.pojo.User">
        select * from user where name like "%" #{value} "%"
    </select>
    

配置解析

核心配置文件
  • mybatis-config.xml

  • MyBatis的配置文件包含了深深影响MyBatis行为的设置和属性信息。

    configuration(配置)
    properties(属性)
    settings(设置)
    typeAliases(类型别名)
    typeHandlers(类型处理器)
    objectFactory(对象工厂)
    plugins(插件)
    environments(环境配置)
    environment(环境变量)
    transactionManager(事务管理器)
    dataSource(数据源)
    databaseIdProvider(数据库厂商标识)
    mappers(映射器)
    
环境配置

MyBatis可以配置成适应多种环境。

不过要记住:尽管可以配置多个环境,但每个SqlSessionFactory实例只能选择一种环境。

学会使用配置多套运行环境!

Mybatis默认的事务管理器就是JDBC,连接池:POOLED

属性(properties)

我们可以通过properties属性来实现引用配置文件

这些属性可以在外部进行配置,并可以进行动态替换。你既可以在典型的 Java 属性文件中配置这些属性,也可以在 properties 元素的子元素中设置。

db.properties.

drive=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=UTF-8
name=root
password=123456

核心配置文件写入

<properties resource="./db.properties">
  <property name="username" value="dev_user"/>
  <property name="password" value="F2Fa3!33TYyg"/>
</properties>
  • 可以直接引入外部文件
  • 可以在其中增加一些属性配置
  • 如果两个文件有同一个字段,优先使用外部配置文件。
别名(typeAliases)

这是 MyBatis 中极为重要的调整设置,它们会改变 MyBatis 的运行时行为。 下表描述了设置中各项设置的含义、默认值等。

  • 类型别名可为 Java 类型设置一个缩写名字。
  • 它仅用于 XML 配置,意在降低冗余的全限定类名书写。
    <typeAliases>
        <typeAlias type="com.ramelon.pojo.User" alias="User"/>
    </typeAliases>

也可以指定一个包名,MyBatis 会在包名下面搜索需要的 Java Bean,比

<typeAliases>
  <package name="domain.blog"/>
</typeAliases>

实体类比较少的时候,使用第一种方式。

如果实体类十分多,建议使用第二种。

第一张可以DIY别名,第二种则不行。

@Alias("author")
public class Author {
    ...
}

若有注解,则别名为其注解值。

设置
映射器(mappers)
<!-- 使用相对于类路径的资源引用 -->
<mappers>
  <mapper resource="org/mybatis/builder/AuthorMapper.xml"/>
  <mapper resource="org/mybatis/builder/BlogMapper.xml"/>
  <mapper resource="org/mybatis/builder/PostMapper.xml"/>
</mappers>
<!-- 使用完全限定资源定位符(URL) -->
<mappers>
  <mapper url="file:///var/mappers/AuthorMapper.xml"/>
  <mapper url="file:///var/mappers/BlogMapper.xml"/>
  <mapper url="file:///var/mappers/PostMapper.xml"/>
</mappers>
<!-- 使用映射器接口实现类的完全限定类名 -->
<mappers>
  <mapper class="org.mybatis.builder.AuthorMapper"/>
  <mapper class="org.mybatis.builder.BlogMapper"/>
  <mapper class="org.mybatis.builder.PostMapper"/>
</mappers>
<!-- 将包内的映射器接口实现全部注册为映射器 -->
<mappers>
  <package name="org.mybatis.builder"/>
</mappers>

注意点:

  • 接口和他的mapper配置文件必须同名!
  • 接口和他的mapper配置文件必须在同一个包下!
生命周期和作用域(Scope)

作用域和生命周期类别是至关重要的,因为错误的使用会导致非常严重的并发问题

SqlSessionFactoryBuilder

这个类可以被实例化、使用和丢弃,一旦创建了 SqlSessionFactory,就不再需要它了。 因此 SqlSessionFactoryBuilder 实例的最佳作用域是方法作用域(也就是局部方法变量)。 你可以重用 SqlSessionFactoryBuilder 来创建多个 SqlSessionFactory 实例,但最好还是不要一直保留着它,以保证所有的 XML 解析资源可以被释放给更重要的事情。

SqlSessionFactory

SqlSessionFactory 一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建另一个实例。 使用 SqlSessionFactory 的最佳实践是在应用运行期间不要重复创建多次,多次重建 SqlSessionFactory 被视为一种代码“坏习惯”。因此 SqlSessionFactory 的最佳作用域是应用作用域。 有很多方法可以做到,最简单的就是使用单例模式或者静态单例模式。

SqlSession

**每个线程都应该有它自己的 SqlSession 实例。**SqlSession 的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用域。 绝对不能将 SqlSession 实例的引用放在一个类的静态域,甚至一个类的实例变量也不行。 也绝不能将 SqlSession 实例的引用放在任何类型的托管作用域中,比如 Servlet 框架中的 HttpSession。 如果你现在正在使用一种 Web 框架,考虑将 SqlSession 放在一个和 HTTP 请求相似的作用域中。 换句话说,每次收到 HTTP 请求,就可以打开一个 SqlSession,返回一个响应后,就关闭它。 这个关闭操作很重要,为了确保每次都能执行关闭操作,你应该把这个关闭操作放到 finally 块中。 下面的示例就是一个确保 SqlSession 关闭的标准模式:

try (SqlSession session = sqlSessionFactory.openSession()) {
  // 你的应用逻辑代码
}

在所有代码中都遵循这种使用模式,可以保证所有数据库资源都能被正确地关闭。

解决属性名和字段名不一致的问题

解决办法:

  • 起别名

    <select id="getUserById" resultType="com.ramelon.pojo.User" parameterType="int">
        select id,name,pwd as password from user where id = #{id}
    </select>
    
  • resultMap

    <resultMap id="userMap" type="user">
        <result column="id" property="id"/>
        <result column="name" property="name"/>
        <result column="pwd" property="pwd"/>
    </resultMap>
    
    <select id="getUserById2" resultMap="userMap">
        select * from user where id = #{id}
    </select>
    
  • resultMap 元素是 MyBatis 中最重要最强大的元素。

  • ResultMap 的设计思想是,对简单的语句做到零配置,对于复杂一点的语句,只需要描述语句之间的关系就行了。

  • 如果这个世界总是这么简单就好了。

日志

日志工厂

如果一个数据库操作,出现了异常,我们需要排错。日志就是最好的助手。

曾经:sout,debug

现在:日志工厂!

在这里插入图片描述

  • SLF4J
  • LOG4J 【掌握】
  • LOG4J2
  • JDK_LOGGING
  • COMMONS_LOGGING
  • STDOUT_LOGGING 【掌握】
  • NO_LOGGING

在Mybatis中具体使用哪一个日志实现,在设置中设定!

STDOUT_LOGGING标准日志输入

在mybatis核心配置文件中,配置我们的日志!

<settings>
    <setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>

在这里插入图片描述

Log4j

Log4j是Apache的一个开源项目,通过使用Log4j,我们可以控制日志信息输送的目的地是控制台、文件、GUI组件,甚至是套接口服务器、NT的事件记录器、UNIX Syslog守护进程等。

1.log4j包

<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>

2.log4j.properties.

#将等级为DEBUG的日志信息输出到console和file这两个目的地,console和file的定义在下面的代码
log4j.rootLogger=DEBUG,console,file

#控制台输出的相关设置
log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.Target = System.out
log4j.appender.console.Threshold=DEBUG
log4j.appender.console.layout = org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=[%c] -%m%n

#文件输出的相关设置
log4j.appender.file = org.apache.log4j.RollingFileAppender
log4j.appender.file.File=./log/kuang.log
log4j.appender.file.MaxFileSize=10mb
log4j.appender.file.Threshold=DEBUG
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%p] [%d{yy-MM-dd}] [%c]%m%n

#日志输出级别
log4j.logger.org.mybatis=DEBUG
log4j.logger.java.sql=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG

3.配置log4j为日志实现

<settings>
<setting name="logImpl" value="Log4j"/>
</settings>

4.log4j的使用!直接测试运行测试。
在这里插入图片描述

简单使用

  • 在要使用Log4j的类中,导入包import org.apache.log4j.Logger;

  • 日志对象,参数为当前类的class

    static Logger logger = Logger.getLogger(UserDaoTest.class);;
    
  • 日志级别

    logger.info("info:进入了testLog4j");
    logger.debug("debug:进入了testLog4j");
    logger.error("error:进入了testLog4j");
    

分页

为什么要分页:

  • 减少数据的处理量
使用Limit分页
SELECT * FROM USER LIMIT startIndex,pageSize

使用Mybatis实现分页,核心sql

  • 接口

    List<User> getUserLimit(Map<String,Integer> map);
    
  • Mapper.xml

    <select id="getUserLimit" parameterType="map" resultType="user">
        select * from user limit #{startIndex},#{pageSize}
    </select>
    
  • 测试

    @Test
    public void  text03(){
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserDao mapper = sqlSession.getMapper(UserDao.class);
        HashMap<String, Integer> map = new HashMap<String, Integer>();
        map.put("startIndex",0);
        map.put("pageSize",2);
        List<User> userLimit = mapper.getUserLimit(map);
        System.out.println(userLimit);
        sqlSession.close();
    }
    
RowBounds分页
@Test // rowbounds
public void test04(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();

    // RowBounds实现
    RowBounds rowBounds = new RowBounds(1,2);
    List<User> users = sqlSession.selectList("com.ramelon.dao.UserDao.getUserRowBounds",null,rowBounds);
    for(User user:users){
        System.out.println(user);
    }
    sqlSession.close();
}
分页插件

Mybatis分页插件PageHelper

使用注解开发

面向接口编程
  • 面向接口编程

    优点:解耦,可拓展,提高复用,分层开发中,上层不用管具体的实现,大家都遵守共同的标准,使得开发变容易,规范性更好。

    在一个面向对象的系统中,系统的各种功能是由许许多多的不同对象协作完成的。在这种情况下,各个对象内部是如何实现自己的,对系统设计人员来讲就不那么重要了;

    而各个对象之间的协作关系则成为系统设计的关键。小到不同类之间的通信,大到各模块之间的交互,在系统设计之初都是要着重考虑的,这也是系统设计的主要工作内容。面向接口编程就是按照这种思想来编程。

  • 关于接口的理解

    接口从更深层次的理解,应是定义(规范,约束)与实现(名实分离的原则)的分离。

    接口的本身反应了系统设计人员对系统的抽象理解。

    接口应有两类:

    ​ 第一类是对一个个体的抽象,它可以应为一个抽象(abstract class);

    ​ 第二类是对一个个体某一方面的抽象,即形成一个抽象面(interface);

    ​ 一个个体可能有多个抽象面。抽象体与抽象面是有区别的。

使用注解开发

1.注解在接口上实现

@Select("select * from user")
List<User> getUsers();

2.需要在核心配置文件中绑定接口!

<mappers>
    <mapper class="com.ramelon.dao.UserDao"/>
</mappers>

3.测试

本质:反射机制实现

底层:动态代理

CURD

我们可以在工具类创建的时候实现自动提交事务!

public static SqlSession getSqlSession(){
    return sqlSessionFactory.openSession(true);
}

编写接口,增加注解

@Select("select * from user")
List<User> getUsers();

@Select("select * from user where id = #{id}")
User getUserById(@Param("id") int id);

@Insert("insert into user (id,name,pwd) values (#{id},#{name},#{pwd})")
int addUser(User user);

@Update("update user set name=#{name}, pwd=#{pwd} where id = #{id }")
int updateUser(User user);

@Delete("delete from user where id = #{uid}")
int deleteUser(@Param("uid") int id);

测试类

​ 【注意:我们必须要将接口类绑定注册到我们的核心配置文件中!】

关于@param注解

  • 基本类型的参数或者String类型,需要加上。
  • 引用类型不需要加。
  • 如果只有一个基本类型的话,可以忽略,但是建议加上。
  • 我们在SQL中引用的就是我们这里的@Param()中设定的属性名。
#{} ${} 区别

${}

<select id="getUser" parameterType="java.lang.String" resultType="com.kenneth.model.entity ">
        SELECT * FROM t_user WHERE name = ${name}
</select>

当你的name传入xiaoming时,sql会变成

SELECT * FROM t_user WHERE name = xiaoming

#{} (常用,对于sql注入有一定的防控作用)

<select id="getUser" parameterType="java.lang.String" resultType="com.kenneth.model.entity ">
        SELECT * FROM t_user WHERE name = #{name}
</select>

当你的name还是传入xiaoming时,sql会变成

SELECT * FROM t_user WHERE name = 'xiaoming'

注:小本子拿出来做笔记

#{}方式能够很大程度防止sql注入;${}方式无法防止Sql注入。

Mybatis详细执行流程!

  • Resources获取加载全局配置文件
  • 实例化SqlSessionFactoryBuilder构造器
  • 解析配置文件流XMLConfigBuilder
  • Configuration所有的配置信息
  • SqlSessionFactory实例化
  • transactional事务管理
  • 创建executor执行器
  • 创建SqlSession
  • 实现crud
  • 查看是否执行成功(不成功返回到transaction)
  • 提交事务
  • 关闭

Lombok

Project Lombok is a java library that automatically plugs into your editor and build tools, spicing up your java.
Never write another getter or equals method again, with one annotation your class has a fully featured builder, Automate your logging variables, and much more.

使用步骤

1.在IDEA中安装Lombok插件!

2.在项目中导入Lombok的jar包。

<!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.12</version>
    <scope>provided</scope>
</dependency>

3.在实体类上加注解

@Getter and @Setter
@FieldNameConstants
@ToString
@EqualsAndHashCode
@AllArgsConstructor, @RequiredArgsConstructor and @NoArgsConstructor
@Log, @Log4j, @Log4j2, @Slf4j, @XSlf4j, @CommonsLog, @JBossLog, @Flogger, @CustomLog
@Data  ☆
@Builder
@SuperBuilder
@Singular
@Delegate
@Value
@Accessors
@Wither
@With
@SneakyThrows
@val
@var

多对一处理

CREATE TABLE `teacher` (
  `id` INT(10) NOT NULL,
  `name` VARCHAR(30) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8

INSERT INTO teacher(`id`, `name`) VALUES (1, '秦老师'); 

CREATE TABLE `student` (
  `id` INT(10) NOT NULL,
  `name` VARCHAR(30) DEFAULT NULL,
  `tid` INT(10) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `fktid` (`tid`),
  CONSTRAINT `fktid` FOREIGN KEY (`tid`) REFERENCES `teacher` (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8

INSERT INTO `student` (`id`, `name`, `tid`) VALUES (1, '小明', 1); 
INSERT INTO `student` (`id`, `name`, `tid`) VALUES (2, '小红', 1); 
INSERT INTO `student` (`id`, `name`, `tid`) VALUES (3, '小张', 1); 
INSERT INTO `student` (`id`, `name`, `tid`) VALUES (4, '小李', 1); 
INSERT INTO `student` (`id`, `name`, `tid`) VALUES (5, '小王', 1);
测试环境搭建
  • 新建实体类Teacher,Student
  • 建立Mapper接口
  • 建立Mapper.xml文件
  • 在核心配置文件中绑定Mapper
  • 测试查询是否能够成功
按照查询嵌套处理
<mapper namespace="com.ramelon.dao.StudentMapper">
    <select id="getStudent" resultMap="StudentTeacher">
        select * from student
    </select>
    
    <resultMap id="StudentTeacher" type="Student">
        <result property="id" column="id"/>
        <result property="name" column="name"/>
        <!--复杂的属性,我们需要简单处理,对象:association 集合:collection -->
        <association property="teacher" column="tid" javaType="Teacher" select="getTeacher">

        </association>
    </resultMap>

    <select id="getTeacher" resultType="Teacher">
        select * from teacher where id = #{id}
    </select>
</mapper>
按照结果嵌套处理
<select id="getStudent2" resultMap="getStudent2">
    SELECT s.id,s.name, t.name tname FROM teacher t,student s where t.id = s.tid
</select>

<resultMap id="getStudent2" type="Student">
    <result property="id" column="id"/>
    <result property="name" column="name"/>
    <association property="teacher" javaType="Teacher">
        <result property="name" column="tname"/>
    </association>
</resultMap>

一对多处理

实体类
public class Student {
    private int id;
    private String name;
    private int tid;
}

public class Teacher {
    private int id;
    private String name;
    private List<Student> students;
}
接口
public interface TeacherMapper {

    @Select("select * from teacher where id = #{tid}")
    Teacher getTeacherById(@Param("tid") int id);

    Teacher getTeacherStudent(int id);

    Teacher getTeacherStudent2(int id);
}
按照结果嵌套查询
<!--按照结果嵌套查询-->
<select id="getTeacherStudent2" resultMap="ts2">
    SELECT s.id sid,s.name sname,t.id tid,t.name tname
    FROM student s,teacher t
    WHERE s.tid = t.id and t.id = #{id}
</select>

<resultMap id="ts2" type="Teacher">
    <result property="id" column="tid"/>
    <result property="name" column="tname"/>
    <!--
        对象:association
        集合:collection
        javaType 指定属性的类型,
        集合中的泛型信息,使用ofType获取
    -->
    <collection property="students" javaType="List">
        <result property="id" column="sid"/>
        <result property="name" column="sname"/>
    </collection>
</resultMap>
按照查询嵌套处理
<select id="getTeacherStudent" resultType="Teacher" resultMap="ts">
    select * from teacher where id = #{id}
</select>

<resultMap id="ts" type="Teacher">
    <result property="id" column="id"/>
    <result property="name" column="name"/>
    <collection property="students" javaType="List" ofType="Student" select="getStudentByTid" column="id">
        <result property="id" column="id"/>
        <result property="name" column="name"/>
    </collection>
</resultMap>

<select id="getStudentByTid" resultType="Student">
    select * from student where tid = #{id}
</select>
小结
  • 关联-association [多对一]
  • 集合-collection [一对多]
  • javaType & ofType
    • javaType用来指定实体类中属性的类型
    • ofType用来指定映射到List或者集合中的pojo类型,泛型中的约束类型!

注意点

  • 保证SQL的可读性,尽量通俗易懂
  • 注意一对多和多对一中,属性名和字段的问题
  • 如果问题不好排查错误,可以使用日志,建议使用Log4j

面试高频

  • mysql引擎
  • innoDB底层原理
  • 索引
  • 索引优化

动态SQL

动态SQL就是根据不同的条件生成不同的SQL

搭建环境
CREATE TABLE `blog`(
`id` VARCHAR(50) NOT NULL COMMENT '博客id',
`title` VARCHAR(100) NOT NULL COMMENT '博客标题',
`author` VARCHAR(30) NOT NULL COMMENT '博客作者',
`create_time` DATETIME NOT NULL COMMENT '创建时间',
`views` INT(30) NOT NULL COMMENT '浏览量'
)ENGINE=INNODB DEFAULT CHARSET=utf8

创建一个基础工程

​ 1.导包

​ 2.编写配置文件

​ 3.编写实体类

​ 4.编写实体类对应Mapper接口和Mapper.xml文件

IF
<select id="queryBlogIF" parameterType="map"  resultType="Blog">
    select * from blog where 1=1
    <if test="title != null">
        and title = #{title}
    </if>
    <if test="author != null">
        and author = #{author}
    </if>
</select>
choose(when,otherwise)
<select id="queryBlogChoose" parameterType="map" resultType="Blog">
    select * from blog
    <where>
        <choose>
            <when test="title != null">
                title = #{title}
            </when>
            <when test="author != null">
                author = #{author}
            </when>
            <otherwise>
                views >= 2000
            </otherwise>
        </choose>
    </where>
</select>
trim(where,set)
<select id="queryBlogIF" parameterType="map"  resultType="Blog">
    select * from blog
    <where>
        <if test="title != null">
            and title = #{title}
        </if>
        <if test="author != null">
            and author = #{author}
        </if>
    </where>
</select>

update set

<update id="updateBlog" parameterType="map">
    update blog
    <set>
        <if test="title != null">title=#{title},</if>
        <if test="author != null">author=#{author},</if>
    </set>
    where id = #{id}
</update>

所谓的动态SQL,本质还是SQL语句,只是我们可以在SQL层面执行一个逻辑代码。

SQL片段

有的时候,我们可能会将一些功能的部分抽取出来,方便复用!

1.使用sql标签抽取公共的部分。

2.在需要使用的地方使用include标签引用即可

<!--sql片段-->
<sql id="if-title-author">
    <if test="title != null">
        and title = #{title}
    </if>
    <if test="author != null">
        and author = #{author}
    </if>
</sql>

<select id="queryBlogIF" parameterType="map"  resultType="Blog">
    select * from blog
    <where>
        <include refid="if-title-author"></include>
    </where>
</select>

注意事项:

  • 最好基于单表来定义sql片段!

  • 不要存在where标签

foreach

动态 SQL 的另一个常见使用场景是对集合进行遍历(尤其是在构建 IN 条件语句的时候)。

<select id="selectPostIn" resultType="domain.blog.Post">
  SELECT *
  FROM POST P
  WHERE ID in
  <foreach item="item" index="index" collection="list"
      open="(" separator="," close=")">
        #{item}
  </foreach>
</select>

foreach 元素的功能非常强大,它允许你指定一个集合,声明可以在元素体内使用的集合项(item)和索引(index)变量。它也允许你指定开头与结尾的字符串以及集合项迭代之间的分隔符。这个元素也不会错误地添加多余的分隔符,看它多智能!

提示 你可以将任何可迭代对象(如 List、Set 等)、Map 对象或者数组对象作为集合参数传递给 foreach。当使用可迭代对象或者数组时,index 是当前迭代的序号,item 的值是本次迭代获取到的元素。当使用 Map 对象(或者 Map.Entry 对象的集合)时,index 是键,item 是值。

<select id="queryBlogForeach" parameterType="map" resultType="Blog">
    select * from blog
    <where>
        <foreach collection="ids" item="id" open="(" close=")" separator="or">
            id = #{id}
        </foreach>
    </where>
</select>
collection: map 的 key
id: ids 为一个collection,id为其中每一项
open: 以什么开始
clse: 以什么结束
separator: 以什么分割
select * from blog WHERE ( id = ? or id = ? ) 

动态sql就是在拼接sql语句,我们只要保证sql的正确性,按照sql的格式,去排列组合就可以了。

建议:

  • 现在Mysql中写出的完整sql,再对应的去修改成为我们的动态sql实现通用即可。

缓存

查询:连接数据库,耗资源!
	一次查询的结果,给他存在一个可以直接取到的地方!-->内存:缓存
	
我们再次查询相同数据的时候,直接走缓存,就不用走数据库了。
简介

1.什么是缓存[Cache]?

​ 存在内存中的临时数据

​ 将用户经常查询的数据放在缓存(内存)中,用户去查询数据就不用从磁盘上(关系型数据库文件)查询,从缓存中查询,从而提高查询效率,解决了高并发系统的性能问题。

2.为什么使用缓存?

​ 减少和数据库的交互次数,减少系统开销,提高系统效率

3.什么样的数据能使用缓存?

​ 经常查询并且不经常改变的数据

Mybatis 缓存
  • Mybatis包含一个非常强大的查询缓存特性,它可以非常方便地定制和配置缓存。缓存可以极大的提升效率。
  • Mybatis系统中默认定义了两级缓存:一级缓存二级缓存
    • 默认情况下,只有一级缓存开启。(SqlSession级别的缓存,也成为了本地缓存)
    • 二级缓存需要手动开启和配置,他是基于namespace级别的缓存。
    • 为了提高扩展性,Mybatis定义了缓存接口Cache。我们可以通过实现Cache接口来自定义二级缓存。
一级缓存
  • 一级缓存也叫本地缓存:SqlSession
    • 与数据库同一次会话期间查询到的数据会放在本地缓存中。
    • 以后如果需要获取相同的数据,直接从缓存中拿,没必要再去查询数据库。

测试:

​ 1.开启日志!

​ 2.测试在一个session中查询两次的记录。

@Test
public void queryUserById(){
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    User user = mapper.queryUserById(1);
    User user2 = mapper.queryUserById(1);
    System.out.println(user);
    System.out.println(user2);
}

​ 3.查看日志输出。
在这里插入图片描述

缓存失效:

​ 1.查询不同的痛惜

​ 2.增删改操作,可能会改变原来的数据,所以必定会刷新缓存!

@Test
public void queryUserById(){
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    User user = mapper.queryUserById(1);
    System.out.println(user);

    User updateUser = new User(1, "小米2", "qwertyui");
    mapper.updateUserById(updateUser);
    sqlSession.commit();

    User user2 = mapper.queryUserById(1);
    System.out.println(user2);
}

​ 3.查询不同段Mapper.xml
在这里插入图片描述

​ 3.手动清理缓存!

sqlSession.clearCache();

小结,一级缓存默认开启,只在一次sqlSession中有效,也就是拿到连接到关闭连接之间!

一级缓存相当于一个map。

二级缓存
  • 耳机缓存也叫全局缓存,一级缓存作用域太低了,所以诞生了二级缓存。
  • 基于namespace级别的缓存,一个名称空间,对应一个二级缓存。
  • 工作机制
    • 一个会话查询一条数据,这个数据就会被放在当前会话的一级缓存中
    • 如果当前会话关闭了,这个会话对应的一级缓存就没了;但是我们想要的是,会话关闭了,一级缓存中的数据被保存到二级缓存中
    • 新的会话查询信息,就可以从二级缓存中获取内容
    • 不同的mapper查出的数据会放在自己对应的缓存中(map)

步骤

​ 1.开启全局缓存

<setting name="cacheEnabled" value="true"/>

​ 2.在要使用二级缓存的Mapper中开启

<cache/>

自定义:
<!--在当前Mapper.xml中使用二级缓存-->
<cache eviction="FIFO"
    flushInterval="60000"
    size="512"
    readOnly="true"/>

​ 3.测试

问题:我们需要将实体类序列化,否则会报错。

Cause: java.io.NotSerializableException: com.ramelon.pojo.User

小结:

  • 只要开启了二级缓存,同一个Mapper下就有效。
  • 所有的数据就会先放在一级缓存中;
  • 只有当会话提交,或者关闭的时候,才会提交到二级缓存中!

原理

在这里插入图片描述

自定义缓存-Ehcache

EhCache 是一个纯Java的进程内缓存框架,具有快速、精干等特点。

要在程序中使用ehcache,先要导包。

<!-- https://mvnrepository.com/artifact/org.mybatis.caches/mybatis-ehcache -->
<dependency>
    <groupId>org.mybatis.caches</groupId>
    <artifactId>mybatis-ehcache</artifactId>
    <version>1.1.0</version>
</dependency>
<?xml version="1.0" encoding="UTF-8" ?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
        updateCheck="false">

    <!--
    diskStore:为缓存路径,ecache分为内存和磁盘两级,此属性定义磁盘的缓存位置。参数解释如下:
    user.home - 用户主目录
    user.dir - 用户当前工作目录
    java.io.tmpdir - 默认临时文件路径
    -->

    <diskStore path="./tmpdir/Tmp_EhCache"/>

    <defaultCache
        eternal="false"
        maxElementsInMemory="10000" overflowToDisk="false"
        diskPersistent="false"
        timeToIdleSeconds="1800"
        timeToLiveSeconds="259200"
        memoryStoreEvictionPolicy="LRU"/>

      <!-- 
    name:Cache的唯一标识
    maxElementsInMemory:内存中最大缓存对象数
    maxElementsOnDisk:磁盘中最大缓存对象数,若是0表示无穷大
    eternal:Element是否永久有效,一但设置了,timeout将不起作用
    overflowToDisk:配置此属性,当内存中Element数量达到maxElementsInMemory时,Ehcache将会Element写到磁盘中
    timeToIdleSeconds:设置Element在失效前的允许闲置时间。仅当element不是永久有效时使用,可选属性,默认值是0,也就是可闲置时间无穷大
    timeToLiveSeconds:设置Element在失效前允许存活时间。最大时间介于创建时间
        和失效时间之间。仅当element不是永久有效时使用,默认是0.,也就是element存活时间无穷大 
    diskPersistent:是否缓存虚拟机重启期数据 
    diskExpiryThreadIntervalSeconds:磁盘失效线程运行时间间隔,默认是120秒
    diskSpoolBufferSizeMB:这个参数设置DiskStore(磁盘缓存)的缓存区大小。默认是30MB。每个Cache都应该有自己的一个缓冲区
    memoryStoreEvictionPolicy:当达到maxElementsInMemory限制时,Ehcache将会根据指定的策略去清理内存。默认策略是LRU(最近最少使用)。你可以设置为FIFO(先进先出)或是LFU(较少使用) 
    -->



    <cache
        name="cloud_user"
        eternal="false"
        maxElementsInMemory="5000"
        overflowToDisk="false"
        diskPersistent="false"
        timeToIdleSeconds="1800"
        timeToLiveSeconds="1800"
        memoryStoreEvictionPolicy="LRU"/>
</ehcache>

练习

SQL
# CREATE DATABASE `smbms`;

USE `smbms`;

DROP TABLE IF EXISTS `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;


insert  into `smbms_address`(`id`,`contact`,`addressDesc`,`postCode`,`tel`,`createdBy`,`creationDate`,`modifyBy`,`modifyDate`,`userId`) values (1,'王丽','北京市东城区东交民巷44号','100010','13678789999',1,'2016-04-13 00:00:00',NULL,NULL,1),(2,'张红丽','北京市海淀区丹棱街3号','100000','18567672312',1,'2016-04-13 00:00:00',NULL,NULL,1),(3,'任志强','北京市东城区美术馆后街23号','100021','13387906742',1,'2016-04-13 00:00:00',NULL,NULL,1),(4,'曹颖','北京市朝阳区朝阳门南大街14号','100053','13568902323',1,'2016-04-13 00:00:00',NULL,NULL,2),(5,'李慧','北京市西城区三里河路南三巷3号','100032','18032356666',1,'2016-04-13 00:00:00',NULL,NULL,3),(6,'王国强','北京市顺义区高丽营镇金马工业区18号','100061','13787882222',1,'2016-04-13 00:00:00',NULL,NULL,3);


DROP TABLE IF EXISTS `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` bigint(20) DEFAULT NULL COMMENT '供应商ID',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=19 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;


insert  into `smbms_bill`(`id`,`billCode`,`productName`,`productDesc`,`productUnit`,`productCount`,`totalPrice`,`isPayment`,`createdBy`,`creationDate`,`modifyBy`,`modifyDate`,`providerId`) values (2,'BILL2016_002','香皂、肥皂、药皂','日用品-皂类','块','1000.00','10000.00',2,1,'2016-03-23 04:20:40',NULL,NULL,13),(3,'BILL2016_003','大豆油','食品-食用油','斤','300.00','5890.00',2,1,'2014-12-14 13:02:03',NULL,NULL,6),(4,'BILL2016_004','橄榄油','食品-进口食用油','斤','200.00','9800.00',2,1,'2013-10-10 03:12:13',NULL,NULL,7),(5,'BILL2016_005','洗洁精','日用品-厨房清洁','瓶','500.00','7000.00',2,1,'2014-12-14 13:02:03',NULL,NULL,9),(6,'BILL2016_006','美国大杏仁','食品-坚果','袋','300.00','5000.00',2,1,'2016-04-14 06:08:09',NULL,NULL,4),(7,'BILL2016_007','沐浴液、精油','日用品-沐浴类','瓶','500.00','23000.00',1,1,'2016-07-22 10:10:22',NULL,NULL,14),(8,'BILL2016_008','不锈钢盘碗','日用品-厨房用具','个','600.00','6000.00',2,1,'2016-04-14 05:12:13',NULL,NULL,14),(9,'BILL2016_009','塑料杯','日用品-杯子','个','350.00','1750.00',2,1,'2016-02-04 11:40:20',NULL,NULL,14),(10,'BILL2016_010','豆瓣酱','食品-调料','瓶','200.00','2000.00',2,1,'2013-10-29 05:07:03',NULL,NULL,8),(11,'BILL2016_011','海之蓝','饮料-国酒','瓶','50.00','10000.00',1,1,'2016-04-14 16:16:00',NULL,NULL,1),(12,'BILL2016_012','芝华士','饮料-洋酒','瓶','20.00','6000.00',1,1,'2016-09-09 17:00:00',NULL,NULL,1),(13,'BILL2016_013','长城红葡萄酒','饮料-红酒','瓶','60.00','800.00',2,1,'2016-11-14 15:23:00',NULL,NULL,1),(14,'BILL2016_014','泰国香米','食品-大米','斤','400.00','5000.00',2,1,'2016-10-09 15:20:00',NULL,NULL,3),(15,'BILL2016_015','东北大米','食品-大米','斤','600.00','4000.00',2,1,'2016-11-14 14:00:00',NULL,NULL,3),(16,'BILL2016_016','可口可乐','饮料','瓶','2000.00','6000.00',2,1,'2012-03-27 13:03:01',NULL,NULL,2),(17,'BILL2016_017','脉动','饮料','瓶','1500.00','4500.00',2,1,'2016-05-10 12:00:00',NULL,NULL,2),(18,'BILL2016_018','哇哈哈','饮料','瓶','2000.00','4000.00',2,1,'2015-11-24 15:12:03',NULL,NULL,2);

DROP TABLE IF EXISTS `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=16 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;


insert  into `smbms_provider`(`id`,`proCode`,`proName`,`proDesc`,`proContact`,`proPhone`,`proAddress`,`proFax`,`createdBy`,`creationDate`,`modifyDate`,`modifyBy`) values (1,'BJ_GYS001','北京三木堂商贸有限公司','长期合作伙伴,主营产品:茅台、五粮液、郎酒、酒鬼酒、泸州老窖、赖茅酒、法国红酒等','张国强','13566667777','北京市丰台区育芳园北路','010-58858787',1,'2013-03-21 16:52:07',NULL,NULL),(2,'HB_GYS001','石家庄帅益食品贸易有限公司','长期合作伙伴,主营产品:饮料、水饮料、植物蛋白饮料、休闲食品、果汁饮料、功能饮料等','王军','13309094212','河北省石家庄新华区','0311-67738876',1,'2016-04-13 04:20:40',NULL,NULL),(3,'GZ_GYS001','深圳市泰香米业有限公司','初次合作伙伴,主营产品:良记金轮米,龙轮香米等','郑程瀚','13402013312','广东省深圳市福田区深南大道6006华丰大厦','0755-67776212',1,'2014-03-21 16:56:07',NULL,NULL),(4,'GZ_GYS002','深圳市喜来客商贸有限公司','长期合作伙伴,主营产品:坚果炒货.果脯蜜饯.天然花茶.营养豆豆.特色美食.进口食品.海味零食.肉脯肉','林妮','18599897645','广东省深圳市福龙工业区B2栋3楼西','0755-67772341',1,'2013-03-22 16:52:07',NULL,NULL),(5,'JS_GYS001','兴化佳美调味品厂','长期合作伙伴,主营产品:天然香辛料、鸡精、复合调味料','徐国洋','13754444221','江苏省兴化市林湖工业区','0523-21299098',1,'2015-11-22 16:52:07',NULL,NULL),(6,'BJ_GYS002','北京纳福尔食用油有限公司','长期合作伙伴,主营产品:山茶油、大豆油、花生油、橄榄油等','马莺','13422235678','北京市朝阳区珠江帝景1号楼','010-588634233',1,'2012-03-21 17:52:07',NULL,NULL),(7,'BJ_GYS003','北京国粮食用油有限公司','初次合作伙伴,主营产品:花生油、大豆油、小磨油等','王驰','13344441135','北京大兴青云店开发区','010-588134111',1,'2016-04-13 00:00:00',NULL,NULL),(8,'ZJ_GYS001','慈溪市广和绿色食品厂','长期合作伙伴,主营产品:豆瓣酱、黄豆酱、甜面酱,辣椒,大蒜等农产品','薛圣丹','18099953223','浙江省宁波市慈溪周巷小安村','0574-34449090',1,'2013-11-21 06:02:07',NULL,NULL),(9,'GX_GYS001','优百商贸有限公司','长期合作伙伴,主营产品:日化产品','李立国','13323566543','广西南宁市秀厢大道42-1号','0771-98861134',1,'2013-03-21 19:52:07',NULL,NULL),(10,'JS_GYS002','南京火头军信息技术有限公司','长期合作伙伴,主营产品:不锈钢厨具等','陈女士','13098992113','江苏省南京市浦口区浦口大道1号新城总部大厦A座903室','025-86223345',1,'2013-03-25 16:52:07',NULL,NULL),(11,'GZ_GYS003','广州市白云区美星五金制品厂','长期合作伙伴,主营产品:海绵床垫、坐垫、靠垫、海绵枕头、头枕等','梁天','13562276775','广州市白云区钟落潭镇福龙路20号','020-85542231',1,'2016-12-21 06:12:17',NULL,NULL),(12,'BJ_GYS004','北京隆盛日化科技','长期合作伙伴,主营产品:日化环保清洗剂,家居洗涤专卖、洗涤用品网、墙体除霉剂、墙面霉菌清除剂等','孙欣','13689865678','北京市大兴区旧宫','010-35576786',1,'2014-11-21 12:51:11',NULL,NULL),(13,'SD_GYS001','山东豪克华光联合发展有限公司','长期合作伙伴,主营产品:洗衣皂、洗衣粉、洗衣液、洗洁精、消杀类、香皂等','吴洪转','13245468787','山东济阳济北工业区仁和街21号','0531-53362445',1,'2015-01-28 10:52:07',NULL,NULL),(14,'JS_GYS003','无锡喜源坤商行','长期合作伙伴,主营产品:日化品批销','周一清','18567674532','江苏无锡盛岸西路','0510-32274422',1,'2016-04-23 11:11:11',NULL,NULL),(15,'ZJ_GYS002','乐摆日用品厂','长期合作伙伴,主营产品:各种中、高档塑料杯,塑料乐扣水杯(密封杯)、保鲜杯(保鲜盒)、广告杯、礼品杯','王世杰','13212331567','浙江省金华市义乌市义东路','0579-34452321',1,'2016-08-22 10:01:30',NULL,NULL);


DROP TABLE IF EXISTS `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=4 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;


insert  into `smbms_role`(`id`,`roleCode`,`roleName`,`createdBy`,`creationDate`,`modifyBy`,`modifyDate`) values (1,'SMBMS_ADMIN','系统管理员',1,'2016-04-13 00:00:00',NULL,NULL),(2,'SMBMS_MANAGER','经理',1,'2016-04-13 00:00:00',NULL,NULL),(3,'SMBMS_EMPLOYEE','普通员工',1,'2016-04-13 00:00:00',NULL,NULL);


DROP TABLE IF EXISTS `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` bigint(20) 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;

insert  into `smbms_user`(`id`,`userCode`,`userName`,`userPassword`,`gender`,`birthday`,`phone`,`address`,`userRole`,`createdBy`,`creationDate`,`modifyBy`,`modifyDate`) values (1,'admin','系统管理员','1234567',1,'1983-10-10','13688889999','北京市海淀区成府路207号',1,1,'2013-03-21 16:52:07',NULL,NULL),(2,'liming','李明','0000000',2,'1983-12-10','13688884457','北京市东城区前门东大街9号',2,1,'2014-12-31 19:52:09',NULL,NULL),(5,'hanlubiao','韩路彪','0000000',2,'1984-06-05','18567542321','北京市朝阳区北辰中心12号',2,1,'2014-12-31 19:52:09',NULL,NULL),(6,'zhanghua','张华','0000000',1,'1983-06-15','13544561111','北京市海淀区学院路61号',3,1,'2013-02-11 10:51:17',NULL,NULL),(7,'wangyang','王洋','0000000',2,'1982-12-31','13444561124','北京市海淀区西二旗辉煌国际16层',3,1,'2014-06-11 19:09:07',NULL,NULL),(8,'zhaoyan','赵燕','0000000',1,'1986-03-07','18098764545','北京市海淀区回龙观小区10号楼',3,1,'2016-04-21 13:54:07',NULL,NULL),(10,'sunlei','孙磊','0000000',2,'1981-01-04','13387676765','北京市朝阳区管庄新月小区12楼',3,1,'2015-05-06 10:52:07',NULL,NULL),(11,'sunxing','孙兴','0000000',2,'1978-03-12','13367890900','北京市朝阳区建国门南大街10号',3,1,'2016-11-09 16:51:17',NULL,NULL),(12,'zhangchen','张晨','0000000',1,'1986-03-28','18098765434','朝阳区管庄路口北柏林爱乐三期13号楼',3,1,'2016-08-09 05:52:37',1,'2016-04-14 14:15:36'),(13,'dengchao','邓超','0000000',2,'1981-11-04','13689674534','北京市海淀区北航家属院10号楼',3,1,'2016-07-11 08:02:47',NULL,NULL),(14,'yangguo','杨过','0000000',2,'1980-01-01','13388886623','北京市朝阳区北苑家园茉莉园20号楼',3,1,'2015-02-01 03:52:07',NULL,NULL),(15,'zhaomin','赵敏','0000000',1,'1987-12-04','18099897657','北京市昌平区天通苑3区12号楼',2,1,'2015-09-12 12:02:12',NULL,NULL);
pojo

Bill

@Data
@AllArgsConstructor
@NoArgsConstructor
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;//供应商名称
}

Provider

@Data
@AllArgsConstructor
@NoArgsConstructor
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;//更新时间
}

Role

@Data
@AllArgsConstructor
@NoArgsConstructor
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;//更新时间
}

User

@Data
@AllArgsConstructor
@NoArgsConstructor
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;   //更新时间
}
Mapper

BillMapper

/**
 * add,增加订单
 * getBillList,通过查询条件获取供应商列表-模糊查询
 * delId删除Bill
 * modify,修改订单信息
 * getBillCountByProviderId,根据供应商ID查询订单数量
 */
public interface BillMapper {
    int add(Bill bill);
    List<Bill> getBillList(Bill bill);
    int deleteBillById(int id);
    Bill getBillById(@Param("id") String id);
    int modify(Bill bill);
    BigDecimal getBillCountByProviderId(@Param("providerId")int providerId);
}

ProviderMapper

public interface ProviderMapper {

    /**
     * add,增加供应商
     * getProviderList,通过供应商名称、编码获取供应商列表-模糊查询-providerList
     * deleteProviderById,通过proId删除Provider
     * getProviderById,通过proId获取Provider
     * modify,修改用户信息
     *
     */
    int add(Provider provider)throws Exception;
    //@Param()的意义在于,有多个参数时,可以直接通过名字区分,不需要写xml中的parameterType
    List<Provider> getProviderList(@Param("proName") String proName, @Param("proCode") String proCode)throws Exception;
    int deleteProviderById(@Param("id") int id)throws Exception;
    Provider getProviderById(@Param("id") int id)throws Exception;
    int modify(Provider provider)throws Exception;
}

RoleMapper

public interface RoleMapper {
    List<Role> getRoleList()throws Exception;
}

UserMapper

public interface UserMapper {
    /**
     * add,增加用户信息
     * getLoginUser,通过userCode获取User
     * getUserList,通过条件查询-userList
     * getUserCount,通过条件查询-用户表记录数
     * deleteUserById,通过userId删除user
     * getUserById,通过userId获取user
     * modify,修改用户信息
     * updatePwd,修改当前用户密码
     */
    int add(User user)throws Exception;
    User getLoginUser(@Param("userCode") String userCode)throws Exception;
    List<User> getUserList(@Param("userPassword") String userPassword)throws Exception;
    int getUserCount(@Param("userName") String userName)throws Exception;
    int deleteUserById(@Param("delId") String delId)throws Exception;
    User getUserById(@Param("id")String id)throws Exception;
    int modify(User user)throws Exception;
    int updatePwd( @Param("id")int id,@Param("pwd") String pwd)throws Exception;
}
etBillList(Bill bill);
    int deleteBillById(int id);
    Bill getBillById(@Param("id") String id);
    int modify(Bill bill);
    BigDecimal getBillCountByProviderId(@Param("providerId")int providerId);
}

ProviderMapper

public interface ProviderMapper {

    /**
     * add,增加供应商
     * getProviderList,通过供应商名称、编码获取供应商列表-模糊查询-providerList
     * deleteProviderById,通过proId删除Provider
     * getProviderById,通过proId获取Provider
     * modify,修改用户信息
     *
     */
    int add(Provider provider)throws Exception;
    //@Param()的意义在于,有多个参数时,可以直接通过名字区分,不需要写xml中的parameterType
    List<Provider> getProviderList(@Param("proName") String proName, @Param("proCode") String proCode)throws Exception;
    int deleteProviderById(@Param("id") int id)throws Exception;
    Provider getProviderById(@Param("id") int id)throws Exception;
    int modify(Provider provider)throws Exception;
}

RoleMapper

public interface RoleMapper {
    List<Role> getRoleList()throws Exception;
}

UserMapper

public interface UserMapper {
    /**
     * add,增加用户信息
     * getLoginUser,通过userCode获取User
     * getUserList,通过条件查询-userList
     * getUserCount,通过条件查询-用户表记录数
     * deleteUserById,通过userId删除user
     * getUserById,通过userId获取user
     * modify,修改用户信息
     * updatePwd,修改当前用户密码
     */
    int add(User user)throws Exception;
    User getLoginUser(@Param("userCode") String userCode)throws Exception;
    List<User> getUserList(@Param("userPassword") String userPassword)throws Exception;
    int getUserCount(@Param("userName") String userName)throws Exception;
    int deleteUserById(@Param("delId") String delId)throws Exception;
    User getUserById(@Param("id")String id)throws Exception;
    int modify(User user)throws Exception;
    int updatePwd( @Param("id")int id,@Param("pwd") String pwd)throws Exception;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值