MyBatis的使用

一、导入依赖

<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.4.1</version>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.44</version>
</dependency>
<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
</dependency>

二、第一个MyBatis程序

1、创建xml文件

在resources目录下创建mybatis-config.xml文件

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <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?useSSL=false&amp;useUnicode=true&amp;characterEncoding=utf-8"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>
    <!-- 每一个Mapper.xml都需要在MyBatis核心配置文件中注册   -->
    <mappers>
        <mapper resource="com/gxm/dao/UserMapper.xml"/>
    </mappers>
</configuration>
1.1报错:

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

<!-- 每一个Mapper.xml都需要在MyBatis核心配置文件中注册   -->
<mappers>
    <!--   resource 表示资源路径    -->
    <mapper resource="com/gxm/mapper/UserMapper.xml" />
    <!--        class 表示Java文件的类路径-->
    <!--        <mapper class="com.gxm.mapper.UserMapper"/>-->
</mappers>

2、创建工具类MybatisUtils

//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 语句。
    public static SqlSession getSqlSession(){
        return sqlSessionFactory.openSession();
    }
}

3、创建实体类

public class User {
    private int id;
    private String name;
    private String pwd

4.创建Dao

public interface UserDao {
    //查询所有用户
    List<User> getUserList();

    //根据id获取用户
    User getUserById(int id);

    //增加用户
    int addUser(User user);

    //修改用户信息
    int updateUser(User user);

    //删除一个用户
    int deleteUser(int id);

}

5、编写UserMapper.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.gxm.dao.UserDao">
    <!--  查询所有用户  -->
    <select id="getUserList" resultType="com.gxm.pojo.User">
        select * from mybatis.user
    </select>

    <!-- 根据id获取用户   -->
    <select id="getUserById" parameterType="int" resultType="com.gxm.pojo.User">
        select * from mybatis.user where id=#{id}
    </select>

