MyBatis 教程02

3. 动态sql
4. 分页
5. 大对象处理
6. 缓存
<!--
\src\com\java1234\mappers\StudentMapper.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.java1234.mappers.StudentMapper"> <!-- 1,size:表示缓存cache中能容纳的最大元素数。默认是1024; 2,flushInterval:定义缓存刷新周期,以毫秒计; 3,eviction:定义缓存的移除机制;默认是LRU(least recently userd,最近最少使用),还有FIFO(first in first out,先进先出) 4,readOnly:默认值是false,假如是true的话,缓存只能读。 --> <cache size="1024" flushInterval="60000" eviction="LRU" readOnly="false"/> <resultMap type="Student" id="StudentResult"> <id property="id" column="id"/> <result property="name" column="name"/> <result property="age" column="age"/> </resultMap> <select id="findStudents" resultMap="StudentResult" flushCache="false" useCache="true"> select * from t_student </select> <select id="findStudents2" parameterType="Map" resultMap="StudentResult"> select * from t_student <if test="start!=null and size!=null"> limit #{start},#{size} </if> </select> <insert id="insertStudent" parameterType="Student" flushCache="true"> insert into t_student values(null,#{name},#{age},#{pic},#{remark}); </insert> <select id="getStudentById" parameterType="Integer" resultType="Student"> select * from t_student where id=#{id} </select> <select id="searchStudents6" resultMap="StudentResult"> select * from t_student where name like #{param1} and age=#{param2} </select> <select id="searchStudents" parameterType="Map" resultMap="StudentResult"> select * from t_student where gradeId=#{gradeId} <if test="name!=null"> and name like #{name} </if> <if test="age!=nulll"> and age=#{age} </if> </select> <select id="searchStudents2" parameterType="Map" resultMap="StudentResult"> select * from t_student <choose> <when test="searchBy=='gradeId'"> where gradeId=#{gradeId} </when> <when test="searchBy=='name'"> where name like #{name} </when> <otherwise> where age=#{age} </otherwise> </choose> </select> <select id="searchStudents3" parameterType="Map" resultMap="StudentResult"> select * from t_student <where> <if test="gradeId!=null"> gradeId=#{gradeId} </if> <if test="name!=null"> and name like #{name} </if> <if test="age!=nulll"> and age=#{age} </if> </where> </select> <select id="searchStudents4" parameterType="Map" resultMap="StudentResult"> select * from t_student <trim prefix="where" prefixOverrides="and|or"> <if test="gradeId!=null"> gradeId=#{gradeId} </if> <if test="name!=null"> and name like #{name} </if> <if test="age!=nulll"> and age=#{age} </if> </trim> </select> <select id="searchStudents5" parameterType="Map" resultMap="StudentResult"> select * from t_student <if test="gradeIds!=null"> <where> gradeId in <foreach item="gradeId" collection="gradeIds" open="(" separator="," close=")"> #{gradeId} </foreach> </where> </if> </select> <update id="updateStudent" parameterType="Student"> update t_student <set> <if test="name!=null"> name=#{name}, </if> <if test="age!=null"> age=#{age}, </if> </set> where id=#{id} </update> </mapper> <!-- \src\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> <properties resource="jdbc.properties"/> <typeAliases> <package name="com.java1234.model"/> </typeAliases> <environments default="development"> <environment id="development"> <transactionManager type="JDBC" /> <dataSource type="POOLED"> <property name="driver" value="${jdbc.driverClassName}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> </dataSource> </environment> <environment id="test"> <transactionManager type="JDBC" /> <dataSource type="POOLED"> <property name="driver" value="${jdbc.driverClassName}" /> <property name="url" value="${jdbc.url}" /> <property name="username" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> </dataSource> </environment> </environments> <mappers> <package name="com.java1234.mappers"/> </mappers> </configuration>
# \src\jdbc.properties
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/db_mybatis
jdbc.username=root
jdbc.password=123456

# \src\log4j.properties
log4j.rootLogger=info,appender1,appender2

log4j.appender.appender1=org.apache.log4j.ConsoleAppender 

log4j.appender.appender2=org.apache.log4j.FileAppender 
log4j.appender.appender2.File=C:/logFile.txt
 
log4j.appender.appender1.layout=org.apache.log4j.TTCCLayout
log4j.appender.appender2.layout=org.apache.log4j.TTCCLayout  
// \src\com\java1234\mappers\StudentMapper.java
package com.java1234.mappers;

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

import org.apache.ibatis.session.RowBounds;

