MyBatis

  • Post author:
  • Post category:其他




搭建MyBatis



查询

  1. 添加依赖包
<dependency>
	<groupId>org.mybatis</groupId>
	<artifactId>mybatis</artifactId>
	<version>3.4.6</version>
</dependency>
<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
	<version>5.1.40</version>
</dependency>
  1. 添加配置文件src/resources/config.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//com.mybatis.org//DTD Config 3.0//EN"
        "http://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/school"/>
                <property name="username" value="root"/>
                <property name="password" value=""/>
            </dataSource>
        </environment>
    </environments>
    <!-- 指定maper文件的路径(maven项目从resources源文件夹下找资源)-->
    <mappers>
        <mapper resource="StudentMapper.xml"/>
    </mappers>
</configuration>
  1. 创建实体类和接口类
  2. 添加mapper文件(mapper文件中储存sql语句)
<?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.mybatis.dao.StudentDao">

    <select id="findAll" resultType="com.mybatis.bean.Student">
        select * from student;
    </select>

</mapper>
  1. 测试类
package com.mybatis.Test;

import com.mybatis.bean.Student;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.Reader;
import java.util.List;

public class Test1 {
    public static void main(String[] args) {
        System.out.println("123");
        try{
        	//1.加载配置文件
            Reader reader = Resources.getResourceAsReader("MyBatis.xml");
            //创建sqlSessionFactoryBuilder对象
            SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
            //得到Session工厂对象
            SqlSessionFactory build = builder.build(reader);
            //得到Session
            SqlSession session = build.openSession();
            //调用sql语句
            List<Student> list = session.selectList("com.mybatis.dao.StudentDao.findAll");
            for (Student s : list) {
                System.out.println(s.toString());
            }
            reader.close();
            session.close();
        }catch(IOException e){
            e.printStackTrace();
        }

    }
}


单行多结果集


dao接口

public interface StudentDao {
    public List<Student> findAll();
    public int insert();
    public int insert2();
    public Map multipleFind();//单行多结果

}

测试类

public class Test1 {
    public static void main(String[] args) {
        System.out.println("123");
        try{
            Reader reader = Resources.getResourceAsReader("MyBatis.xml");
            SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
            SqlSessionFactory build = builder.build(reader);
            SqlSession session = build.openSession();
            Map map = session.selectOne("com.mybatis.dao.StudentDao.multipleFind");
            Set<Map.Entry> set = map.entrySet();
            for(Map.Entry s : set){
                System.out.println(s);

            }
            reader.close();
            session.close();
        }catch(IOException e){
            e.printStackTrace();
        }

    }
}

Mapper

  <select id="multipleFind" resultType="map">
        select max(SId) as max ,min(SId)as min,avg(SID) as avg from test;
    </select>