    <!-- 添加用户   -->
    <insert id="addUser" parameterType="com.gxm.pojo.User">
        insert into mybatis.user(id,name,pwd) values(#{id},#{name},#{pwd})
    </insert>

    <!--  修改用户  -->
    <update id="updateUser" parameterType="com.gxm.pojo.User">
        update mybatis.user set name=#{name},pwd=#{pwd} where id=#{id}
    </update>

    <!-- 删除一个用户   -->
    <delete id="deleteUser" parameterType="int">
        delete from mybatis.user where id=#{id}
    </delete>
</mapper>
  • namespace=“com.gxm.dao.UserDao” 为命名空间,接口名
  • id=“getUserList” 为Dao中的方法
  • parameterType=“com.gxm.pojo.User” 是Dao方法中传入的参数类型
  • resultType=“com.gxm.pojo.User” 是Dao方法的返回值类型

5、测试

注意

  • maven由于他们的约定大于配置,我们之后可能遇见我们写的配置文件,无法被导出或者生效,解决方法

    <build>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>
    
5.1、查询所有用户

UserMapper.xml

<!--  查询所有用户  -->
<select id="getUserList" resultType="com.gxm.pojo.User">
    select * from mybatis.user
</select>
@Test
public void getUserListTest(){
    //第一步:获取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.toString());
    }
    sqlSession.close();
}

5.2、根据id查询用户

UserMapper.xml

<!-- 根据id获取用户   -->
<select id="getUserById" parameterType="int" resultType="com.gxm.pojo.User">
    select * from mybatis.user where id=#{id}
</select>
@Test
public void getUserByIdTest(){
    //获取sqlSession
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    UserDao mapper = sqlSession.getMapper(UserDao.class);
    User user = mapper.getUserById(2);
    System.out.println(user.toString());
    sqlSession.close();
}
5.3、添加用户

UserMapper.xml

<!-- 添加用户   -->
<insert id="addUser" parameterType="com.gxm.pojo.User">
    insert into mybatis.user(id,name,pwd) values(#{id},#{name},#{pwd})
</insert>
@Test
public void addUserTest(){
    //第一步:获取sqlSession
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    UserDao mapper = sqlSession.getMapper(UserDao.class);
    int res = mapper.addUser(new User(4, "李白", "123"));
    if (res>0){
        System.out.println("插入成功");
        sqlSession.commit();
    }
    sqlSession.close();
}
5.4、修改用户

UserMapper.xml

<!--  修改用户  -->
<update id="updateUser" parameterType="com.gxm.pojo.User">
    update mybatis.user set name=#{name},pwd=#{pwd} where id=#{id}
</update>
@Test
public void updateUserTest(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    UserDao mapper = sqlSession.getMapper(UserDao.class);
    int res = mapper.updateUser(new User(1, "小明", "123"));
    if (res>0){
        System.out.println("修改成功");
        sqlSession.commit();
    }
    sqlSession.close();
}
5.5、删除用户

UserMapper.xml

<!-- 删除一个用户   -->
<delete id="deleteUser" parameterType="int">
    delete from mybatis.user where id=#{id}
</delete>
@Test
public void deleteUserTest(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    UserDao mapper = sqlSession.getMapper(UserDao.class);
    int res = mapper.deleteUser(1);
    if (res>0){
        System.out.println("删除成功");
        sqlSession.commit();
    }
    sqlSession.close();
}

注意

  • 增删改都要sqlSession.commit()提交
  • 所有执行完后都要sqlSession.close()关闭

三、模糊查询

//模糊查询
List<User> query(String value);
<!-- 模糊查询   -->
<select id="query" resultType="com.gxm.pojo.User">
    select * from mybatis.user where name like "%"#{value}"%"
</select>
@Test
public void query(){
    SqlSession sqlSession = MybatisUtils.getSqlSession();
    UserDao mapper = sqlSession.getMapper(UserDao.class);
    List<User> users = mapper.query("李");
    for (User user : users) {
        System.out.println(user);
    }

    sqlSession.close();
}

四、Map传值

  • 当参数过多时,使用map传参

    //Map
    int addUser2(Map<String,Object> map);
    
    <!-- Map   -->
    <insert id="addUser2" parameterType="map">
        insert into mybatis.user (id,name,pwd) values(#{userId},#{userName},#{password})
    </insert>
    
    @Test
    public void addUser2() {
        SqlSession sqlSession = MybatisUtils.getSqlSession();
        UserDao mapper = sqlSession.getMapper(UserDao.class);
    
        HashMap<String, Object> map = new HashMap<>();
        map.put("userId", 5);
        map.put("userName", "网名");
        map.put("password", "123");
    
        mapper.addUser2(map);
    
        sqlSession.commit();
        sqlSession.close();
    }
    
    

五、环境配置

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

1、环境配置(environments)

  • MyBatis可以配置多种环境,但每个SqlSessionFactory实例只能选择一种环境。

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

2、typeAliases(类型别名)

  • 类型别名可为 Java 类型设置一个缩写名字。

  • 它仅用于 XML 配置,意在降低冗余的全限定类名书写。

    <!--  起别名  -->
    <typeAliases>
        <typeAlias type="com.gxm.pojo.User" alias="User"/>
    </typeAliases>
    
    <select id="getUser" resultType="User">
        select * from mybatis.user
    </select>
    
  • 也可以指定一个包名,MyBatis 会在包名下面搜索需要的 Java Bean

  • 在没有注解的情况下,会使用 Bean 的首字母小写的非限定类名来作为它的别名

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

    <typeAliases>
        <package name="com.gxm.pojo"/>
    </typeAliases>
    
    <select id="getUser" resultType="user">
        select * from mybatis.user
    </select>
    

3、映射器(mapper)

MapperRegister:注册绑定我们的Mapper文件

方式一:

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

方式二:使用class文件绑定注册

<mappers>
    <mapper class="com.gxm.dao.UserMapper"/>
</mappers>

注意点:

  • 接口和它的Mapper配置文件必须同名
  • 接口和它的Mapper配置文件必须在同一个包下

方式三:使用包扫描进行注入

<mappers>
    <package name="com.gxm.dao"/>
</mappers>

注意点:

  • 接口和它的Mapper配置文件必须同名
  • 接口和它的Mapper配置文件必须在同一个包下

4、开启驼峰命名

<settings>
    <!--标准的日志工厂实现 -->
    <setting name="logImpl" value="STDOUT_LOGGING"/>
    <!--是否开启驼峰命名自动映射,即从经典数据库列名 A_COLUMN 映射到经典 Java 属性名 aColumn。 -->
    <setting name="mapUnderscoreToCamelCase" value="true"/>
</settings>

六、作用域(Scope)和生命周期

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

SqlSessionFactoryBuilder

  • 这个类可以被实例化、使用和丢弃,一旦创建了 SqlSessionFactory,就不再需要它了
  • SqlSessionFactoryBuilder 实例的最佳作用域是方法作用域(也就是局部方法变量)

SqlSessionFactory

  • SqlSessionFactory 一旦被创建就应该在应用的运行期间一直存在,没有任何理由丢弃它或重新创建另一个实例
  • SqlSessionFactory 的最佳作用域是应用作用域
  • 最简单的就是使用单例模式或者静态单例模式

SqlSession

  • 每个线程都应该有它自己的 SqlSession 实例
  • SqlSession 的实例不是线程安全的,因此是不能被共享的,所以它的最佳的作用域是请求或方法作用域
  • 绝对不能将 SqlSession 实例的引用放在一个类的静态域,甚至一个类的实例变量也不行
  • 每次收到 HTTP 请求,就可以打开一个 SqlSession,返回一个响应后,就关闭它
  • 在所有代码中都遵循这种使用模式,可以保证所有数据库资源都能被正确地关闭。

七、ResultMap

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

在这里插入图片描述

方法一:起别名

<select id="getUser2" resultType="user">
    select id,name,pwd as password from mybatis.user
</select>

方法二:ResultMap

结果集映射

属性	id 	name 	password
字段	id  name 	pwd
<!--    ResultMap,解决属性和字段名不一致的问题-->
<select id="getUser3" resultMap="UserMap">
    select * from mybatis.user
</select>
<resultMap id="UserMap" type="user">
    <result property="password" column="pwd"/>
</resultMap>

八、日志

1、日志工厂

logImpl: 指定 MyBatis 所用日志的具体实现,未指定时将自动查找。

  • SLF4J
  • LOG4J(3.5.9 起废弃)
  • LOG4J2
  • JDK_LOGGING
  • COMMONS_LOGGING
  • STDOUT_LOGGING 标准日志输出
  • NO_LOGGING

在MyBatis中具体使用哪个日志实现,在mybatis-config.xml中的settings标签中设定

<settings>
    <!--标准的日志工厂实现 -->
    <setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>

在这里插入图片描述

2、LOG4J

什么是LOG4J?

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

  • 我们也可以控制每一条日志的输出格式

  • 通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程

  • 可以通过一个配置文件来灵活地进行配置,而不需要修改应用的代码

3、导入LOG4J

<!-- https://mvnrepository.com/artifact/log4j/log4j -->
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>

4、log4j.properties配置

# 将等级为DEBUG的日志信息输出到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/gxm.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

5、配置log4j为日志实现

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

简单使用

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

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

    public class Log4jTest {
    
        static Logger logger = Logger.getLogger(Log4jTest.class);
    }
    
  • 日志级别

    @Test
    public void test(){
        logger.info("info:进入了testLog4j");
        logger.debug("debug:进入了testLog4j");
        logger.error("error:进入了testLog4j");
    
    }
    

    输出结果

    [INFO][23-07-31][com.gxm.Log4jTest]info:进入了testLog4j
    [DEBUG][23-07-31][com.gxm.Log4jTest]debug:进入了testLog4j
    [ERROR][23-07-31][com.gxm.Log4jTest]error:进入了testLog4j
    

九、分页

思考:为什么要分页

  • 减少数据处理量

方式一:使用Limit分页

语法:	
    select * from mybatis.user limit startIndex,pageSize;
    select * from mybatis.user limit n; # [0,n]

接口编写:

//分页
List<TUser> getTUserByLimit(Map<String,Integer> map);

UserMapper.xml编写

<select id="getTUserByLimit" resultType="com.gxm.pojo.TUser">
    select * from mybatis.user limit #{startIndex},#{pageSize}
</select>

测试:

@Test
public void getTUserByLimit(){
    SqlSession sqlSession = MyBatisUtil.getSqlSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);

    HashMap<String, Integer> map = new HashMap<String, Integer>();
    map.put("startIndex",1);
    map.put("pageSize",3);
    List<TUser> tUserByLimit = mapper.getTUserByLimit(map);
    for (TUser tUser : tUserByLimit) {
        System.out.println(tUser);
    }

}

方式二:使用RowBounds分页

接口编写:

//使用RowBounds分页
List<TUser> getTUserRowBounds();

UserMapper.xml编写

<select id="getTUserRowBounds" resultType="com.gxm.pojo.TUser">
    select * from mybatis.user
</select>

测试:

@Test
public void getTUserRowBounds(){
    SqlSession sqlSession = MyBatisUtil.getSqlSession();
    RowBounds rowBounds = new RowBounds(2,1);
    List<TUser> TUsers = sqlSession.selectList("com.gxm.mapper.UserMapper.getTUserRowBounds", null, rowBounds);
    for (TUser tUser : TUsers) {
        System.out.println(tUser);
    }
    sqlSession.close();
    }

十、使用注解开发

  • 大家之前都学过面向对象编程,也学过接口,但在真正开发中,很多时候我们都会选择面向接口编程
    • 根本原因:解耦,可拓展,提高复用,分层开发中,上层不用管具体实现,大家都遵守共同的标准,使得开发变得容易,规范性跟好
  • 在一个面向对象的系统中,系统的各种功能是由许许多多的不同对象协作完成的。在这种情况下,各个对象内部是如何实现自己的,对系统设计人员来讲就不那么重要了
  • 而各个对象之间的协作关系则成为系统设计的关键。小到不同类之间的通信,大到各个模块之间的交互,在系统设计之初都是要着重考虑的,这也是系统设计的主要内容。面向接口编程就是按照这种思想来编程的。

关于接口的理解

  • 接口从更深层次的理解,应是定义(规范,约束)与实现的分离
  • 接口的本身反映了系统设计人员对系统的抽象理解
  • 接口应有两类:
    • 第一类是对一个个体的抽象,它可对应一个抽象体(abstract class)
    • 第二类是对一个个体某一方面的抽象,即形成一个抽象(interface)
    • 一个个体可能有多个抽象面,抽象体与抽象面是有区别的

三个面向的区别

  • 面向对象是指,我们考虑问题时,以对象为单位,考虑它的属性及方法
  • 面向过程是指,我们考虑问题时,以一个具体的流程(事务过程)为单位,考虑它的实现
  • 接口设计与非接口设计是针对复用技术而言的,与面向对象(过程)不是一个问题,更多的体现就是对系统整体的架构

使用注解

1、编写接口

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

2、在核心配置文件中注册绑定接口文件

<mappers>
    <mapper class="com.gxm.mapper.UserMapper"/>
</mappers>

3、测试

@Test
public void getUsers(){
    SqlSession sqlSession = MyBatisUtil.getSqlSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    List<DUser> users = mapper.getUsers();
    for (DUser user : users) {
        System.out.println(user);
    }
    sqlSession.close();
}

使用注解实现增删改查(CRUD)

自动提交事务

private static SqlSessionFactory build;

public static SqlSession getSqlSession(){
    //设置为true就是自动提交事务,默认为false
    return build.openSession(true);
}

增删改查

// 方法存在多个参数,所以的参数面前必须加上@Param注解
@Select("select * from user where id=#{id}")
DUser getUserById(@Param("id") int id);

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

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

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

测试

@Test
public void gteUserById(){
    SqlSession sqlSession = MyBatisUtil.getSqlSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    DUser user = mapper.getUserById(3);
    System.out.println(user);
    sqlSession.close();
}

@Test
public void addUser(){
    SqlSession sqlSession = MyBatisUtil.getSqlSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    int user = mapper.addUser(new DUser(9, "王五", "123"));
    sqlSession.close();
}

@Test
public void updateUser(){
    SqlSession sqlSession = MyBatisUtil.getSqlSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    int dayu = mapper.updateUser(new DUser(9, "dayu", "321"));
    sqlSession.close();
}

@Test
public void deleteUser(){
    SqlSession sqlSession = MyBatisUtil.getSqlSession();
    UserMapper mapper = sqlSession.getMapper(UserMapper.class);
    int i = mapper.deleteUser(9);
    sqlSession.close();
}

关于@Param()注解

  • 基本类型的参数或者String类型,需要加上
  • 引用类型不需要加
  • 如果只有一个基本类型的参数,可以忽略,但是建议大家都加上

#{} 和 ==${}==的区别

  • ==#{}==通过预编译在一定程度上能防止sql注入

  • ==${}==只是拼接sql语句

十一、复杂查询

1、多对一

  • 按照查询嵌套处理(子查询)
<!--  多表查询思路:
        1.查询所有学生信息
        2.根据查询出来学生的tid,查询对应的老师
    -->
<select id="getStudent" resultMap="StudentTeacher">
    select * from Student
</select>
<resultMap id="StudentTeacher" type="com.gxm.pojo.Student">
    <result property="id" column="id"/>
    <result property="name" column="name"/>
    <!--   复杂的属性,我们需要单独处理,
                    对象:association
                    集合:collection
         -->
    <association property="teacher" column="tid" javaType="com.gxm.pojo.Teacher" select="getTeacher"/>
</resultMap>
<select id="getTeacher" resultType="com.gxm.pojo.Teacher">
    select * from teacher where id=#{id}
</select>
  • 按照结果嵌套处理(连表查询)
<!-- 按照结果嵌套处理   -->
<select id="getStudent2" resultMap="StudentTeacher2">
    select s.id sid,s.name sname,t.name tname,t.id tid
    from student s,teacher t
    where s.tid=t.id
</select>
<resultMap id="StudentTeacher2" type="com.gxm.pojo.Student">
    <result property="id" column="sid"/>
    <result property="name" column="sname"/>
    <association property="teacher" javaType="com.gxm.pojo.Teacher">
        <result property="id" column="tid"/>
        <result property="name" column="tname"/>
    </association>
</resultMap>

2、一对多

  • 按照查询嵌套处理(子查询)
    List<Teacher2> getTeacher(@Param("tid") int id);
<select id="getTeacher" resultMap="TeacherStudent2">
    select * from teacher where id=#{tid}
</select>
<resultMap id="TeacherStudent2" type="com.gxm.pojo.Teacher2">
    <!--  不写的话就会被映射到 collection中 查出来id=0 -->
    <result property="id" column="id"/> 
    <collection property="students" javaType="ArrayList" ofType="com.gxm.pojo.Student2" select="getStudentByTeacherId" column="id"/>
</resultMap>
<select id="getStudentByTeacherId" resultType="com.gxm.pojo.Student2">
    select * from student where tid=#{tid}
</select>

3、小结

  • 按照结果嵌套处理(连表查询)
 //获取指定老师下的所有学生信息以及老师的信息
    List<Teacher2> getTeacher2(@Param("id") int id);
<select id="getTeacher2" resultMap="TeacherStudent">
    select t.id tid,t.name tname,s.name sname,s.id sid
    from teacher t,student s
    where s.tid=t.id and t.id=#{id};
</select>
<resultMap id="TeacherStudent" type="com.gxm.pojo.Teacher2">
    <result property="id" column="tid"/>
    <result property="name" column="tname"/>
    <!--  复杂的属性,我们需要单独处理
                    对象:association
                    集合:collection
            javaType=""指定属性的类型
            集合中的泛型信息,我们使用ofType获取
         -->
    <collection property="students" ofType="com.gxm.pojo.Student2">
        <result property="name" column="sname"/>
        <result property="id" column="sid"/>
    </collection>
</resultMap>
  • 关联 association 【多对一】
  • 集合 collection 【一对多】
  • javaTypeofType
    • javaType 用来指定实体类中属性的类型 ===》 ArrayList
    • ofType 用来指定映射到List或者集合中的pojo类型,泛型中的约束类型

十二、动态SQL

什么是动态SQL:动态SQL就是根据不同的条件生成不同的SQL语句

如果你之前用过 JSTL 或任何基于类 XML 语言的文本处理器,你对动态 SQL 元素可能会感觉似曾相识。在 MyBatis 之前的版本中,需要花时间了解大量的元素。借助功能强大的基于 OGNL 的表达式,MyBatis 3 替换了之前的大部分元素,大大精简了元素种类,现在要学习的元素种类比原来的一半还要少。

if
choose (when, otherwise)
trim (where, set)
foreach

if

//查询博客
List<Blog> queryBlogIF(Map map);
<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>
@Test
public void queryBlogIF(){
    SqlSession sqlSession = MyBatisUtil.getSqlSession();
    BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
    HashMap map = new HashMap();
    map.put("title","mysql");
    List<Blog> blogs = mapper.queryBlogIF(map);
    for (Blog blog : blogs) {
        System.out.println(blog);
    }
    sqlSession.close();
}

choose、when、otherwise

有时候,我们不想使用所有的条件,而只是想从多个条件中选择一个使用。针对这种情况,MyBatis 提供了 choose 元素,它有点像 Java 中的 switch 语句。但它默认每个when后面有break。

<!--choose -->
<select id="queryBlogChoose" parameterType="map" resultType="blog">
    select * from blog
    <where>
        <choose>
            <when test="title != null">
                title=#{title}
            </when>
            <when test="author != null">
                and author=#{author}
            </when>
            <otherwise>
                and views=#{views}
            </otherwise>
        </choose>
    </where>
</select>
@Test
public void queryBlogChoose(){
    SqlSession sqlSession = MyBatisUtil.getSqlSession();
    BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);
    HashMap map = new HashMap();
    map.put("title","mysql");
    map.put("author","小白");
    map.put("views","123");
    List<Blog> blogs = mapper.queryBlogChoose(map);
    for (Blog blog : blogs) {
        System.out.println(blog);
    }
    sqlSession.close();
}

set、where

wherewhere 元素只会在子元素返回任何内容的情况下才插入 “WHERE” 子句。而且,若子句的开头为 “AND” 或 “OR”,where 元素也会将它们去除。

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

等价的trim

<!-- prefixOverrides前缀覆盖-->
<select id="queryBlogIF" parameterType="map" resultType="blog">
    select * from Blog
    <trim  prefix="where" prefixOverrides="and | or">
        <if test="title != null">
            and title=#{title}
        </if>
        <if test="author != null">
            and author=#{author}
        </if>
    </trim>
</select>

set :元素会动态地在行首插入 SET 关键字,并会删掉额外的逗号

<!--更新博客  set :元素会动态地在行首插入 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>

等价的trim

<!--suffixOverrides后缀覆盖  -->
    <update id="updateBlog" parameterType="map">
        update blog
        <trim prefix="set" suffixOverrides=",">
            <if test="title != null">
                title=#{title},
            </if>
            <if test="author != null">
                author=#{author}
            </if>
        </trim>
        where id=#{id}
    </update>

注意:

  • prefixOverrides前缀覆盖
  • suffixOverrides后缀覆盖

sql

SQL片段实现SQL语句复用:

  • sql标签定义SQL语句
<sql id="if-title-author">
    <if test="title != null">
        and title=#{title}
    </if>
    <if test="author != null">
        and author=#{author}
    </if>
</sql>
  • include标签引用SQL片段
<!-- sql片段引用-->
<select id="queryBlogIF" parameterType="map" resultType="blog">
    select * from Blog
    <where>
        <include refid="if-title-author"></include>
    </where>
</select>

注意事项

  • 最好基于单表来定义SQL片段
  • SQL片段中不要存在where标签

foreach

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

<select id="getBlogForeach" parameterType="map" resultType="blog">
    select * from blog
    <where>
        <foreach collection="ids" item="id" open="and (" close=")" separator="or">
            id=#{id}
        </foreach>
    </where>
</select>
@Test
public void getBlogForeach(){
    SqlSession sqlSession = MyBatisUtil.getSqlSession();
    BlogMapper mapper = sqlSession.getMapper(BlogMapper.class);

    ArrayList<Integer> ids = new ArrayList<Integer>();
    ids.add(1);
    ids.add(2);
    ids.add(3);

    HashMap map = new HashMap();
    map.put("ids",ids);

    List<Blog> blogs = mapper.getBlogForeach(map);
    for (Blog blog : blogs) {
        System.out.println(blog);
    }

    sqlSession.close();
}
  • collection:集合对象
  • open:开头拼接什么
  • close:末尾拼接什么
  • separator:中间拼接什么

十三、缓存

使用缓存的好处:

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

1、MyBatis缓存