import com.java1234.model.Student;


public interface StudentMapper {

    public List<Student> searchStudents(Map<String,Object> map);
    
    public List<Student> searchStudents2(Map<String,Object> map);
    
    public List<Student> searchStudents3(Map<String,Object> map);
    
    public List<Student> searchStudents4(Map<String,Object> map);
    
    public List<Student> searchStudents5(Map<String,Object> map);
    
    public List<Student> searchStudents6(String name,int age);
    
    public int updateStudent(Student student);
    
    public int insertStudent(Student student);
    
    public Student getStudentById(Integer id);
    
    public List<Student> findStudents(RowBounds rowBounds);
    
    public List<Student> findStudents2(Map<String,Object> map);
}

// \src\com\java1234\model\Student.java
package com.java1234.model;

public class Student {

    private Integer id;
    private String name;
    private Integer age;
    private byte[] pic;
    private String remark;
    
    
    public Student() {
        super();
        // TODO Auto-generated constructor stub
    }
    
    
    
    
    public Student(Integer id, String name, Integer age) {
        super();
        this.id = id;
        this.name = name;
        this.age = age;
    }




    public Student(String name, Integer age) {
        super();
        this.name = name;
        this.age = age;
    }



    public Integer getId() {
        return id;
    }
    public void setId(Integer id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Integer getAge() {
        return age;
    }
    public void setAge(Integer age) {
        this.age = age;
    }
    



    public byte[] getPic() {
        return pic;
    }




    public void setPic(byte[] pic) {
        this.pic = pic;
    }




    public String getRemark() {
        return remark;
    }




    public void setRemark(String remark) {
        this.remark = remark;
    }




    @Override
    public String toString() {
        return "Student [id=" + id + ", name=" + name + ", age=" + age
                + ", remark=" + remark + "]";
    }

    
    
    
}

// \src\com\java1234\service\StudentTest.java
package com.java1234.service;

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

import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.java1234.mappers.StudentMapper;
import com.java1234.model.Student;
import com.java1234.util.SqlSessionFactoryUtil;

public class StudentTest {

    private static Logger logger=Logger.getLogger(StudentTest.class);
    private SqlSession sqlSession=null;
    private StudentMapper studentMapper=null;
    
    /**
     * 测试方法前调用
     * @throws Exception
     */
    @Before
    public void setUp() throws Exception {
        sqlSession=SqlSessionFactoryUtil.openSession();
        studentMapper=sqlSession.getMapper(StudentMapper.class);
    }

    /**
     * 测试方法后调用
     * @throws Exception
     */
    @After
    public void tearDown() throws Exception {
        sqlSession.close();
    }

    @Test
    public void testSearchStudents() {
        logger.info("添加学生(带条件)");
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("gradeId", 2);
        // map.put("name", "%李%");
        // map.put("age", 11);
        List<Student> studentList=studentMapper.searchStudents(map);
        for(Student student:studentList){
            System.out.println(student);
        }
    }
    
    @Test
    public void testSearchStudents2() {
        logger.info("添加学生(带条件)");
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("searchBy", "age");
        map.put("gradeId", 2);
        map.put("name", "%李%");
        map.put("age", 11);
        List<Student> studentList=studentMapper.searchStudents2(map);
        for(Student student:studentList){
            System.out.println(student);
        }
    }

    @Test
    public void testSearchStudents3() {
        logger.info("添加学生(带条件)");
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("gradeId", 2);
        map.put("name", "%李%");
        map.put("age", 11);
        List<Student> studentList=studentMapper.searchStudents3(map);
        for(Student student:studentList){
            System.out.println(student);
        }
    }
    
    @Test
    public void testSearchStudents4() {
        logger.info("添加学生(带条件)");
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("gradeId", 2);
        // map.put("name", "%李%");
        // map.put("age", 11);
        List<Student> studentList=studentMapper.searchStudents4(map);
        for(Student student:studentList){
            System.out.println(student);
        }
    }
    
    @Test
    public void testSearchStudents5() {
        logger.info("添加学生(带条件)");
        Map<String,Object> map=new HashMap<String,Object>();
        List<Integer> gradeIds=new ArrayList<Integer>();
        // gradeIds.add(1);
        gradeIds.add(2);
        map.put("gradeIds", gradeIds);
        List<Student> studentList=studentMapper.searchStudents5(map);
        for(Student student:studentList){
            System.out.println(student);
        }
    }
    
