洪君99--Java篇mybatis章:动态查询SQL和缓存,以及优化调试、Nginx简介

动态查询是mybatis的特色之一,拼接SQL。

缓存的实际意义:减少对数据库的I/O操作,

直接拿内存中的数据

Student
sid sname sage
2 张三 34
5 李四 21

动态添加:

例如:只添加student的名字,而年龄稍后做添加。

动态SQL可以拼接SQL语句,从而达到目的。

注意数据库中的sname列段必须允许为空。

<?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>MybatisSpace</groupId>
    <artifactId>MybatisSpace</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

    <name>MybatisSpace Maven Webapp</name>
    <!-- FIXME change it to the project's website -->
    <url>http://www.example.com</url>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>

        <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.43</version>
        </dependency>

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

    </dependencies>

    <build>
        <finalName>MybatisSpace</finalName>

        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
        </resources>

        <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
            <plugins>
                <plugin>
                    <artifactId>maven-clean-plugin</artifactId>
                    <version>3.0.0</version>
                </plugin>
                <!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
                <plugin>
                    <artifactId>maven-resources-plugin</artifactId>
                    <version>3.0.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <version>3.7.0</version>
                </plugin>
                <plugin>
                    <artifactId>maven-surefire-plugin</artifactId>
                    <version>2.20.1</version>
                </plugin>
                <plugin>
                    <artifactId>maven-war-plugin</artifactId>
                    <version>3.2.0</version>
                </plugin>
                <plugin>
                    <artifactId>maven-install-plugin</artifactId>
                    <version>2.5.2</version>
                </plugin>
                <plugin>
                    <artifactId>maven-deploy-plugin</artifactId>
                    <version>2.8.2</version>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</project>

与上期的区别就是多了一个log4j。

mybatis的核心配置,如数据库连接、别名,与上期的相同。

log4j配置:log4j.properties

放在resources

### 把日志信息输出到控制台 ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} [%c]-[%p] %m%n



### 设置优先级别,以及输出源###
log4j.rootLogger=debug,stdout

 log4j:检查所发送的SQL或者报错,以及运行过程。

package com.hc.entity;


import java.io.Serializable;

public class Student implements Serializable{

    private int stuId;
    private String stuName;
    private String stuSex;
    private int stuAge;

    public Student() {

    }

    public Student(String stuName, String stuSex, int stuAge) {
        this.stuName = stuName;
        this.stuSex = stuSex;
        this.stuAge = stuAge;
    }

    public int getStuId() {
        return stuId;
    }

    public void setStuId(int stuId) {
        this.stuId = stuId;
    }

    public String getStuName() {
        return stuName;
    }

    public void setStuName(String stuName) {
        this.stuName = stuName;
    }

    public String getStuSex() {
        return stuSex;
    }

    public void setStuSex(String stuSex) {
        this.stuSex = stuSex;
    }

    public int getStuAge() {
        return stuAge;
    }

    public void setStuAge(int stuAge) {
        this.stuAge = stuAge;
    }
}

开启缓存,必须实现序列化接口

封装的student类。

package com.hc.dao;

import com.hc.entity.Student;

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

public interface StudentDao {
    public List<Student> selectStudent(Map<String,Object> map);
    public List<Student> allStudent();
    public void insertStudent(Map<String,Object> map);
    public void deleteStudents(int[] stuids);
    public void deleteStudentList(List<Integer> stuids);
    public void updateStudent(Map<String,Object> map);
}

dao接口,方便调用对象映射关系文件中的SQL,接口名与mapper的id相同。 