新增


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

    <select id="findAll" resultType="com.mybatis.bean.Student">
        select * from student;
    </select>
    <!--通过对象添加-->
    <insert id="insert" parameterType="com.mybatis.bean.Student" >
        insert into student (SId,Sname,Sage,Ssex)values(#{SId},#{Sname},#{Sage},#{Ssex})
    </insert>
    <!--通过Map集合添加-->
	<insert id="insert2" parameterType="com.mybatis.bean.Student" >
        insert into student (Sname,Sage,Ssex)values(#{Sname},#{Sage},#{Ssex})
    </insert>
</mapper>


dao接口

public interface StudentDao {
    public List<Student> findAll();
    public int insert(Student student);
    public int insert2(Map map);

}


测试类

public class Test1 {
    public static void main(String[] args) {
        System.out.println("123");
        try{
            Reader reader = Resources.getResourceAsReader("MyBatis.xml");
            SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
            SqlSessionFactory build = builder.build(reader);
            SqlSession session = build.openSession();
            //Student student = new Student("18","富贵",new Timestamp(new Date().getTime()),"男");//通过对象添加-创建对象		
            Map map = new Map();
            map.put("SName","长贵");
            map.put("SAge",new Timestamp(new Date().getTime()));
			map.put("SSex","男");
            //int result = session.insert("com.mybatis.dao.StudentDao.insert",student);//通过对象添加
            //int result = session.insert("com.mybatis.dao.StudentDao.insert2",map);//通过Map集合添加
            session.commit();
            System.out.println("result="+result);
            System.out.println(student.toString());
            reader.close();
            session.close();
        }catch(IOException e){
            e.printStackTrace();
        }

    }
}

在做查询时,如果需要将查询的结果和实体类属性自动对应的话,要求:属性名=列名

添加:session.insert(“namespace+id”[,传递给sql的参数值]);

修改:session.update(“namespace+id”[,传递给sql的参数值]);

删除:session.delete(“namespace+id”[,传递给sql的参数值]);

单行:session.selectOne(“namespace+id”[,传递给sql的参数值]);

多行:session.selectList(“namespace+id”[,传递给sql的参数值]);

处理多个聚合函数:使用map作为方法的返回值,默认key是列名

注意:增删改的时候需要提交事务

session.commit();

session.rollback();



省略实现类

Mybatis简化调用过程

Reader r=Resources.getResourceAsReader("mybatis.xml");
SqlSession session= new SqlSessionFactoryBuilder().build(r).openSession();
//参数是接口的class类
StudentDao dao=session.getMapper(StudentDao.class);
List<Student> list = dao.findAll();//查询所有学生



ThreadLocal处理sqlSession

ThreadLocal并非是一个线程的本地实现版本,它并不是一个Thread,而是threadlocalvariable(线程局部变量)。也许把它命名为ThreadLocalVar更加合适。线程局部变量(ThreadLocal)就是为每一个使用该变量的线程都提供一个变量值的副本,是Java中一种较为特殊的线程绑定机制,是每一个线程都可以独立地改变自己的副本,而不会和其它线程的副本冲突。

public class TestThread {
    private ThreadLocal<String> threadLocal=new ThreadLocal<String>();
    private List<String> list=new ArrayList<String>();
    class A extends  Thread{
        @Override
        public void run() {
           //存值
            System.out.println("A线程开始存值");
            threadLocal.set("thread内容");
            list.add("list内容");
            System.out.println("A---threadLocal="+threadLocal.get());
        }
    }
    class B extends  Thread{
        @Override
        public void run() {
            //  取值
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("B线程取数据");
            System.out.println("B---threadLocal="+threadLocal.get());
            System.out.println("list="+list.get(0));
        }
    }

    public static void main(String[] args) {
        TestThread testThread = new TestThread();
        TestThread.A a=testThread.new A();
        TestThread.B b=testThread.new B();
        a.start();
        b.start();
    }
}

结果

在这里插入图片描述

从上述结果可以看出ThreadLocal存值 对于不同线程提供变量值的副本 而普通的存值方式会导致变量的共享



ThreadLocal 工具类

getSession采用单例模式进行优化

public class SqlSessionUtil {
    private static ThreadLocal<SqlSession>threadLocal=new ThreadLocal<SqlSession>();
    private static SqlSessionFactory sqlSessionFactory;

    static {
        try {
            Reader resourceAsReader = Resources.getResourceAsReader("mybatis.xml");
            sqlSessionFactory= new SqlSessionFactoryBuilder().build(resourceAsReader,"a2");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static SqlSession getSession(){
        SqlSession session = threadLocal.get();//采用单例模式进行优化
        if(session==null){
            session = sqlSessionFactory.openSession();
            threadLocal.set(session);
        }
        return session;
    }
    public static void closeSession(){
        SqlSession session = threadLocal.get();
        if(session!=null){
            session.close();
            threadLocal.remove();
        }
    }

}



自定义类名

方法一:直接给实体类添加别名

<!—自定义实体类名 -->
<typeAliases>
	<typeAlias alias="u" type="com.mybatis.bean.Users"></typeAlias>
	<!--指定哪些包的类可以使用别名,默认别名:类名首字母小写(实际使用的时候,全部小写也可以做结果映射) -->
	<package name="bean"></package>
</typeAliases>

方法二:给包下的所有实体类添加别名(实体类原名的首字母小写)

<!—自定义实体类名 -->
<typeAliases>

	<!--指定哪些包的类可以使用别名,默认别名:类名首字母小写(实际使用的时候,全部小写也可以做结果映射) -->
	<package name="com.mybatis.bean"></package>
</typeAliases>



获得新增数据自增主键

适用于可以自增的主键列上

<insert useGeneratedKeys="true" keyProperty="userid">



Log4j日志

在控制台显示sql语句

  1. 添加jar包
<dependency>
	<groupId>org.slf4j</groupId>
	<artifactId>slf4j-api</artifactId>
	<version>1.7.5</version>
</dependency>
<dependency>
	<groupId>org.slf4j</groupId>
	<artifactId>slf4j-log4j12</artifactId>
	<version>1.7.12</version>
</dependency>
<dependency>
	<groupId>log4j</groupId>
	<artifactId>log4j</artifactId>
	<version>1.2.17</version>
</dependency>
  1. 配置log4j.properties文件

log4j.rootLogger=DEBUG, Console

log4j.appender.Console=org.apache.log4j.ConsoleAppender

log4j.appender.Console.layout=org.apache.log4j.PatternLayout

log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] – %m%n

log4j.logger.java.sql.ResultSet=INFO

log4j.logger.org.apache=INFO

log4j.logger.java.sql.Connection=DEBUG

log4j.logger.java.sql.Statement=DEBUG

log4j.logger.java.sql.PreparedStatement=DEBUG

在这里插入图片描述



复杂查询



in查询

foreach标签中属性说明:

item 表示集合中每一个元素进行迭代时的别名,等同于c 标签中的var

index 指定一个名字,用于表示在迭代过程中,每次迭代到的位置,可以不写

open 表示该语句以什么开始,

separator 表示在每次进行迭代之间以什么符号作为分隔符,

close 表示以什么结束。

注意:在使用foreach 的时候最关键的也是最容易出错的就是collection 属性,

collection该属性是必须指定的

list 时取值list,数组时取值array,map 时取值map 的key 值。


Dao

package com.mybatis.dao;

import com.mybatis.bean.Student;

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

public interface StudentDao2 {
    public List<Student> findAll1(List list);
    public List<Student> findAll2(int[] list);
    public List<Student> findAll3(Map map);

}


StudentMapper2.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.mybatis.dao.StudentDao2">

<!--    通过list集合进行复杂查询-->
    <select id="findAll1" resultType="Student">
        select * from student where SId in 
        <foreach collection="list" index="i" item="sid" open="(" separator="," close=")">
            #{sid}
        </foreach>
    </select>
    <!--    通过数组进行复杂查询-->
    <select id="findAll2" resultType="Student">
        select * from student where SId in
        <foreach collection="array" index="i" item="sid" open="(" separator="," close=")">
        #{sid}
        </foreach>
    </select>
    <!--    通过Map集合进行复杂查询-->
    <select id="findAll3" resultType="Student">
        select * from student where SId in
        <foreach collection="ids" index="i" item="sid" open="(" separator="," close=")">
            #{sid}
        </foreach>
    </select>


</mapper>


测试类

public class Test2 {
    public static void main(String[] args) {
        SqlSession session = SqlSessionUtil.getSession();
        StudentDao2 studentDao2 = session.getMapper(StudentDao2.class);
        //通过list集合进行复杂查询
        List list = new ArrayList();
        list.add(1);
        list.add(3);
        list.add(5);
        list.add(7);
//         List<Student> students=  studentDao2.findAll1(list);
        //通过数组进行复杂查询
//        int[] list =new int[]{1,3,5,7};
//        List<Student> students = studentDao2.findAll2(list);
        //通过map集合进行复杂查询
        Map map = new HashMap();
        map.put("ids",list);
        List<Student> students = studentDao2.findAll3(map);
        for (Student s :students){
            System.out.println(s);
        }
        SqlSessionUtil.closeSession();
    }
}



模糊查询 动态SQL

<mapper>
<!--    通过Map集合进行模糊查询-->
    <select id ="findAll4" resultType="Student">
        select * from student where 1=1
        <if test="Sname!=null and Sname!=''">
            and Sname like "%"#{Sname}"%"
        </if>
        <if test="Ssex !=null and Ssex !=''">
            and Ssex =#{Ssex}
        </if>
    </select>
</mapper>

测试类

public class TestLike {
    public static void main(String[] args) {
        SqlSession session = SqlSessionUtil.getSession();
        StudentDao2 studentDao2 = session.getMapper(StudentDao2.class);
        Map map = new HashMap();
        map.put("Sname","贵");
        map.put("Ssex","男");
        List<Student> students =  studentDao2.findAll4(map);
        for(Student s:students){
            System.out.println(s);
        }

    }
}


注意:


当使用Map集合进行模糊查询时,test后参数对应map 的键

而使用对象进行模糊查询时,test后参数对应对象的属性


通过Map集合对一个区间进行查询

    <!--    通过Map集合进行区间模糊查询1-->
    <select id="findAll6" resultType="Student">
        select * from Student where SId between #{begin} and #{end}
    </select>
    <!--    通过Map集合进行区间模糊查询2-->
    <select id="findAll7" resultType="Student">
        select * from Student where SId <![CDATA[>=]]>#{begin} and SId <![CDATA[ <= ]]> #{end}
    </select>

<![CDATA[符号]]> 防止特殊符号进行编译


通过resultMap解决对象属性名与字段名不一致造成的映射问题

<resultMap id="map1" type="Student">
        <result property="address" column="stuAddress"></result>
</resultMap>
    <select id="findAll" resultMap="map1">
        select * from student;
    </select>



多表查询


一对多


一对多关系中,首先分辨两表之间的关系,哪个是一,哪个是多。

在一的类中,创建多的类集合

例如在年级的类中创建一个学生集合。

Mapper.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.mybatis.dao.GradeDao">
	<!--配置映射关系-->
    <resultMap id="b1" type="com.mybatis.bean.Grade">
    	<!--对于该表的主键用id,其他字段用result-->
        <id column="gid" property="gid"></id>
        <result column="gname" property="gname"></result>
        <!--集合用collection,ofType定义集合内元素类型-->
        <collection property="studentList" ofType="com.mybatis.bean.Student">
            <id property="SId" column="SId"></id>
            <result property="Sname" column="Sname"></result>
            <result property="Sage" column="Sage"></result>
            <result property="Ssex" column="Ssex"></result>
            <result property="gid" column="gid"></result>
        </collection>

    </resultMap>
    <select id="findByGradeid" resultMap="b1">
        select * from student s ,grade g where s.gid=g.gid and s.gid=#{gid};
    </select>

</mapper>


多对一


在多方的类中创建一方的对象

Mapper.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.mybatis.dao.GradeDao">
	<!--配置映射关系-->
    <resultMap id="b2" type="com.mybatis.bean.Student">
    	<!--对于该表的主键用id,其他字段用result-->
        <id property="SId" column="SId"></id>
        <result property="Sname" column="Sname"></result>
        <result property="Sage" column="Sage"></result>
        <result property="Ssex" column="Ssex"></result>
        <result property="gid" column="gid"></result>
        <!--关联表用association,javaType定义关联表类型-->
        <association property="grade" javaType="com.mybatis.bean.Grade">
        	<id column="gid" property="gid"></id>
        	<result column="gname" property="gname"></result>
            
        </collection>

    </resultMap>
    <select id="findAllStudent" resultMap="b2">
        select * from student s ,grade g where s.gid=g.gid ;
    </select>

</mapper>


一对一


在两个类中创建另一个类的对象

Mapper.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.mybatis.dao.WifeDao">
    <resultMap id="rs1" type="com.mybatis.bean.Husband">
        <id property="husId" column="husId"></id>
        <result property="husName" column="husName"></result>
        <association property="wife" javaType="com.mybatis.bean.Wife">
            <id property="wifeId" column="wifeId"></id>
            <result property="wifeName" column="wifeName"></result>
        </association>

    </resultMap>

    <resultMap id="rs2" type="com.mybatis.bean.Wife">
        <id property="wifeId" column="wifeId"></id>
        <result property="wifeName" column="wifeName"></result>
        <association property="husband" javaType="com.mybatis.bean.Husband">
            <id property="husId" column="husId"></id>
            <result property="husName" column="husName"></result>
        </association>
    </resultMap>



    <select id="findByhusId" resultMap="rs2">
  select * from wife w join husband h
    on  w.wifeid=h.wifeid where h.husid=#{husid}
    </select>



pageHelper分页



1.内存分页

内存分页

通过RowBounds对对象进行分页,针对ResultSet结果集执行的内存分页

优缺点:

物理分页每次都要访问数据库,逻辑分页只访问一次

物理分页占用内存少,逻辑分页相对较多

物理分页数据每次都是最新的,逻辑分页有可能滞后

List<Student> list = session.selectList("com.mybatis.dao.StudentDao.findAll",null,new RowBounds(0,3));//RowBounds(从第几条开始(以0为初始值),显示几条)
for (Student s : list) {
   System.out.println(s.toString());
}



2.物理分页

分页插件的基本原理是使用Mybatis提供的插件接口,实现自定义插件,在插件的拦截方法内拦截待执行的sql,然后重写sql,根据dialect方言,添加对应的物理分页语句和物理分页参数。


导入依赖包

<dependency>
   <groupId>com.github.pagehelper</groupId>
   <artifactId>pagehelper</artifactId>
   <version>5.1.6</version>
</dependency>


Mybatis.xml 引用分页插件

<plugins>
        <plugin interceptor="com.github.pagehelper.PageInterceptor"></plugin>
</plugins>


测试类

            PageHelper.startPage(6,3);//指定物理分页参数
            List<Student> list = session.selectList("com.mybatis.dao.StudentDao.findAll");
            PageInfo<Student>info = new PageInfo<Student>(list);
            for (Student s : info.getList()) {
                System.out.println(s.toString());
            }
            System.out.println("总页数"+info.getPages());
            System.out.println("总条数"+info.getTotal());
            System.out.println("当前页"+info.getPageNum());
            System.out.println("当前条数"+info.getSize());
            System.out.println("上一页"+info.getPrePage());
            System.out.println("下一页"+info.getNextPage());
            System.out.println("显示条数"+info.getPageSize());



缓存

减少同一条sql语句对数据库的访问次数

前提在同一个 SqlSessionFactory对象,同一个Mapper文件中。


一级缓存:


在同一个session中,对于同样的sql语句,会自动进行缓存


二级缓存:


从不同的缓存中共享数据 通过SqlSessionFactory手动开启

映射配置文件StudentMapper.xml

<mapper namespace="com.mybatis.dao.StudentDao">
	<cache eviction="FIFO"	flushInterval="60000"	size="512" readOnly="true"/>
	
</mapper>

eviction:二级缓存 ,缓存对象向从缓存中移除的策略,遵循先进先出

flushInterval:刷新缓存的建个时间

size:缓存对象个数

readOnly:是否只读

使用二级缓存时,查询结果映射的java对象必须实现java.Serializable接口的序列化和反序列化操作



注解操作

向配置文件添加扫描注解的位置

<mapper class="com.mybatis.dao.StudentDao"></mapper>



注解实现增删改查

public interface StudentDao {

    @Select("select * from Student")
    public List<Student> findall();
    @Select("select * from Student where sid=#{sid}")
    public Student findById();
    @Insert("Insert into Student values(null,#{Sname},#{Sage},#{Ssex},#{gid})")
    @Options(useGeneratedKeys=true,keyProperty="SId")
    public int insert(Student student);
    @Update("update Student set Sname=#{Sname},Sage=#{Sage},Ssex=#{Ssex},gid=#{gid} where Sid=#Sid")
    public int update(Student student);
    @Delete("delete from Student where SId=#{SId}")
    public int delete(int sid);
    @Select("select max(SId) as max,min(SId) as min,avg(SId) as avg from Student")
    public Map count();


}


测试类

public class Test1 {
    public static void main(String[] args) {
       SqlSession session =  SqlSessionUtil.getSession();
       StudentDao2 studentDao = session.getMapper(StudentDao2.class);
       //-----计数----
//        Map map = studentDao.count();
//        Set<Map.Entry> set = map.entrySet();
//        for (Map.Entry m: set) {
//            System.out.println(m);
//
//        }
       //-----查询所有学生---
        List<Student> list = studentDao.findall();
        for (Student s:list) {
            System.out.println(s.toString());

        }
//        for (Student s:list) {
//            System.out.println(s.toString()+s.getGrade().getGname());
//
//        }

        //-----新增学生(部分信息)----
//        studentDao.insert2("voker","男",2);
//        session.commit();
       //-----新增学生----
//       Student student = new Student();
//       student.setSname("Naix");
//       student.setSage(new Timestamp(new Date().getTime()));
//       student.setSsex("男");
//       student.setGid(3);
//       int result = studentDao.insert(student);
//       session.commit();
//        System.out.println("插入结果"+result+",新增的学生的ID是"+student.getSId());
        SqlSessionUtil.closeSession();



    }


当类名和属性名不一致


使用注解@Resulits()

@Select("select * from student")
/* @Results({
@Result(id = true, property = "id", column = "test_id")
@Result(column = "username",property = "user_name")
})*/



AOP的思想 通过反射将所有sql放入一个类中

用来定义sql语句的sqlUtil.java

返回值一定很是字符串

public class SqlUtil {
    public String findAll(){
        return "select * from Student";
    }
    public String findById(){
        return "select * from Student where sid=#{sid}";
    }
    public String insert(){
        return "Insert into Student values(null,#{Sname},#{Sage},#{Ssex},#{gid})";
    }
    public String update(){
        return "update Student set Sname=#{Sname},Sage=#{Sage},Ssex=#{Ssex},gid=#{gid} where Sid=#Sid";
    }
    public String delete(){
        return "delete from Student where SId=#{SId}";
    }
    public String count(){
        return "select max(SId) as max,min(SId) as min,avg(SId) as avg from Student";
    }
}

Dao类

public interface StudentDao2 {
    @Options(useCache = true,flushCache=Options.FlushCachePolicy.FALSE,timeout =9999999)
    @SelectProvider(type= SqlUtil.class,method="findAll")
    public List<Student> findall();
    @SelectProvider(type=SqlUtil.class,method="findById")
    public Student findById();
    @InsertProvider(type=SqlUtil.class,method="insert")
    @Options(useGeneratedKeys=true,keyProperty="SId")
    public int insert(Student student);
    @UpdateProvider(type=SqlUtil.class,method="update")
    public int update(Student student);
    @DeleteProvider(type=SqlUtil.class,method="delete")
    public int delete(int sid);
    @SelectProvider(type=SqlUtil.class,method="count")
    public Map count();
}



两表联查

Dao

//两表联查
    //查询所有学生以及其班级信息
    @ResultMap("com.xzk.dao.StudentDao2.rs3")
    @Select("select * from student s,grade g where s.gradeid=g.gid")
    public List<Student> getAllStudent();

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.mybatis.dao.StudentDao2">
    <resultMap id="rs7" type="com.mybatis.bean.Student">
        <id property="SId" column="SId"></id>
        <result property="Sname" column="Sname"></result>
        <result property="Sage" column="Sage"></result>
        <result property="Ssex" column="Ssex"></result>
        <result property="gid" column="gid"></result>
        <association property="grade" javaType="com.mybatis.bean.Grade">
            <id column="gid" property="gid"></id>
            <result column="gname" property="gname"></result>
        </association>
    </resultMap>


</mapper>



注解实现参数绑定

当sql语句不在使用对象进行添加或者更新时

@Insert("insert into Student(SId,Sname,Ssex,gid) values(null,#{Sname},#{Ssex},#{gid})")
@Options(useGeneratedKeys = true,keyProperty = "SId")
 public int insert2(@Param("Sname") String name,@Param("Ssex") String gender,@Param("gid") int gid);



注解实现二级缓存

Dao类添加注解@CacheNamespace

需要缓存的方法前添加注解@Options

@CacheNamespace
public interface StudentDao2 {
    @Options(useCache = true,flushCache=Options.FlushCachePolicy.FALSE,timeout =9999999)
    @SelectProvider(type= SqlUtil.class,method="findAll")
    public List<Student> findall();
}



注解实现动态查询

与在xml文件内相似,不同在于在java代码里,sql语句还有< if >标签,sql语句需要包含在< script >标签内,需要反编译



MyBatis自动化


依赖包

<dependency>
	<groupId>org.mybatis.generator</groupId>
	<artifactId>mybatis-generator-core</artifactId>
	<version>1.3.5</version>
</dependency>


加载插件

<build>
        <plugins>
            <plugin>
                <groupId>org.mybatis.generator</groupId>
                <artifactId>mybatis-generator-maven-plugin</artifactId>
                <version>1.3.5</version>
                <configuration>
                    <!--配置文件的路径-->
                    <configurationFile>src/main/resources/generatorConfig.xml</configurationFile>
                    <overwrite>true</overwrite>
                </configuration>
                <dependencies>
                    <dependency>
                        <groupId>org.mybatis.generator</groupId>
                        <artifactId>mybatis-generator-core</artifactId>
                        <version>1.3.5</version>
                    </dependency>
                </dependencies>
            </plugin>
        </plugins>
    </build>


修改配置文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
	PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
	"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<!-- 配置生成器 -->
<generatorConfiguration>
<!--数据库驱动jar -->
<classPathEntry
        location="C:\Users\Administrator\.m2\repository\mysql\mysql-connector-java\mysql-connector-java-5.1.46.jar" />
<context id="MyBatis" targetRuntime="MyBatis3">
    <!--去除注释 -->
    <commentGenerator>
        <property name="suppressAllComments" value="true" />
    </commentGenerator>
    <!--数据库连接 -->
    <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                    connectionURL="jdbc:mysql://localhost:3306/school"
                    userId="root"
                    password="">
    </jdbcConnection>
    <!--生成实体类 指定包名 以及生成的地址 (可以自定义地址,但是路径不存在不会自动创建
    使用Maven生成在target目录下,会自动创建) -->
    <javaModelGenerator targetPackage="com.mybatis.bean"
                        targetProject="C:\Users\Administrator\Desktop\Project\MyBatis_Annotation">
        <property name="trimStrings" value="true" />
    </javaModelGenerator>
    <!--生成SQLmapper文件 -->
    <sqlMapGenerator targetPackage="mapper"
                     targetProject="C:\Users\Administrator\Desktop\Project\MyBatis_Annotation\src\main\resources">
    </sqlMapGenerator>
    <!--生成Dao文件,生成接口 -->
    <javaClientGenerator type="XMLMAPPER"
                         targetPackage="com.mybatis.dao"
                         targetProject="C:\Users\Administrator\Desktop\Project\MyBatis_Annotation\src\main\java">
    </javaClientGenerator>
    <table tableName="student" enableCountByExample="false"
           enableUpdateByExample="false" enableDeleteByExample="false"
           enableSelectByExample="false" selectByExampleQueryId="false">
    </table>
    <table tableName="grade" enableCountByExample="false"
           enableUpdateByExample="false" enableDeleteByExample="false"
           enableSelectByExample="false" selectByExampleQueryId="false">
    </table>
    <table tableName="subject" enableCountByExample="false"
           enableUpdateByExample="false" enableDeleteByExample="false"
           enableSelectByExample="false" selectByExampleQueryId="false">
    </table>
</context>
</generatorConfiguration>

maven Project选项卡->plugins->mybatis-generator-core,自动生成

如失败,删除生成代码后再次尝试



版权声明:本文为Just__2009原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。