    @Test
    public void testUpdateStudent(){
        logger.info("更新学生(带条件)");
        Student student=new Student();
        student.setId(1);
        student.setName("张三3");
        student.setAge(13);
        studentMapper.updateStudent(student);
        sqlSession.commit();
    }
}

// \src\com\java1234\service\StudentTest2.java
package com.java1234.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.java1234.mappers.StudentMapper;
import com.java1234.model.Student;
import com.java1234.util.SqlSessionFactoryUtil;

public class StudentTest2 {

    private static Logger logger=Logger.getLogger(StudentTest2.class);
    private SqlSession sqlSession=null;
    private StudentMapper studentMapper=null;
    
    /**
     * 测试方法前调用
     * @throws Exception
     */
    @Before
    public void setUp() throws Exception {
        sqlSession=SqlSessionFactoryUtil.openSession();
        studentMapper=sqlSession.getMapper(StudentMapper.class);
    }

    /**
     * 测试方法后调用
     * @throws Exception
     */
    @After
    public void tearDown() throws Exception {
        sqlSession.close();
    }

    
    @Test
    public void testInsertStudent(){
        logger.info("添加学生");
        Student student=new Student();
        student.setName("张三4");
        student.setAge(14);
        student.setRemark("很长的本文...");
        byte []pic=null;
        try{
            File file=new File("c://boy.jpg");
            InputStream inputStream=new FileInputStream(file);
            pic=new byte[inputStream.available()];
            inputStream.read(pic);
            inputStream.close();
        }catch(Exception e){
            e.printStackTrace();
        }
        student.setPic(pic);
        studentMapper.insertStudent(student);
        sqlSession.commit();
    }
    
    @Test
    public void testGetStudentById(){
        logger.info("通过ID查找学生");
        Student student=studentMapper.getStudentById(4);
        System.out.println(student);
        byte []pic=student.getPic();
        try{
            File file=new File("d://boy2.jpg");
            OutputStream outputStream=new FileOutputStream(file);
            outputStream.write(pic);
            outputStream.close();
        }catch(Exception e){
            e.printStackTrace();
        }
    }
    
    @Test
    public void testSearchStudents6() {
        logger.info("添加学生(带条件)");
        List<Student> studentList=studentMapper.searchStudents6("%3%",12);
        for(Student student:studentList){
            System.out.println(student);
        }
    }
}

// \src\com\java1234\service\StudentTest3.java
package com.java1234.service;

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

import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import com.java1234.mappers.StudentMapper;
import com.java1234.model.Student;
import com.java1234.util.SqlSessionFactoryUtil;

public class StudentTest3 {

    private static Logger logger=Logger.getLogger(StudentTest3.class);
    private SqlSession sqlSession=null;
    private StudentMapper studentMapper=null;
    
    /**
     * 测试方法前调用
     * @throws Exception
     */
    @Before
    public void setUp() throws Exception {
        sqlSession=SqlSessionFactoryUtil.openSession();
        studentMapper=sqlSession.getMapper(StudentMapper.class);
    }

    /**
     * 测试方法后调用
     * @throws Exception
     */
    @After
    public void tearDown() throws Exception {
        sqlSession.close();
    }

    
    @Test
    public void testFindStudent(){
        logger.info("查询学生");
        int offset=0,limit=3;
        RowBounds rowBounds=new RowBounds(offset,limit);
        List<Student> studentList=studentMapper.findStudents(rowBounds);
        for(Student student:studentList){
            System.out.println(student);
        }
    }
    
    @Test
    public void testFindStudent2(){
        logger.info("查询学生");
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("start", 3);
        map.put("size", 3);
        List<Student> studentList=studentMapper.findStudents2(map);
        for(Student student:studentList){
            System.out.println(student);
        }
    }
    
    
}

// \src\com\java1234\util\SqlSessionFactoryUtil.java
package com.java1234.util;

import java.io.InputStream;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

public class SqlSessionFactoryUtil {

    private static SqlSessionFactory sqlSessionFactory;
    
    public static SqlSessionFactory getSqlSessionFactory(){
        if(sqlSessionFactory==null){
            InputStream inputStream=null;
            try{
                inputStream=Resources.getResourceAsStream("mybatis-config.xml");
                sqlSessionFactory=new SqlSessionFactoryBuilder().build(inputStream);
            }catch(Exception e){
                e.printStackTrace();
            }
        }
        return sqlSessionFactory;
    }
    
    public static SqlSession openSession(){
        return getSqlSessionFactory().openSession();
    }
}

 

posted on 2017-09-04 23:01  程序员修仙之路  阅读(152)  评论(0编辑  收藏  举报