<?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.hc.dao.StudentDao">

    <cache></cache>

    <select id="selectStudent" resultType="Student">
        select * from student
        <where>
            <trim prefixOverrides="and">
                <if test="stuid!=null">
                    and stuId=#{stuid}
                </if>
                <if test="stuname!=null and stuname!=''">
                    and stuName like concat('%',#{stuname},'%')
                </if>

            </trim>
        </where>
    </select>

    <select id="allStudent" resultType="Student">
        select * from student
    </select>

    <update id="updateStudent" parameterType="map">
        update student
        <set>
            <trim suffixOverrides=",">
                <if test="students.stuName!=null">
                    stuName=#{students.stuName},
                </if>
                <if test="students.stuSex!=null">
                    stuSex=#{students.stuSex},
                </if>
                <if test="students.stuAge!=null and students.stuAge!=0">
                    stuAge=#{students.stuAge},
                </if>
            </trim>
        </set>
        <if test="students.stuId!=null">
           where stuId=#{students.stuId}
        </if>
    </update>

    <delete id="deleteStudentList">
        delete from student
        <where>
            stuId in
            <foreach collection="list" item="stuids" open="(" close=")" separator=",">
                #{stuids}
            </foreach>
        </where>
    </delete>
    
    <delete id="deleteStudents">
        delete from student
        <where>
            stuId in
            <foreach collection="array" item="stuids" open="(" close=")" separator=",">
                #{stuids}
            </foreach>
        </where>
    </delete>
    
    

    <sql id="keys">
        <trim suffixOverrides=",">
            <if test="students.stuName!=null">
                stuName,
            </if>
            <if test="students.stuSex!=null">
                stuSex,
            </if>
            <if test="students.stuAge!=null and students.stuAge!=0">
                stuAge,
            </if>
        </trim>
    </sql>

    <sql id="values">
        <trim suffixOverrides=",">
            <if test="students.stuName!=null">
                #{students.stuName},
            </if>
            <if test="students.stuSex!=null">
                #{students.stuSex},
            </if>
            <if test="students.stuAge!=null and students.stuAge!=0">
                #{students.stuAge},
            </if>
        </trim>
    </sql>

    <insert id="insertStudent" parameterType="map">
        insert into student(<include refid="keys"></include>) values(<include refid="values"></include>)
    </insert>

</mapper>

映射关系文件。

stuName like concat('%',#{stuname},'%'):拼接like模糊查询SQL

对象属性为int:and students.stuAge!=0,判断不为0

传进来的参数为Map:判断条件中,Map名字.对象属性stuName。赋值,#{Map名字.对象属性stuName}

<sql>:做判断,拼接

open="(" close=")" separator=",":for循环开始是,中间以区别,最后是

prefixOverrides:去除第一个and

suffixOverrides:去除最后一个,

package com.hc.test;

import com.hc.dao.StudentDao;
import com.hc.entity.Student;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

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

public class First {

    private SqlSession session;
    private StudentDao studentDao;

    @Before
    public void before(){
        SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(getClass().getClassLoader().getResourceAsStream("myBatis-config.xml"));
        session = factory.openSession();
        studentDao = session.getMapper(StudentDao.class);
    }

    @Test
    public void updateStudent(){
        Map<String,Object> map=new HashMap<>();
        Student student=new Student();
        student.setStuId(1);
        student.setStuName("天花");
        map.put("students",student);
        studentDao.updateStudent(map);
    }

    @Test
    public void deleteStudentList(){
        List<Integer> stuids=new ArrayList<>();
        stuids.add(2);
        stuids.add(3);
        studentDao.deleteStudentList(stuids);
    }

    @Test
    public void deleteStudents(){
        int[] stuids={5,6};
        studentDao.deleteStudents(stuids);
    }


    @Test
    public void insertStudent(){
        Map<String,Object> map=new HashMap<>();
        Student student=new Student();
        student.setStuName("天魔");
        map.put("students",student);
        studentDao.insertStudent(map);
    }

    @Test
    public void testallStudent(){
        List<Student> students= studentDao.allStudent();
        for (Student student : students) {
            System.out.println(student.getStuId()+"\t"+student.getStuName()+"\t"+student.getStuSex()+"\t"+student.getStuAge());
            System.out.println("\n");
        }
    }

    @Test
    public void selectStudent(){
        Map<String,Object> map=new HashMap<>();
//        map.put("stuid",1);
        map.put("stuname","天");
        List<Student> students=studentDao.selectStudent(map);
        for (Student student : students) {
            System.out.println(student.getStuId()+"\t"+student.getStuName()+"\t"+student.getStuSex()+"\t"+student.getStuAge());
            System.out.println("\n");
        }
    }

    @After
    public void after(){
        session.commit();
        session.close();
    }
}

单元测试!

nice! 


 

一级缓存:mybatis默认缓存。

二级缓存:在对象映射中配置标记

public class Student implements Serializable:对象序列化

<cache></cache>:对象映射标记

三级缓存:第三方数据库

hibernate:一级缓存默认是Session,二级缓存是SessionFactory

                   二级默认缓存对象,list等需要开启查询缓存

mybatis:一级缓存默认是SqlSession,二级缓存是SqlSessionFactory

                    可直接缓存对象或者list等,mapper方法可配置是否刷新

优化调试:

EXPLAIN
select * from student


alter table student ADD index stunameindexs(stuName)

EXPLAIN:关键字,注意rows列
 

方法:添加索引

普通索引:alter table 表名student ADD index 索引名stunameindexs(目标stuName)

Nginx("engine x")是一款是由俄罗斯的程序设计师Igor Sysoev所开发高性能的 Web和 反向代理 服务器,也是一个 IMAP/POP3/SMTP 代理服务器。

在高连接并发的情况下,Nginx是Apache服务器不错的替代品。

资源:nginx

猜你喜欢

转载自blog.csdn.net/qq_43532342/article/details/83591326