MyBatis 教程02

<!-- \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();
    }
}
时间: 2024-10-27 01:29:36

MyBatis 教程02的相关文章

[转载]AngularJS入门教程02:AngularJS模板

是时候给这些网页来点动态特性了——用AngularJS!我们这里为后面要加入的控制器添加了一个测试. 一个应用的代码架构有很多种.对于AngularJS应用,我们鼓励使用模型-视图-控制器(MVC)模式解耦代码和分离关注点.考虑到这一点,我们用AngularJS来为我们的应用添加一些模型.视图和控制器. 请重置工作目录: git checkout -f step-2 我们的应用现在有了一个包含三部手机的列表. 步骤1和步骤2之间最重要的不同在下面列出.,你可以到GitHub去看完整的差别. 视图

Angular系列----AngularJS入门教程02:静态模板(转载)

为了说明angularJS如何增强了标准HTML,我们先将创建一个静态HTML页面模板,然后把这个静态HTML页面模板转换成能动态显示的AngularJS模板. 在本步骤中,我们往HTML页面中添加两个手机的基本信息,用以下命令将工作目录重置到步骤1. git checkout -f step-1 请编辑app/index.html文件,将下面的代码添加到index.html文件中,然后运行该应用查看效果. app/index.html <ul> <li> <span>

史上最简单的 MyBatis 教程

1 前言 MyBatis 源于 Apache 的一个开源项目 iBatis,而 iBatis 一词则来源于"internet"和"abatis"的组合,2010年这个项目由 Apache Software Foundation 迁移到了 Google Code,并且改名为MyBatis ,2013年11月其又迁移到 Github.MyBatis 是一个基于 Java 的支持普通 SQL 查询,存储过程和高级映射的优秀持久层框架,相比于基于面向对象使用 HQL 语言的

最简单的SpringBoot整合MyBatis教程

本文就来看看在Spring Boot中MyBatis要如何使用. 工程创建 首先创建一个基本的Spring Boot工程,添加Web依赖,MyBatis依赖以及MySQL驱动依赖,如下:最简单的SpringBoot整合MyBatis教程创建成功后,添加Druid依赖,并且锁定MySQL驱动版本,完整的依赖如下: <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-

Mybatis教程(一)

1      Mybatis教程(一) 学习过的持久层框架:DBUtils , Hibernate Mybatis就是类似于hibernate的orm持久层框架. 为什么学Mybatis? 目前最主流的持久层框架为hibernate与mybatis,而且国内目前情况使用Mybatis的公司比hibernate要多. Hibernate学习门槛不低,要精通门槛更高.门槛高在怎么设计O/R映射,在性能和对象模型之间如何权衡取得平衡,以及怎样用好Hibernate缓存与数据加载策略方面需要你的经验和能

MyBatis 教程01

<!-- \src\com\java1234\mappers\AddressMapper.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"&

MyBatis 教程03

<!-- \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"> <confi

MyBatis 教程05

<!-- \build\classes\applicationContext.xml --> <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" x

python入门基础教程02 Python简介

02 Python简介 Python简介 Python是一种解释型.面向对象.动态数据类型的高级程序设计语言,属于应用层软件.自从20 世纪90 年代初Python语言诞生至今,它逐渐被广泛应用于处理系统管理任务.自动化运维.图像处理游戏和Web 网站开发等领域.Python已经成为最受欢迎的程序设计语言之一.4.易读以及可扩展性,在国外用Python做科学计算的研究机构日益增多,一些知名大学已经采用Python教授程序设计课程.例如麻省理工学院的计算机科学及编程导论课程就使用Python语言讲