1. 程式人生 > >關於mybatis+maven基本知識掌握總結

關於mybatis+maven基本知識掌握總結

首先這次學習mybatis,得先下載idea軟體。maven在idea上好操作點,破解方案自行百度。這裡暫不詳細介紹。

當然學習mybatis框架需要一定基礎,對於jdbc+mysql底層實現有一定認識,這裡就不在講解。

mybatis還是很簡單的,網上教程一大堆,很可能你看一堆都比我的寫得好。對於三天對mybatis的學習,在這裡對知識點寫下一個總結,不然後面硬碟壞了,又沒了。

連結:https://pan.baidu.com/s/1qp44GPp7xgCFjr_y9jcnXw    提取碼:kecl 
對於mybatis。ssh框架不能寫sql,但是後期不能優化,ssm框架可以優化sql,對於效能好一些。

  • 簡單mybatis

 這是最初的練習,可能註釋有問題,但是後面的程式碼就糾正過來了。

為了更好的xml分離,就建立了一個資料夾,然後轉成編譯包,在再下面建立相同的mapper包。

package org.lisonglin.entity;

public class Student {
    private int id;
    private String name;
    private int age;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Student(int id, String name, int age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

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

    public Student() {
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
<?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>
    <settings>
        <!-- 對資料庫與屬性不一致,自動轉換 -->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
        <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/stus"/>
                <property name="username" value="root"/>
                <property name="password" value="123"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <!-- 呼叫dao層 -->
        <mapper resource="org/lisonglin/mapper/StudentMapper.xml"/>
    </mappers>
</configuration>
package org.lisonglin.mapper;

import org.apache.ibatis.annotations.Param;
import org.lisonglin.entity.Student;

public interface StudentMapper {
    Student get(int id);
    void insert(Student stu);
    void insertInfo(@Param("name") String name, @Param("age") int age);
}
<?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="org.lisonglin.mapper.StudentMapper">
    <select id="get" resultType="org.lisonglin.entity.Student">
        select * from student where id=#{id}
    </select>
    <insert id="insert">
        insert into student values(null,#{name},#{age})
    </insert>
    <insert id="insertInfo">
        insert into student values(null,#{name},#{age})
    </insert>
</mapper>
package org.lisonglin.test;

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 org.junit.Test;
import org.lisonglin.entity.Student;
import org.lisonglin.mapper.StudentMapper;

import java.io.IOException;
import java.io.InputStream;


public class TestMyBatis {

    @Test
    public void test(){
        InputStream is=null;
        try {
            //獲取src下全域性配置檔案的輸入流
            is = Resources.getResourceAsStream("mybatis-config.xml");
            //獲取SqlSessionFactory物件
            SqlSessionFactory factory =new SqlSessionFactoryBuilder().build(is);
            SqlSession sqlSession = factory.openSession();
            StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
//            Student student = mapper.get(1);
//            System.out.print(student);
//            Student s=new Student();
//            s.setName("bb");
//            s.setAge(12);
//            mapper.insert(s);
            mapper.insertInfo("cc",13);
            //手動提交
            sqlSession.commit();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}
  • 進一步學習mybatis

其中有原生DAO的寫法,用於理清mybatis的實現思路,還有就是因為老師說註解方式耦合性不高,就沒有繼續完成相應功能。不多說看下面程式碼。

package org.lisonglin.entity;

public class Student {
    private int id;
    private String sName;
    private int age;
    public final static String MYBATIS_CONFIG_FILE="mybatis-config2.xml";

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getsName() {
        return sName;
    }

    public void setsName(String sName) {
        this.sName = sName;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "id=" + id +
                ", sName='" + sName + '\'' +
                ", age=" + age +
                '}';
    }

    public Student(int id, String sName, int age) {
        this.id = id;
        this.sName = sName;
        this.age = age;
    }


    public Student() {
    }
}

 

<?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"></properties>
    <settings>
        <!--把資料中的下劃線改為駝峰命名法-->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
    <typeAliases>
        <!-- 別名 -->
        <!--<typeAlias type="org.lisonglin.entity.Student" alias="Student"></typeAlias>-->
        <!-- 直接導包 -->
        <package name="org.lisonglin.entity"></package>
    </typeAliases>
    <!-- 配置壞境變數,可以配置多個,預設值與id一致 -->
   <environments default="development">
       <environment id="development">
           <transactionManager type="JDBC"></transactionManager><!--事務-->
           <dataSource type="POOLED"><!-- 資料來源  連線池POOLED -->
               <property name="driver" value="${jdbc.driver}"/>
               <property name="url" value="${jdbc.url}"/>
               <property name="username" value="${jdbc.username}"/>
               <property name="password" value="${jdbc.password}"/>
           </dataSource>
       </environment>
   </environments>
    <!--配置對映檔案-->
    <mappers>
        <!--基於XML配置檔案-->
        <!--<mapper resource="org/lisonglin/mapper/StudentMapper.xml"/>-->
        <package name="org.lisonglin.mapper"></package>
    </mappers>
</configuration>
package org.lisonglin.mapper;

import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.lisonglin.entity.Student;

import java.util.List;

public interface StudentMapper {
    /**
     * XML配置方式
     * @param id
     * @return
     */
    Student get(int id);
    void insert(Student stu);
    void insertInfo(@Param("name") String name, @Param("age") int age);
    List<Student> getAll();
    int insertStudentCacheId(Student stu);
    List<Student> getByName(@Param("key") String key);
    List<Student> getByIds(@Param("ids") int ... ids);
    List<Student> getStudents(Student stu);
    /**
     * 註解方式(程式碼耦合性不高,不推薦)
     * @param stu
     * @return
     */
    @Select("insert into stu(id,s_name,age) values(null,#{name},#{age})")
    public int add(Student stu);
}

 

<?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="org.lisonglin.mapper.StudentMapper">
    <!-- 通用sql -->
    <sql id="selectInfo">
        select * from stu
    </sql>
    <select id="getById" resultType="Student" parameterType="int">
        <!-- 引入通用sql -->
       <include refid="selectInfo"></include>
       where id=#{id}
    </select>
    <select id="getStudents" resultType="Student">
        <include refid="selectInfo"></include>
        <!-- 條件查詢,如果沒有符合條件,那麼sql中的and會自動去掉 -->
        <where>
            <!-- 判斷中屬性是bean中的命名 -->
            <if test="sName != null">
                and s_name = #{sName}
            </if>
            <if test="age!=0">
                and age = #{age}
            </if>
        </where>
    </select>
    <select id="getByIds" resultType="Student">
        <include refid="selectInfo"></include>
        <where>
            <!--<foreach collection="ids" open="id in (" close=")" separator="," item="id">-->
                <!--id=#{id}-->
            <!--</foreach>-->
            <foreach collection="ids" item="id" separator="or">
                id=#{id}
            </foreach>
        </where>
    </select>
    <select id="get" resultType="Student" parameterType="int">
        select * from stu where id=#{id}
    </select>
    <insert id="insert">
        insert into stu values(null,#{name},#{age})
    </insert>
    <insert id="insertInfo">
        insert into stu values(null,#{name},#{age})
    </insert>
    <select id="getAll" resultType="Student">
        select * from stu
    </select>
    <!-- 查詢出增加的主鍵(方法一) -->
    <insert id="insertStudentCacheId" keyColumn="id" keyProperty="id" useGeneratedKeys="true">
        insert into stu values(null,#{sName},#{age})
    </insert>
    <!-- 方法二 -->
    <insert id="insertStudentId">
          <selectKey keyProperty="id" keyColumn="id" order="AFTER" resultType="int">
              <!-- 查詢自增id (方法一) -->
              select last_insert_id()
              <!--方法二-->
              <!--select @@identity-->
          </selectKey>
         insert into stu values(null,#{sName},#{age})
    </insert>
    <select id="getByName" resultType="Student">
        <!-- ${} 拼接sql #{}  佔位符 -->
        <!-- 推薦使用這種 -->
        <!-- select * from stu where s_name like '%' #{key} '%' -->
        <bind name="new_key" value="'%'+key+'%'"></bind>
        <include refid="selectInfo"></include>
        where s_name like #{new_key}
        <!-- select * from stu where s_name like concat('%',#{key},'%') -->
        <!-- 這種不建議使用,這種使用statement查詢方式,有sql注入風險 -->
        <!-- select * from stu where s_name like '%${key}%' -->
    </select>

</mapper>
package org.lisonglin.servlet;

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 org.lisonglin.entity.Student;
import org.lisonglin.mapper.StudentMapper;

import java.io.IOException;
import java.io.InputStream;

public class DataUtil {
    private static SqlSessionFactory sqlSessionFactory;

    public static StudentMapper getStudentMapper(){
        InputStream is=null;
        try {
            is = Resources.getResourceAsStream("mybatis-config.xml");
            SqlSessionFactory build = new SqlSessionFactoryBuilder().build(is);
            SqlSession sqlSession = build.openSession();
            StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
            return  mapper;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return  null;
    }

    public static SqlSessionFactory getSqlSessionFactory(){
        InputStream is=DataUtil.class.getClassLoader().getResourceAsStream(Student.MYBATIS_CONFIG_FILE);
        return new SqlSessionFactoryBuilder().build(is);
    }

    /**
     * @param autoCommit
     *      true:表示建立的SqlSession物件在執行完SQL之後自動提交事務
     *      false:表示建立的SqlSession物件在執行完SQL之後不會自動提交事務,這時就需要我們手動呼叫SqlSession.commit()提交事務
     * @return
     */
    public static SqlSession getSqlSession(boolean autoCommit){
        return getSqlSessionFactory().openSession(autoCommit);
    }

    public static SqlSession getSqlSession(){
        return getSqlSessionFactory().openSession();
    }

}

 

package org.lisonglin.test;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import org.lisonglin.dao.StudentImpl;
import org.lisonglin.entity.Student;
import org.lisonglin.mapper.StudentMapper;
import org.lisonglin.servlet.DataUtil;

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

public class MyTest {
    private SqlSessionFactory sqlSessionFactory;

    @Test
    public void getStudentByAgeOrNames(){
        StudentMapper studentMapper = DataUtil.getStudentMapper();
        Student student=new Student();
        student.setAge(20);
        System.out.println(student.toString());
        List<Student> studentByAgeOrName = studentMapper.getStudents(student);
        System.out.println(studentByAgeOrName);
    }

    @Test
    public void getByIdsStudent(){
        StudentMapper studentMapper = DataUtil.getStudentMapper();
        List<Student> byIds = studentMapper.getByIds(1, 2, 3);
        System.out.println(byIds);
    }

    @Test
    public void getByNameStu(){
        StudentMapper studentMapper = DataUtil.getStudentMapper();
        List<Student> a = studentMapper.getByName("a");
        System.out.println(a);
    }

    @Test
    public void getMapperAll(){
        StudentMapper sqlSession = DataUtil.getStudentMapper();
        List<Student> all = sqlSession.getAll();
        System.out.print(all.toString());
    }

    /**
     * mybatis代理模式
     */
    @Test
    public void getMapperMybatis(){
        StudentMapper sqlSession = DataUtil.getStudentMapper();
        Student student = sqlSession.get(1);
        System.out.print(student);
    }

    @Test
    public void insertGetId(){
        StudentMapper studentMapper = DataUtil.getStudentMapper();
        Student stu=new Student();
        stu.setAge(12);
        stu.setsName("aaa");
        int i = studentMapper.insertStudentCacheId(stu);
        System.out.println(i);
        System.out.println(stu.getId());
    }

    /**
     * 原生Dao開發
     */
    @Test
    public void getDaoMyBatis(){
        String resource = "mybatis-config.xml";
        Reader reader = null;
        try {
            reader = Resources.getResourceAsReader(resource);
        } catch (IOException e) {
            e.printStackTrace();
        }
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        StudentMapper studentMapper=new StudentImpl(sqlSessionFactory);
        Student student = studentMapper.get(2);
        System.out.print(student);
    }
}

 

  • 完整mybatis學習

這在最後是maven+mybatis,其中有自動生成generatorConfig外掛,不過這個後面用熟悉了再用這個外掛吧。

還有log4j日誌列印,一級快取和二級快取,資料庫多表連線,一對一對映和一對多對映。還有一個懶載入,分頁

pagehelper的使用。

首先maven對jar包有一個相當於中央倉庫的作用,減少專案的沒用的東西,因為我們寫的以前專案,很多東西其實只有一點點,而其他檔案佔比相當大,maven的好處就是把jar包放在一個資料夾下,用的時候就匯出來用。

maven專案建立太晚就不寫了,自行百度把。

groupId:相當於專案別名把
artifactId:專案名
dependencies:配置jar包

在pom.xml中寫相關jar包的xml配置,在這個網站搜尋https://mvnrepository.com/

複製到pom.xml的

在ssm下建立一個web專案,相當於一個版塊,然後在點選右鍵設定Add Framework .....新增pom.xml,然後在這個pom.xml中新增

<dependency>
    <groupId>java</groupId>
    <artifactId>ssm</artifactId>
    <version>1.0-SNAPSHOT</version>
</dependency>

相對你的總專案的名字,在artifactId中新增ssm後,它會自動新增。

dependencies標籤對裡,它會自動下載jar包。
package org.lisonglin.entity;

import java.io.Serializable;
import java.util.List;

public class Teacher implements Serializable {
    private int id;
    private String name;
    private int age;
    private Wifes wife;
    private List<User> user;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public Wifes getWife() {
        return wife;
    }

    public void setWife(Wifes wife) {
        this.wife = wife;
    }

    public List<User> getUser() {
        return user;
    }

    public void setUser(List<User> user) {
        this.user = user;
    }

    @Override
    public String toString() {
        return "Teacher{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", wife=" + wife +
                ", user=" + user +
                '}';
    }
}
package org.lisonglin.entity;

import java.io.Serializable;

public class User implements Serializable {
    private int id;
    private String name;
    private int age;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
package org.lisonglin.entity;

import java.io.Serializable;

public class Wifes implements Serializable {
    private int id;
    private String name;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Wifes{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}
package org.lisonglin.util;

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 org.lisonglin.mapper.UserMapper;

import java.io.IOException;
import java.io.InputStream;

public class MyBatis {
    public static SqlSession getSqlSession(){
        try {
            InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
            SqlSession sqlSession = sqlSessionFactory.openSession();
            return sqlSession;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
<?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"></properties>
    <settings>
        <!--把資料中的下劃線改為駝峰命名法-->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
        <!--二級快取開關-->
        <setting name="cacheEnabled" value="true"></setting>
        <!--允許返回多個結果集-->
        <setting name="multipleResultSetsEnabled" value="true"></setting>
        <!--日誌-->
        <setting name="logImpl" value="LOG4J"></setting>
        <!-- 延遲載入總開關 -->
        <setting name="lazyLoadingEnabled" value="false"/>
        <!-- 侵入懶載入,設定為false則按需載入,否則會全部載入 -->
        <setting name="aggressiveLazyLoading" value="false"/>
    </settings>
    <typeAliases>
        <!-- 別名 -->
        <!--<typeAlias type="org.lisonglin.entity.Student" alias="Student"></typeAlias>-->
        <!-- 直接導包 -->
        <package name="org.lisonglin.entity"></package>
    </typeAliases>
    <!-- 配置分頁外掛 -->
    <plugins>
        <!-- com.github.pagehelper為PageHelper類所在包名 -->
        <plugin interceptor="com.github.pagehelper.PageInterceptor">
            <!--&lt;!&ndash; 設定方言 &ndash;&gt;-->
            <!--<property name="dialect" value="mysql"/>-->
            <!--&lt;!&ndash;設定為true時,使用RowBounds分頁會進行count查詢 &ndash;&gt;-->
            <!--<property name="offsetAsPageNum" value="false" />-->
            <!--&lt;!&ndash; 設定為true時,如果pageSize=0或者RowBounds.limit = 0就會查詢出全部的結果 &ndash;&gt;-->
            <!--<property name="rowBoundsWithCount" value="true" />-->
        </plugin>
    </plugins>
    <!-- 配置壞境變數,可以配置多個,預設值與id一致 -->
   <environments default="development">
       <environment id="development">
           <transactionManager type="JDBC"></transactionManager><!--事務-->
           <dataSource type="POOLED"><!-- 資料來源  連線池POOLED -->
               <property name="driver" value="${jdbc.driver}"/>
               <property name="url" value="${jdbc.url}"/>
               <property name="username" value="${jdbc.username}"/>
               <property name="password" value="${jdbc.password}"/>
           </dataSource>
       </environment>
   </environments>
    <!--配置對映檔案-->
    <mappers>
        <!--基於XML配置檔案-->
        <!--<mapper resource="org/lisonglin/mapper/StudentMapper.xml"/>-->
        <package name="org.lisonglin.mapper"></package>
    </mappers>
</configuration>
package org.lisonglin.mapper;

import org.lisonglin.entity.Teacher;

import java.util.List;

public interface TeacherMapper {
    Teacher getTeacher(int id);
    Teacher get(int id);
    List<Teacher> getAll();
    List<Teacher> getAll1();
}
package org.lisonglin.mapper;

import org.lisonglin.entity.Teacher;
import org.lisonglin.entity.User;

import javax.print.Doc;
import java.util.List;

public interface UserMapper {
    List<User> getByUserId(int teacherid);
    List<User> getAllUser();
}
package org.lisonglin.mapper;

import org.lisonglin.entity.Wifes;

public interface WifesMapper {
    Wifes getByWifesId(int teacherid);
}
<?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="org.lisonglin.mapper.TeacherMapper">
    <!--延遲載入-->
    <resultMap id="selectTeacher" type="Teacher">
        <id property="id" column="id"></id>
        <!--一對一對映-->
        <association property="wife" column="id" select="org.lisonglin.mapper.WifesMapper.getByWifesId" fetchType="lazy">
        </association>
        <!--一對多對映-->
        <collection property="user" column="id" select="org.lisonglin.mapper.UserMapper.getByUserId" fetchType="lazy"></collection>
    </resultMap>
    <select id="getTeacher" resultMap="selectTeacher">
        select * from teachers  where id=#{id}
    </select>
    <cache type="org.mybatis.caches.ehcache.EhcacheCache"></cache>
    <resultMap id="selectClass" type="Teacher">
        <id column="tid" property="id"></id>
        <result column="tname" property="name"></result>
        <result column="tage" property="age"></result>
        <!--一對一對映-->
        <association property="wife" javaType="Wifes">
            <id column="wid" property="id"></id>
            <result column="wname" property="name"></result>
        </association>
        <!--一對多對映-->
        <collection property="user" ofType="User">
            <id column="uid" property="id"></id>
            <result column="uname" property="name"></result>
            <result column="uage" property="age"></result>
        </collection>
    </resultMap>
    <select id="get" resultMap="selectClass">
        select u.id uid,u.`name` uname,u.age uage,
            t.id tid,t.`name` tname,t.age tage,
            w.id wid,w.`name` wname
        from `user` u
          join teachers t
        on u.teacher=t.id
          join wifes w
        on t.wife=w.id
          where t.id=#{id}
    </select>

    <select id="getAll" resultMap="selectClass">
        select u.id uid,u.`name` uname,u.age uage,
            t.id tid,t.`name` tname,t.age tage,
            w.id wid,w.`name` wname
        from `user` u
          join teachers t
        on u.teacher=t.id
          join wifes w
        on t.wife=w.id
    </select>
    <select id="getAll1" resultMap="selectTeacher">
         select *   from teachers
    </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="org.lisonglin.mapper.UserMapper">
    <select id="getAllUser" resultType="User">
        select * from user
    </select>
    <select id="getByUserId" resultType="User">
        select * from `user` where teacher=#{id}
    </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="org.lisonglin.mapper.WifesMapper">
    <select id="getByWifesId" resultType="Wifes">
        select * from wifes where id=#{id}
    </select>

</mapper>
package org.lisonglin.test;

import com.github.pagehelper.PageHelper;
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 org.junit.Test;
import org.lisonglin.entity.Teacher;
import org.lisonglin.entity.User;
import org.lisonglin.mapper.TeacherMapper;
import org.lisonglin.mapper.UserMapper;
import org.lisonglin.util.MyBatis;

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

public class MyTest {

    @Test
    public void test(){
        SqlSession sqlSession = MyBatis.getSqlSession();
        TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
        Teacher teacher = mapper.get(1);
        System.out.println(teacher);
        SqlSession sqlSession1 = MyBatis.getSqlSession();
        TeacherMapper mapper1 = sqlSession.getMapper(TeacherMapper.class);
        Teacher teacher1 = mapper1.get(1);
        System.out.println(teacher1);
        sqlSession1.close();
    }

    @Test
    public void test2(){
        InputStream is = null;
        try {
            is = Resources.getResourceAsStream("mybatis-config.xml");
        } catch (IOException e) {
            e.printStackTrace();
        }
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        SqlSession sqlSession = sqlSessionFactory.openSession();
        TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
        Teacher teacher = mapper.get(1);
        System.out.println(teacher);
        sqlSession.close();
        SqlSession sqlSession1 = sqlSessionFactory.openSession();
        TeacherMapper mapper1 = sqlSession1.getMapper(TeacherMapper.class);
        Teacher teacher1 = mapper1.get(1);
        System.out.println(teacher1);
        sqlSession1.close();
    }

    @Test
    public void testGetLayz(){
        SqlSession sqlSession = MyBatis.getSqlSession();
        TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
        Teacher teacher = mapper.getTeacher(2);
        System.out.println(teacher.getName());
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(teacher.getWife());
        try {
            Thread.sleep(5000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(teacher.getUser());
    }

    @Test
    public void testPageHelper() {
        SqlSession sqlSession = MyBatis.getSqlSession();
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        PageHelper.startPage(1,3);
        List<User> all = mapper.getAllUser();
        System.out.println(all);
    }

    @Test
    public void testPageHelperAll(){
        SqlSession sqlSession = MyBatis.getSqlSession();
        TeacherMapper mapper = sqlSession.getMapper(TeacherMapper.class);
        PageHelper.startPage(1,3);
        List<Teacher> all = mapper.getAll1();
        System.out.println(all);
    }
}

其他檔案配置就不多寫了,還有一個專案to,裡面有自動生成javabean+mybatis的外掛使用,ok!