  • MyBatis 内置了一个强大的事务性查询缓存机制,它可以非常方便地配置和定制。 为了使它更加强大而且易于配置,我们对 MyBatis 3 中的缓存实现进行了许多改进。

  • 默认情况下,只启用了本地的会话缓存,它仅仅对一个会话中的数据进行缓存。 要启用全局的二级缓存,只需要在你的 SQL 映射文件中添加一行:

    <cache/>
    

2、一级缓存

  • 一级缓存也叫本地缓存:SqlSession
    • 与数据库同一次会话期间查询到的数据会放到本地缓存中
    • 以后如果需要获取相同的数据,直接从缓存中拿,没必要再去查询数据库

步骤

  1. 开启日志

  2. 测试在一个SqlSession中查询两次相同的记录

    @Test
    public void getUser(){
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        List<User> users = mapper.getUser();
        for (User user : users) {
            System.out.println(user);
        }
    
        System.out.println("==================");
        List<User> user2 = mapper.getUser();
        for (User user : user2) {
            System.out.println(user);
        }
        sqlSession.close();
    }
    
  3. 查看日志输出
    在这里插入图片描述

缓存失效的情况:

  1. 查询不同的东西

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

  3. 查询不同的Mapper.xml

  4. 手动清理缓存

    //清理缓存
    sqlSession.clearCache();
    

3、二级缓存

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

步骤:

