了解Mybatis的基礎(chǔ)

了解Mybatis的基礎(chǔ)

免費(fèi)學(xué)習(xí)推薦:mysql視頻教程

mybatis

mybatis-config.xml詳細(xì)配置(配置時(shí)要把多余的屬性刪除 不能有中文 否則報(bào)錯(cuò)!)

<?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核心配置  配置文件的根元素 --><configuration>     <!-- 屬性:定義配置外在化 -->     <properties></properties>     <!-- 設(shè)置:定義mybatis的一些全局性設(shè)置 -->     <settings>         <!-- 具體的參數(shù)名和參數(shù)值 -->         <setting name="" value=""/>     </settings>     <!-- 類型名稱:為一些類定義別名 -->     <typeAliases>         <!-- 實(shí)體類少 建議 第一種取別名方式-->         <typeAlias type="包路徑" alias="別名"></typeAlias>         <!--實(shí)體類多 建議  第二種取別名方式         默認(rèn)情況下用這種方式 別名為類名 首字母最好小寫         -->         <package name="包名"/>     </typeAliases>     <!-- 類型處理器:定義Java類型與數(shù)據(jù)庫(kù)中的數(shù)據(jù)類型之間的轉(zhuǎn)換關(guān)系 -->     <typeHandlers></typeHandlers>     <!-- 對(duì)象工廠 -->     <objectFactory type=""></objectFactory>     <!-- 插件:mybatis的插件,插件可以修改mybatis的內(nèi)部運(yùn)行規(guī)則 -->     <plugins>         <plugin interceptor=""></plugin>     </plugins>     <!-- 環(huán)境:配置mybatis的環(huán)境 -->     <environments default="development">         <!-- 環(huán)境變量:可以配置多個(gè)環(huán)境變量,比如使用多數(shù)據(jù)源時(shí),就需要配置多個(gè)環(huán)境變量 -->         <environment id="development">             <!-- 事務(wù)管理器 -->             <transactionManager type="JDBC"/>             <!-- 數(shù)據(jù)源 配置連接我的數(shù)據(jù)庫(kù)-->             <dataSource type="POOLED">                 <property name="driver" value="com.mysql.jdbc.Driver"/>                 <property name="url"                           value="jdbc:mysql://localhost:3306/mybatis?serverTimezone=GMT%2B8&useSSL=true&useUnicode=true&characterEncoding=UTF-8"/>                 <property name="password" value="123"/>                 <property name="username" value="root"/>             </dataSource>         </environment>     </environments>     <!-- 數(shù)據(jù)庫(kù)廠商標(biāo)識(shí) -->     <databaseIdProvider type=""></databaseIdProvider>     <!-- 映射器:指定映射文件或者映射類 -->     <mappers>         <mapper resource="com/kang/w/dao/impl/UserMapper.xml"></mapper>     </mappers></configuration>

分頁(yè)

減少數(shù)據(jù)訪問(wèn)量
limt實(shí)現(xiàn)分頁(yè)
sql語(yǔ)句: select * from 表名 limt 0,5;

  • 0:數(shù)據(jù)開(kāi)始的位置
  • 5:數(shù)據(jù)的長(zhǎng)度

第一種:使用Mybatis
1接口

  List<User> getUserByLimit(Map<String, Object> map);

2mapeer.xml

   <select id="getUserByLimit" parameterType="map" resultType="user">         select *         from mybatis.user         limit ${starIndex},${pageSize}    </select>

2-1結(jié)果集映射

<resultMap id="map" type="User">         <result property="pwd" column="password"></result>     </resultMap>

3測(cè)試

 @Test     public void getUserByLimitTest() {         SqlSession sqlSession = MyBatisUtils.getSqlSession ();         UserMapper mapper = sqlSession.getMapper (UserMapper.class);         HashMap hashMap = new HashMap<String, Object> ();         hashMap.put ("starIndex", 1);         hashMap.put ("pageSize", 2);         List userByLimit = mapper.getUserByLimit (hashMap);         for (Object o : userByLimit) {             System.out.println (o);         }          sqlSession.close ();     }

第二種:使用RowBounds方法
1.接口
List getUserList();
2.實(shí)現(xiàn)接口

<select id="getUserList" resultType="user">         select *         from mybatis.user    </select>