  1. 全局性地开启或关闭所有映射器配置文件中已配置的任何缓存。cacheEnabled

    <settings>
        <!--显示的开启全局缓存-->
        <setting name="cacheEnabled" value="true"/>
    </settings>
    
  2. 在要使用二级缓存的mapper.xml文件中开启

    <!--在当前mapper.xml中使用二级缓存-->
    <cache />
    

    也可以自定义参数:

    <!--在当前mapper.xml中使用二级缓存-->
    <!--    
        这个更高级的配置创建了一个 FIFO 缓存,
        每隔 60 秒刷新,最多可以存储结果对象或列表的 512 个引用,
        而且返回的对象被认为是只读的,
        因此对它们进行修改可能会在不同线程中的调用者产生冲突。
        -->
    <cache
           eviction="FIFO"
           flushInterval="60000"
           size="512"
           readOnly="true"/>
    

    可用的清除策略有:

    • LRU – 最近最少使用:移除最长时间不被使用的对象。
    • FIFO – 先进先出:按对象进入缓存的顺序来移除它们。
    • SOFT – 软引用:基于垃圾回收器状态和软引用规则移除对象。
    • WEAK – 弱引用:更积极地基于垃圾收集器状态和弱引用规则移除对象。

    默认的清除策略是 LRU

    flushInterval(刷新间隔)属性可以被设置为任意的正整数,设置的值应该是一个以毫秒为单位的合理时间量。 默认情况是不设置,也就是没有刷新间隔,缓存仅仅会在调用语句时刷新。

    size(引用数目)属性可以被设置为任意正整数,要注意欲缓存对象的大小和运行环境中可用的内存资源。默认值是 1024。

    readOnly(只读)属性可以被设置为 true 或 false。只读的缓存会给所有调用者返回缓存对象的相同实例。 因此这些对象不能被修改。这就提供了可观的性能提升。而可读写的缓存会(通过序列化)返回缓存对象的拷贝。 速度上会慢一些,但是更安全,因此默认值是 false。

    提示 二级缓存是事务性的。这意味着,当 SqlSession 完成并提交时,或是完成并回滚,但没有执行 flushCache=true 的 insert/delete/update 语句时,缓存会获得更新。

  3. 测试

    @Test
    public void getUser2(){
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        SqlSession sqlSession2 = MyBatisUtil.getSqlSession();
    
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        UserMapper mapper2 = sqlSession2.getMapper(UserMapper.class);
    
        List<User> users = mapper.getUser();
        for (User user : users) {
            System.out.println(user);
        }
        //关闭会话
        sqlSession.close();
    
        System.out.println("==================");
    
        List<User> user2 = mapper2.getUser();
        for (User user : user2) {
            System.out.println(user);
        }
        sqlSession2.close();
    }
    