3.測(cè)試:

 /**      * 測(cè)試使用RowBounds實(shí)現(xiàn)分頁(yè)      */@Test     public void getUserByLimitRowBoundsTest() {         SqlSession sqlSession = MyBatisUtils.getSqlSession ();         RowBounds rowBounds = new RowBounds (0, 2);         List<User> userList = sqlSession.selectList ("com.kuang.w.dao.UserMapper.getUserList", null, rowBounds);         for (User user : userList) {             System.out.println (user);         }         //關(guān)閉         sqlSession.close ();     }

第三種:使用Mybatis的分頁(yè)插件 pageHeIper
了解Mybatis的基礎(chǔ)

sql 多對(duì)一處理

數(shù)據(jù)庫(kù) :了解Mybatis的基礎(chǔ)
pojo
數(shù)據(jù)庫(kù)中teacher-table表 對(duì)應(yīng)實(shí)體類 Teacher

package com.kuang.w.pojo;  import lombok.Data;  /**  * @author W  */ @Data public class Teacher {     private int tId;     private String tName;  }

數(shù)據(jù)庫(kù)中user表 對(duì)應(yīng) 實(shí)體類Student

package com.kuang.w.pojo;import lombok.Data;/**  * @author W  */@Datapublic class Student {     private int id;     private int tid;     private String name;     private String password;     private Teacher teacher;}

1.接口

   List<Student> getStudentList();

2.xml配置實(shí)現(xiàn)接口

  <!-- 多對(duì)一查詢     1 子查詢 mysql 通過(guò)一個(gè)表里是數(shù)據(jù)   與另一個(gè)表的一個(gè)數(shù)據(jù)相的情況下 查詢另一個(gè)的數(shù)據(jù) 一起顯示   -->     <select id="getStudentList" resultMap="studentTeacher">         select *         from mybatis.user;    </select>     <resultMap id="studentTeacher" type="Student">         <!--  復(fù)雜屬性 對(duì)象用 :association 集合用:collection-->         <!--column 數(shù)據(jù)庫(kù)中的字段 property 實(shí)體類中的屬性-->         <result property="id" column="id"/>         <result property="name" column="name"/>         <result property="password" column="password"/>         <!--javaType	一個(gè) Java 類的全限定名         ,或一個(gè)類型別名(關(guān)于內(nèi)置的類型別名,可以參考上面的表格)。         如果你映射到一個(gè) JavaBean,MyBatis 通常可以推斷類型。         然而,如果你映射到的是 HashMap,         那么你應(yīng)該明確地指定 javaType 來(lái)保證行為與期望的相一致。-->         <association property="teacher" column="tid" javaType="Teacher" select="getTeacher"></association>     </resultMap>     <select id="getTeacher" resultType="Teacher">         select *         from mybatis.teacher_table         where tid = #{id};    </select>
 <!--2 多表聯(lián)查-->     <select id="getStudentList" resultMap="StudentList">         select u.id       uid,                u.name     uname,                u.password upassword,                u.tid      utid,                t.tname         from mybatis.user u,              mybatis.teacher_table t         where t.tid = u.tid;    </select>      <!-- 映射-->     <resultMap id="StudentList" type="Student">         <result column="uid" property="id"/>         <result column="utid" property="tid"/>         <result column="uname" property="name"/>         <result column="upassword" property="password"/>         <association property="teacher" javaType="Teacher">             <result property="tName" column="tname"></result>         </association>     </resultMap>

mybatis-config.xm配置

<?xml version="1.0" encoding="UTF8" ?><!DOCTYPE configuration         PUBLIC "-//mybatis.org//DTD Config 3.0//EN"         "http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration>     <properties resource="db.properties"/>     <settings>         <setting name="logImpl" value="STDOUT_LOGGING"/>     </settings>     <typeAliases>         <typeAlias type="com.kuang.w.pojo.Teacher" alias="teacher"/>         <typeAlias type="com.kuang.w.pojo.Student" alias="student"/>     </typeAliases>      <environments default="development">         <environment id="development">             <transactionManager type="JDBC"/>             <dataSource type="POOLED">                 <property name="driver" value="${driver}"/>                 <property name="url" value="${url}"/>                 <property name="password" value="${password}"/>                 <property name="username" value="${username}"/>             </dataSource>         </environment>     </environments>     <mappers>         <!--   <mapper resource="com/kuang/w/dao/TeacherMapper.xml"></mapper>            <mapper resource="com/kuang/w/dao/StudentMapper.xml"></mapper>-->         <mapper class="com.kuang.w.dao.StudentMapper"></mapper>         <mapper class="com.kuang.w.dao.TeacherMapper"></mapper>     </mappers></configuration>

3 測(cè)試

 @Test     public void getStudentListTest() {         SqlSession sqlSession = MyBatisUtils.getSqlSession ();         StudentMapper mapper = sqlSession.getMapper (StudentMapper.class);           List<Student> studentList = mapper.getStudentList ();         for (Student student : studentList) {             System.out.println (student);         }          sqlSession.commit ();         sqlSession.close ();     }

sql 一對(duì)多處理

數(shù)據(jù)表結(jié)構(gòu) 對(duì)應(yīng)的實(shí)體類 不變

第一種方式: 多表聯(lián)查
1接口

    List<Teacher> getTeacher(int tid);

2.1 xml實(shí)現(xiàn)接口

  <select id="getTeacher" resultMap="TeacherStudent">         select t.tid, t.tname, u.id, u.name, u.password         from mybatis.user u,              mybatis.teacher_table t         where t.tid = u.tid           and t.tid = #{tid};    </select>

2.2映射配置

<resultMap id="TeacherStudent" type="Teacher">         <result property="tName" column="tname"/>         <result property="tId" column="tid"/>         <!--  復(fù)雜屬性 對(duì)象用 :association 集合用:collection-->         <collection property="students" ofType="Student">             <!--javaType 指定屬性類型 一個(gè) Java 類的全限定名-->             <result column="id" property="id"></result>             <result column="name" property="name"></result>             <result column="password" property="password"></result>             <result column="tid" property="tid"></result>         </collection>     </resultMap>

3測(cè)試

 /*測(cè)試一對(duì)多*/     @Test     public void getTeacherTest2() {         SqlSession sqlSession = MyBatisUtils.getSqlSession ();         TeacherMapper mapper = sqlSession.getMapper (TeacherMapper.class);         List<Teacher> teacher = mapper.getTeacher (1);         for (Teacher teacher1 : teacher) {             System.out.println (teacher1);         }  		//提交事務(wù)   架子  這里可以不要         sqlSession.commit ();         // 關(guān)閉         sqlSession.close ();     }

結(jié)果

com.intellij.rt.junit.JUnitStarter -ideVersion5 -junit4 com.kuang.w.dao.myTest,getTeacherTest2 Logging initialized using 'class org.apache.ibatis.logging.stdout.StdOutImpl' adapter.PooledDataSource forcefully closed/removed all connections.PooledDataSource forcefully closed/removed all connections.PooledDataSource forcefully closed/removed all connections.PooledDataSource forcefully closed/removed all connections.Opening JDBC Connection Created connection 164974746.Setting autocommit to false on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@9d5509a]==>  Preparing: select t.tid, t.tname, u.id, u.name, u.password from mybatis.user u, mybatis.teacher_table t where t.tid = u.tid and t.tid = ?; ==> Parameters: 1(Integer)<==    Columns: tid, tname, id, name, password<==        Row: 1, 狂神, 1, 天王蓋地虎, 111<==        Row: 1, 狂神, 2, 小波, 123<==        Row: 1, 狂神, 3, 雷神, 922<==        Row: 1, 狂神, 5, 馬兒扎哈, 123<==      Total: 4Teacher(tId=1, tName=狂神, students=[Student(id=1, tid=1, name=天王蓋地虎, password=111), Student(id=2, tid=1, name=小波, password=123), Student(id=3, tid=1, name=雷神, password=922), Student(id=5, tid=1, name=馬兒扎哈, password=123)])Resetting autocommit to true on JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@9d5509a]Closing JDBC Connection [com.mysql.cj.jdbc.ConnectionImpl@9d5509a]Returned connection 164974746 to pool.Process finished with exit code 0

第二種方式: 子查詢
1接口

    List<Teacher> getTeacher(int tid);

2 實(shí)現(xiàn)接口

 <!--第二種方式: 子查詢-->     <select id="getTeacher3" resultMap="TeacherStudent3">         select *         from mybatis.teacher_table         where tid = #{tid};    </select>     <resultMap id="TeacherStudent3" type="Teacher">         <!--  復(fù)雜屬性 對(duì)象用 :association 集合用:collection         我們需要單獨(dú)處理對(duì)象: association 集合: collection         javaType=""指定屬性的類型!         集合中的泛型信息,我們使用ofType 獲取         -->         <result column="tid" property="tId"/>         <result column="tname" property="tName"/>         <collection property="students" javaType="ArrayList" ofType="Student" select="getStudentByTeacherId"                     column="tid">         </collection>     </resultMap>     <select id="getStudentByTeacherId" resultType="Student">         select *         from mybatis.user         where tid = #{tid};    </select>

3測(cè)試 同上
。。。。

相關(guān)免費(fèi)學(xué)習(xí)推薦:mysql數(shù)據(jù)庫(kù)(視頻)

? 版權(quán)聲明
THE END
喜歡就支持一下吧
點(diǎn)贊5 分享