  4. 查看日志

在这里插入图片描述

问题:

  • mapper.xml文件的cache设置中没有配置readOnly="true"报错Caused by: java.io.NotSerializableException: com.gxm.pojo.User

    <cache
           eviction="FIFO"
           flushInterval="60000"
           size="512" />
    

解决方法

  • 可以将实体类序列化

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    public class User implements Serializable {
        private int id;
        private String name;
        private String pwd;
    }
    
  • 加上readOnly=“true”

    <cache
           eviction="FIFO"
           flushInterval="60000"
           size="512"
           readOnly="true"/>
    

小结:

  • 只要开启了二级缓存,在同一Mapper下就有效
  • 所以的数据都会先放在一级缓存中
  • 只要当会话提交或者关闭的时候,一级缓存中的数据才会放到二级缓存中
《餐馆点餐管理系统——基于Java和MySQL的课程设计解析》 在信息技术日益发达的今天,餐饮行业的数字化管理已经成为一种趋势。本次课程设计的主题是“餐馆点餐管理系统”,它结合了编程语言Java和数据库管理系统MySQL,旨在帮助初学者理解如何构建一个实际的、具有基本功能的餐饮管理软件。下面,我们将深入探讨这个系统的实现细节及其所涉及的关键知识点。 我们要关注的是数据库设计。在“res_db.sql”文件中,我们可以看到数据库的结构,可能包括菜品表、订单表、顾客信息表等。在MySQL中,我们需要创建这些表格并定义相应的字段,如菜品ID、名称、价格、库存等。此外,还要设置主键、外键来保证数据的一致性和完整性。例如,菜品ID作为主键,确保每个菜品的唯一性;订单表中的顾客ID和菜品ID则作为外键,与顾客信息表和菜品表关联,形成数据间的联系。 接下来,我们来看Java部分。在这个系统中,Java主要负责前端界面的展示和后端逻辑的处理。使用Java Swing或JavaFX库可以创建用户友好的图形用户界面(GUI),让顾客能够方便地浏览菜单、下单。同时,Java还负责与MySQL数据库进行交互,通过JDBC(Java Database Connectivity)API实现数据的增删查改操作。在程序中,我们需要编写SQL语句,比如INSERT用于添加新的菜品信息,SELECT用于查询所有菜品,UPDATE用于更新菜品的价格,DELETE用于删除不再提供的菜品。 在系统设计中,我们还需要考虑一些关键功能的实现。例如,“新增菜品和价格”的功能,需要用户输入菜品信息,然后通过Java程序将这些信息存储到数据库中。在显示所有菜品的功能上,程序需要从数据库获取所有菜品数据,然后在界面上动态生成列表或者表格展示。同时,为了提高用户体验,可能还需要实现搜索和排序功能,允许用户根据菜品名称或价格进行筛选。 另外,安全性也是系统设计的重要一环。在连接数据库时,要避免SQL注入攻击,可以通过预编译的PreparedStatement对象来执行SQL命令。对于用户输入的数据,需要进行验证和过滤,防止非法字符和异常值。 这个“餐馆点餐管理系统”项目涵盖了Java编程、数据库设计与管理、用户界面设计等多个方面,是一个很好的学习实践平台。通过这个项目,初学者不仅可以提升编程技能,还能对数据库管理和软件工程有更深入的理解。在实际开发过程中,还会遇到调试、测试、优化等挑战,这些都是成长为专业开发者不可或缺的经验积累
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值