乡下人产国偷v产偷v自拍,国产午夜片在线观看,婷婷成人亚洲综合国产麻豆,久久综合给合久久狠狠狠9

  • <output id="e9wm2"></output>
    <s id="e9wm2"><nobr id="e9wm2"><ins id="e9wm2"></ins></nobr></s>

    • 分享

      Mybatis高級:Mybatis注解開發(fā)單表操作,Mybatis注解開發(fā)多表操作,構(gòu)建sql語句,綜合案例學(xué)生管理系統(tǒng)使用接口注解方式優(yōu)化

       小樣樣樣樣樣樣 2021-05-03

      知識點(diǎn)梳理

      課堂講義

      一.Mybatis注解開發(fā)單表操作 ***

      1.1 MyBatis的常用注解

      • 之前我們在Mapper映射文件中編寫的sql語句已經(jīng)各種配置,其實(shí)是比較麻煩的

      • 而這幾年來注解開發(fā)越來越流行,Mybatis也可以使用注解開發(fā)方式,這樣我們就可以減少編寫Mapper映射文件了

      • 常用注解

        • @Select(“查詢的 SQL 語句”):執(zhí)行查詢操作注解

        • @Insert(“查詢的 SQL 語句”):執(zhí)行新增操作注解

        • @Update(“查詢的 SQL 語句”):執(zhí)行修改操作注解

        • @Delete(“查詢的 SQL 語句”):執(zhí)行刪除操作注解

      1.2 注解實(shí)現(xiàn)查詢操作

      1. 表:我們還是用db1中的student表

         

         

      2. 新建mybatis04項(xiàng)目

         

         

        • 導(dǎo)入所需要的包

        • 配置相關(guān)的幾個(gè)配置文件(配置文件的內(nèi)容與之前項(xiàng)目都一致,這里就不在羅列)

        • 新建所需要的包

      3. javabean

        package com.itheima.bean;
        ?
        public class Student {
           private Integer id;
           private String name;
           private Integer age;
        ?
           public Student() {
          }
        ?
           public Student(Integer id, String name, Integer age) {
               this.id = id;
               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;
          }
        ?
           @Override
           public String toString() {
               return "Student{" +
                       "id=" + id +
                       ", name='" + name + '\'' +
                       ", age=" + age +
                       '}';
          }
        }
      4. 創(chuàng)建mapper接口

        package com.itheima.mapper;
        ?
        import com.itheima.bean.Student;
        import org.apache.ibatis.annotations.Select;
        ?
        import java.util.List;
        ?
        public interface StudentMapper {
           //查詢?nèi)?br>    @Select("SELECT * FROM student")
           public abstract List<Student> selectAll();
        }
        ?
      5. 配置MyBatisConfig.xml

        <!--配置映射關(guān)系:這里已經(jīng)沒有Mapper映射文件了,但是我們需要配置mapper接口所在的包-->
        <mappers>
           <package name="com.itheima.mapper"/>
        </mappers>
        <!--其實(shí)是注解的方式幫助我們生成了映射文件,所以我們依然是在mappers節(jié)點(diǎn)里配置-->
      6. 測試類:com.itheima.test.Test01

          @Test
           public void selectAll() throws Exception{
               //1.加載核心配置文件
               InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");
        ?
               //2.獲取SqlSession工廠對象
               SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        ?
               //3.通過工廠對象獲取SqlSession對象
               SqlSession sqlSession = sqlSessionFactory.openSession(true);
        ?
               //4.獲取StudentMapper接口的實(shí)現(xiàn)類對象
               StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        ?
               //5.調(diào)用實(shí)現(xiàn)類對象中的方法,接收結(jié)果
               List<Student> list = mapper.selectAll();
        ?
               //6.處理結(jié)果
               for (Student student : list) {
                   System.out.println(student);
              }
          }
      • 注意:

        • 修改MyBatis的核心配置文件,我們使用了注解替代的映射文件,所以我們只需要加載使用了注解的Mapper接口即可

        <mappers>
           <!--掃描使用注解的類-->
           <mapper class="com.itheima.mapper.UserMapper"></mapper>
        </mappers>
        • 或者指定掃描包含映射關(guān)系的接口所在的包也可以

        <mappers>
           <!--掃描使用注解的類所在的包-->
           <package name="com.itheima.mapper"></package>
        </mappers>

      1.3 注解實(shí)現(xiàn)新增操作

      1. StudentMapper新增接口方法

        //新增操作: sql的參數(shù)與之前的寫法一致,從insert方法的參數(shù)中獲取對應(yīng)屬性值
        @Insert("INSERT INTO student VALUES (#{id},#{name},#{age})")
        public abstract Integer insert(Student stu);
      2. 測試方法

        @Test
        public void insert() throws Exception{
           //1.加載核心配置文件
           InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");
        ?
           //2.獲取SqlSession工廠對象
           SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        ?
           //3.通過工廠對象獲取SqlSession對象
           SqlSession sqlSession = sqlSessionFactory.openSession(true);
        ?
           //4.獲取StudentMapper接口的實(shí)現(xiàn)類對象
           StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        ?
           //5.調(diào)用實(shí)現(xiàn)類對象中的方法,接收結(jié)果
           Student stu = new Student(4,"趙六",26);
           Integer result = mapper.insert(stu);
        ?
           //6.處理結(jié)果
           System.out.println(result);
        ?
           //7.釋放資源
           sqlSession.close();
           is.close();
        }
      3. 返回自動(dòng)增長主鍵

        1. 介紹

           

           

        2. 代碼

           

           

          • 在insert注解之上添加Options注解

          • 指定主鍵列為id,主鍵屬性為id(意味會(huì)將注解列id最終的自增結(jié)果返回,并且賦值給stu的id屬性)

        3. 測試

           

           

          • 在mapper.insert(stu)之后,會(huì)將操作結(jié)果返回,并且也會(huì)對stu本身的id進(jìn)行賦值

        4. 結(jié)果

           

           

         

      1.4 注解實(shí)現(xiàn)修改操作

      1. StudentMapper新增接口方法

        //修改操作
        @Update("UPDATE student SET name=#{name},age=#{age} WHERE id=#{id}")
        public abstract Integer update(Student stu);
      2. 測試方法

        @Test
        public void update() throws Exception{
           //1.加載核心配置文件
           InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");
        ?
           //2.獲取SqlSession工廠對象
           SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        ?
           //3.通過工廠對象獲取SqlSession對象
           SqlSession sqlSession = sqlSessionFactory.openSession(true);
        ?
           //4.獲取StudentMapper接口的實(shí)現(xiàn)類對象
           StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        ?
           //5.調(diào)用實(shí)現(xiàn)類對象中的方法,接收結(jié)果
           Student stu = new Student(4,"趙六",36);
           Integer result = mapper.update(stu);
        ?
           //6.處理結(jié)果
           System.out.println(result);
        ?
           //7.釋放資源
           sqlSession.close();
           is.close();
        }

      1.5 注解實(shí)現(xiàn)刪除操作

      1. StudentMapper新增接口方法

        //刪除操作
        @Delete("DELETE FROM student WHERE id=#{id}")
        public abstract Integer delete(Integer id);
      2. 測試方法

        @Test
        public void delete() throws Exception{
           //1.加載核心配置文件
           InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");
        ?
           //2.獲取SqlSession工廠對象
           SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
        ?
           //3.通過工廠對象獲取SqlSession對象
           SqlSession sqlSession = sqlSessionFactory.openSession(true);
        ?
           //4.獲取StudentMapper接口的實(shí)現(xiàn)類對象
           StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
        ?
           //5.調(diào)用實(shí)現(xiàn)類對象中的方法,接收結(jié)果
           Integer result = mapper.delete(4);
        ?
           //6.處理結(jié)果
           System.out.println(result);
        ?
           //7.釋放資源
           sqlSession.close();
           is.close();
        }

      1.6 注解開發(fā)總結(jié)

      注解可以簡化開發(fā)操作,省略映射配置文件的編寫

      • 常用注解

        @Select(“查詢的 SQL 語句”):執(zhí)行查詢操作注解

        @Insert(“查詢的 SQL 語句”):執(zhí)行新增操作注解

        @Update(“查詢的 SQL 語句”):執(zhí)行修改操作注解

        @Delete(“查詢的 SQL 語句”):執(zhí)行刪除操作注解

      • 配置映射關(guān)系

        <mappers> <package name="接口所在包"/> </mappers>    

      二.MyBatis注解開發(fā)的多表操作

      2.1 MyBatis的注解實(shí)現(xiàn)復(fù)雜映射開發(fā)

      • 實(shí)現(xiàn)復(fù)雜關(guān)系映射之前我們可以在映射文件中通過配置<resultMap>來實(shí)現(xiàn),

      • 使用注解開發(fā)后,我們可以使用@Results注解,@Result注解,@One注解,@Many注解組合完成復(fù)雜關(guān)系的配置

       

       

       

       

      2.2 一對一查詢

      2.2.0 準(zhǔn)備工作
      1. 創(chuàng)建項(xiàng)目: mybatis05

         

         

      2. javabean - card

        package com.itheima.bean;
        ?
        public class Card {
           private Integer id;     //主鍵id
           private String number;  //身份證號
        ?
           private Person p;       //所屬人的對象
        ?
           public Card() {
          }
        ?
           public Card(Integer id, String number, Person p) {
               this.id = id;
               this.number = number;
               this.p = p;
          }
        ?
           public Integer getId() {
               return id;
          }
        ?
           public void setId(Integer id) {
               this.id = id;
          }
        ?
           public String getNumber() {
               return number;
          }
        ?
           public void setNumber(String number) {
               this.number = number;
          }
        ?
           public Person getP() {
               return p;
          }
        ?
           public void setP(Person p) {
               this.p = p;
          }
        ?
           @Override
           public String toString() {
               return "Card{" +
                       "id=" + id +
                       ", number='" + number + '\'' +
                       ", p=" + p +
                       '}';
          }
        }
      3. javabean - person

        package com.itheima.bean;
        ?
        public class Person {
           private Integer id;     //主鍵id
           private String name;    //人的姓名
           private Integer age;    //人的年齡
        ?
           public Person() {
          }
        ?
           public Person(Integer id, String name, Integer age) {
               this.id = id;
               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;
          }
        ?
           @Override
           public String toString() {
               return "Person{" +
                       "id=" + id +
                       ", name='" + name + '\'' +
                       ", age=" + age +
                       '}';
          }
        }
        ?
      4. cardMapper接口:我們的核心就是要在Card中做一些處理,實(shí)現(xiàn)一對一的查詢

        package com.itheima.one_to_one;
        ?
        import com.itheima.bean.Card;
        ?
        import java.util.List;
        ?
        public interface CardMapper {
           //查詢?nèi)?br>    public abstract List<Card> selectAll();
        }
      2.2.1 一對一查詢的模型

      一對一查詢的需求:查詢一個(gè)用戶信息,與此同時(shí)查詢出該用戶對應(yīng)的身份證信息

       

       

      2.2.2 一對一查詢的語句

      對應(yīng)的sql語句:

      SELECT * FROM card; -- 只根據(jù)這個(gè)sql語句只能查詢出來card的數(shù)據(jù)
      
      SELECT * FROM person WHERE id=#{id}; -- 需要根據(jù)card表中查詢出來的pid,再次查詢person數(shù)據(jù)才能將person數(shù)據(jù)也查詢出來
      2.2.3 創(chuàng)建PersonMapper接口
      public interface PersonMapper {
          //根據(jù)id查詢
          @Select("SELECT * FROM person WHERE id=#{id}")
          public abstract Person selectById(Integer id);
      }
      
      2.2.4 使用注解配置CardMapper
      public interface CardMapper {
          //查詢?nèi)?    @Select("SELECT * FROM card")
          @Results({
                  @Result(column = "id",property = "id"),
                  @Result(column = "number",property = "number"),
                  @Result(
                          property = "p",             // 被包含對象的變量名
                          javaType = Person.class,    // 被包含對象的實(shí)際數(shù)據(jù)類型
                          column = "pid",             // 根據(jù)查詢出的card表中的pid字段來查詢person表
                          /*
                              one、@One 一對一固定寫法
                              select屬性:指定調(diào)用哪個(gè)接口中的哪個(gè)方法
                           */
                          one = @One(select = "com.itheima.one_to_one.PersonMapper.selectById")
                  )
          })
          public abstract List<Card> selectAll();
      }
      2.2.5 測試類
      package com.itheima.one_to_one;
      
      import com.itheima.bean.Card;
      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 java.io.InputStream;
      import java.util.List;
      
      public class Test01 {
          @Test
          public void selectAll() throws Exception{
              //1.加載核心配置文件
              InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");
      
              //2.獲取SqlSession工廠對象
              SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
      
              //3.通過工廠對象獲取SqlSession對象
              SqlSession sqlSession = sqlSessionFactory.openSession(true);
      
              //4.獲取CardMapper接口的實(shí)現(xiàn)類對象
              CardMapper mapper = sqlSession.getMapper(CardMapper.class);
      
              //5.調(diào)用實(shí)現(xiàn)類對象中的方法,接收結(jié)果
              List<Card> list = mapper.selectAll();
      
              //6.處理結(jié)果
              for (Card card : list) {
                  System.out.println(card);
              }
      
              //7.釋放資源
              sqlSession.close();
              is.close();
          }
      
      }
      • 結(jié)果

         

         

      2.2.6 一對一配置總結(jié)
      @Results:封裝映射關(guān)系的父注解。
      Result[] value():定義了 Result 數(shù)組
      @Result:封裝映射關(guān)系的子注解。
      column 屬性:查詢出的表中字段名稱
      property 屬性:實(shí)體對象中的屬性名稱
      javaType 屬性:被包含對象的數(shù)據(jù)類型
      one 屬性:一對一查詢固定屬性
       @One:一對一查詢的注解。
      select 屬性:指定調(diào)用某個(gè)接口中的方法
      2.2.7 分析

       

       

      2.3 一對多查詢

      2.3.1 一對多查詢的模型

      一對多查詢的需求:查詢一個(gè)課程,與此同時(shí)查詢出該該課程對應(yīng)的學(xué)生信息

       

       

      2.3.2 一對多查詢的語句

      對應(yīng)的sql語句:

      SELECT * FROM classes
      
      SELECT * FROM student WHERE cid=#{cid}
      2.3.3 創(chuàng)建StudentMapper接口
      public interface StudentMapper {
          //根據(jù)cid查詢student表
          @Select("SELECT * FROM student WHERE cid=#{cid}")
          public abstract List<Student> selectByCid(Integer cid);
      }
      2.3.4 使用注解配置Mapper
      public interface ClassesMapper {
          //查詢?nèi)?    @Select("SELECT * FROM classes")
          @Results({
                  @Result(column = "id",property = "id"),
                  @Result(column = "name",property = "name"),
                  @Result(
                          property = "students",  // 被包含對象的變量名
                          javaType = List.class,  // 被包含對象的實(shí)際數(shù)據(jù)類型
                          column = "id",          // 根據(jù)查詢出的classes表的id字段來查詢student表
                          /*
                              many、@Many 一對多查詢的固定寫法
                              select屬性:指定調(diào)用哪個(gè)接口中的哪個(gè)查詢方法
                           */
                          many = @Many(select = "com.itheima.one_to_many.StudentMapper.selectByCid")
                  )
          })
          public abstract List<Classes> selectAll();
      }
      2.3.5 測試類
      public class Test01 {
          @Test
          public void selectAll() throws Exception{
              //1.加載核心配置文件
              InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");
      
              //2.獲取SqlSession工廠對象
              SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
      
              //3.通過工廠對象獲取SqlSession對象
              SqlSession sqlSession = sqlSessionFactory.openSession(true);
      
              //4.獲取ClassesMapper接口的實(shí)現(xiàn)類對象
              ClassesMapper mapper = sqlSession.getMapper(ClassesMapper.class);
      
              //5.調(diào)用實(shí)現(xiàn)類對象中的方法,接收結(jié)果
              List<Classes> list = mapper.selectAll();
      
              //6.處理結(jié)果
              for (Classes cls : list) {
                  System.out.println(cls.getId() + "," + cls.getName());
                  List<Student> students = cls.getStudents();
                  for (Student student : students) {
                      System.out.println("\t" + student);
                  }
              }
      
              //7.釋放資源
              sqlSession.close();
              is.close();
          }
      
      }
      
      2.3.6 一對多配置總結(jié)
      @Results:封裝映射關(guān)系的父注解。
      Result[] value():定義了 Result 數(shù)組
      @Result:封裝映射關(guān)系的子注解。
      column 屬性:查詢出的表中字段名稱
      property 屬性:實(shí)體對象中的屬性名稱
      javaType 屬性:被包含對象的數(shù)據(jù)類型
      many 屬性:一對多查詢固定屬性
      @Many:一對多查詢的注解。
      select 屬性:指定調(diào)用某個(gè)接口中的方法
      2.3.7 分析

       

       

      2.4 多對多查詢

      2.4.1 多對多查詢的模型

      多對多查詢的需求:查詢學(xué)生以及所對應(yīng)的課程信息

       

       

      2.4.2 多對多查詢的語句

      對應(yīng)的sql語句:

      SELECT DISTINCT s.id,s.name,s.age FROM student s,stu_cr sc WHERE sc.sid=s.id
      SELECT c.id,c.name FROM stu_cr sc,course c WHERE sc.cid=c.id AND sc.sid=#{id}
      2.4.3 添加CourseMapper 接口方法
      public interface CourseMapper {
          //根據(jù)學(xué)生id查詢所選課程
          @Select("SELECT c.id,c.name FROM stu_cr sc,course c WHERE sc.cid=c.id AND sc.sid=#{id}")
          public abstract List<Course> selectBySid(Integer id);
      }
      2.4.4 使用注解配置Mapper
      public interface StudentMapper {
          //查詢?nèi)?    @Select("SELECT DISTINCT s.id,s.name,s.age FROM student s,stu_cr sc WHERE sc.sid=s.id")
          @Results({
                  @Result(column = "id",property = "id"),
                  @Result(column = "name",property = "name"),
                  @Result(column = "age",property = "age"),
                  @Result(
                          property = "courses",   // 被包含對象的變量名
                          javaType = List.class,  // 被包含對象的實(shí)際數(shù)據(jù)類型
                          column = "id",          // 根據(jù)查詢出student表的id來作為關(guān)聯(lián)條件,去查詢中間表和課程表
                          /*
                              many、@Many 一對多查詢的固定寫法
                              select屬性:指定調(diào)用哪個(gè)接口中的哪個(gè)查詢方法
                           */
                          many = @Many(select = "com.itheima.many_to_many.CourseMapper.selectBySid")
                  )
          })
          public abstract List<Student> selectAll();
      }
      
      2.4.5 測試類
      public class Test01 {
          @Test
          public void selectAll() throws Exception{
              //1.加載核心配置文件
              InputStream is = Resources.getResourceAsStream("MyBatisConfig.xml");
      
              //2.獲取SqlSession工廠對象
              SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
      
              //3.通過工廠對象獲取SqlSession對象
              SqlSession sqlSession = sqlSessionFactory.openSession(true);
      
              //4.獲取StudentMapper接口的實(shí)現(xiàn)類對象
              StudentMapper mapper = sqlSession.getMapper(StudentMapper.class);
      
              //5.調(diào)用實(shí)現(xiàn)類對象中的方法,接收結(jié)果
              List<Student> list = mapper.selectAll();
      
              //6.處理結(jié)果
              for (Student student : list) {
                  System.out.println(student.getId() + "," + student.getName() + "," + student.getAge());
                  List<Course> courses = student.getCourses();
                  for (Course cours : courses) {
                      System.out.println("\t" + cours);
                  }
              }
      
              //7.釋放資源
              sqlSession.close();
              is.close();
          }
      
      }
      2.4.6 多對多配置總結(jié)
      @Results:封裝映射關(guān)系的父注解。
      Result[] value():定義了 Result 數(shù)組
      @Result:封裝映射關(guān)系的子注解。
      column 屬性:查詢出的表中字段名稱
      property 屬性:實(shí)體對象中的屬性名稱
      javaType 屬性:被包含對象的數(shù)據(jù)類型
      many 屬性:一對多查詢固定屬性
      @Many:一對多查詢的注解。
      select 屬性:指定調(diào)用某個(gè)接口中的方法
      2.4.7 分析

       

       

      三.構(gòu)建sql

      3.1 SQL構(gòu)建對象介紹

      • 我們之前通過注解開發(fā)時(shí),相關(guān) SQL 語句都是自己直接拼寫的。一些關(guān)鍵字寫起來比較麻煩、而且容易出錯(cuò)。

      • MyBatis 給我們提供了 org.apache.ibatis.jdbc.SQL 功能類,專門用于構(gòu)建 SQL 語句

         

         

      • 創(chuàng)建項(xiàng)目:將之前的注解的所有相關(guān)代碼,配置文件拿過來

         

      • 新建測試類: com.itheima.sql.SqlTest

        package com.itheima.sql;
        
        public class SqlTest {
            public static void main(String[] args) {
                String sql = getSql();
                System.out.println(sql);
            }
        
            //定義方法,獲取查詢student表的sql語句
            public static String getSql() {
                String sql = "SELECT * FROM student";
                return sql;
            }
        }
        • 如果sql語句比較長,sql中的關(guān)鍵字較多時(shí),就可能會(huì)寫錯(cuò)

      • 修改代碼:使用SQL類通過的方法來編寫sql語句

        package com.itheima.sql;
        
        import org.apache.ibatis.jdbc.SQL;
        
        public class SqlTest {
            public static void main(String[] args) {
                String sql = getSql();
                System.out.println(sql);
            }
        
            //定義方法,獲取查詢student表的sql語句
            /*public static String getSql() {
                String sql = "SELECT * FROM student";
                return sql;
            }*/
        
            public static String getSql() {
                String sql = new SQL(){//通過SQL類提供的方法來實(shí)現(xiàn)sql語句的編寫
                    {
                        SELECT("*");
                        FROM("student");
                    }
                }.toString();
        
                return sql;
            }
        }
        
      • 結(jié)果

         

         

      3.2 查詢功能的實(shí)現(xiàn)

      • 定義功能類并提供獲取查詢的 SQL 語句的方法

        • 新建類:com.itheima.sql.ReturnSql,定義獲取sql語句的方法

        package com.itheima.sql;
        import org.apache.ibatis.jdbc.SQL;
        
        public class ReturnSql {
            //定義方法,返回查詢的sql語句
            public String getSelectAll() {
                return new SQL() {
                    {
                        SELECT("*");
                        FROM("student");
                    }
                }.toString();
            //以上代碼說明:內(nèi)層的花括號是一個(gè)構(gòu)造代碼塊,在實(shí)例化一個(gè)對象時(shí)會(huì)先于構(gòu)造方法執(zhí)行,編譯時(shí)會(huì)將構(gòu)造代碼塊移入構(gòu)造方法中
                //如果上述不理解,可以使用以下方式:Builder風(fēng)格
                String sql = new SQL()
                     .SELECT("*")
                     .FROM("student")
                     .toString();
                  return sql;
            }
        }
        • 那么如何獲取這個(gè)提供了sql語句的方法呢?

        • 之前是在Mapper接口中直接通過注解(@Select,@Insert等)來設(shè)置的sql

        • 現(xiàn)在有提供了sql語句的方法,如何獲取呢?

        • 通過@SelectProvider注解來獲取

      • @SelectProvider:生成查詢用的 SQL 語句注解(調(diào)用提供sql語句的方法,獲取到查詢的sql語句

        • type 屬性:用于指定生成 SQL 語句功能的類對象

      • method 屬性:用于指定類中要執(zhí)行獲取sql語句的方法 (指定方法名,不加小括號)

      • 修改StudentMapper

        //查詢?nèi)?//@Select("SELECT * FROM student")
        //注意:method只是指定一個(gè)方法的名字,SelectProvider內(nèi)部會(huì)自己調(diào)用
        @SelectProvider(type = ReturnSql.class , method = "getSelectAll")
        public abstract List<Student> selectAll();
      • 運(yùn)行test包中的Test01的selectAll方法,能查詢出數(shù)據(jù)即可

      3.3 新增功能的實(shí)現(xiàn)

      • 定義功能類并提供獲取新增的 SQL 語句的方法,在ReturnSql中增加如下方法:

        //定義方法,返回新增的sql語句
        public String getInsert(Student stu) {
            return new SQL() {
                {
                    INSERT_INTO("student");
                    INTO_VALUES("#{id},#{name},#{age}");
                }
            }.toString();
        }
      • @InsertProvider:生成新增用的 SQL 語句注解(調(diào)用提供sql語句的方法,獲取到新增的sql語句

        • type 屬性:生成 SQL 語句功能類對象

      • method 屬性:指定調(diào)用方法

      • 修改StudentMapper

        //新增功能
        //@Insert("INSERT INTO student VALUES (#{id},#{name},#{age})")
        @InsertProvider(type = ReturnSql.class , method = "getInsert")
        public abstract Integer insert(Student stu);
      • 運(yùn)行test包中的Test01的insert方法,能插入數(shù)據(jù)即可

      3.4 修改功能的實(shí)現(xiàn)

      • 定義功能類并提供獲取修改的 SQL 語句的方法

        //定義方法,返回修改的sql語句
        public String getUpdate(Student stu) {
            return new SQL() {
                {
                    UPDATE("student");
                    SET("name=#{name}","age=#{age}");
                    WHERE("id=#{id}");
                }
            }.toString();
        }
      • @UpdateProvider:生成修改用的 SQL 語句注解(調(diào)用提供sql語句的方法,獲取到更新的sql語句

        • type 屬性:生成 SQL 語句功能類對象

      • method 屬性:指定調(diào)用方法

      • 修改StudentMapper

        //修改功能
        //@Update("UPDATE student SET name=#{name},age=#{age} WHERE id=#{id}")
        @UpdateProvider(type = ReturnSql.class , method = "getUpdate")
        public abstract Integer update(Student stu);
      • 運(yùn)行test包中的Test01的update方法,能更新數(shù)據(jù)即可

      3.5 刪除功能的實(shí)現(xiàn)

      • 定義功能類并提供獲取刪除的 SQL 語句的方法

         //定義方法,返回刪除的sql語句
            public String getDelete(Integer id) {
                return new SQL() {
                    {
                        DELETE_FROM("student");
                        WHERE("id=#{id}");
                    }
                }.toString();
            }
      • @DeleteProvider:生成刪除用的 SQL 語句注解(調(diào)用提供sql語句的方法,獲取到刪除的sql語句

        • type 屬性:生成 SQL 語句功能類對象

      • method 屬性:指定調(diào)用方法

      • 修改StudentMapper

        //刪除功能
        //@Delete("DELETE FROM student WHERE id=#{id}")
        @DeleteProvider(type = ReturnSql.class , method = "getDelete")
        public abstract Integer delete(Integer id);
      • 運(yùn)行test包中的Test01的delete方法,能刪除數(shù)據(jù)即可

      四.綜合案例 ***

      4.1 系統(tǒng)介紹

      我們之前在做學(xué)生管理系統(tǒng)時(shí),使用的是原始JDBC操作數(shù)據(jù)庫的,操作非常麻煩,現(xiàn)在我們使用MyBatis操作數(shù)據(jù)庫,簡化Dao的開發(fā)。

      4.2 環(huán)境搭建

      1. 創(chuàng)建數(shù)據(jù)庫

        -- 創(chuàng)建db3數(shù)據(jù)庫
        CREATE DATABASE db3;
        
        -- 使用db3數(shù)據(jù)庫
        USE db3;
        
        -- 創(chuàng)建用戶表
        CREATE TABLE USER(
        uid VARCHAR(50) PRIMARY KEY,-- 用戶id
        ucode VARCHAR(50),-- 用戶標(biāo)識
        loginname VARCHAR(100),-- 登錄用戶名
        PASSWORD VARCHAR(100),-- 登錄密碼
        username VARCHAR(100),-- 用戶名
        gender VARCHAR(10),-- 用戶性別
        birthday DATE,-- 出生日期
        dutydate DATE                   -- 入職日期
        );
        
        -- 添加一條測試數(shù)據(jù)
        INSERT INTO USER VALUES ('11111111', 'zhangsan001', 'zhangsan', '1234', '張三', '男', '2008-10-28', '2018-10-28');
        
        
        -- 創(chuàng)建student表
        CREATE TABLE student(
        sid INT PRIMARY KEY AUTO_INCREMENT,-- 學(xué)生id
        NAME VARCHAR(20),-- 學(xué)生姓名
        age INT,-- 學(xué)生年齡
        birthday DATE-- 學(xué)生生日
        );
        
        -- 添加數(shù)據(jù)
        INSERT INTO student VALUES (NULL,'張三',23,'1999-09-23'),(NULL,'李四',24,'1998-08-10'),
        (NULL,'王五',25,'1996-06-06'),(NULL,'趙六',26,'1994-10-20');
        
      2. 將之前的“JDBC基礎(chǔ)網(wǎng)頁版”項(xiàng)目copy過來

         

         

      3. 運(yùn)行起來:注意這個(gè)項(xiàng)目的虛擬目錄必須是/,因?yàn)榻缑嬷械逆溄訉懰懒?/span>

         

         

      4. 輸入zhangsan,1234,登陸進(jìn)去,我們現(xiàn)在要處理的是 在校學(xué)生管理:

         

         

      5. 在這里,可以對學(xué)生進(jìn)行增刪改查,之前是通過jdbc實(shí)現(xiàn)的這些功能,現(xiàn)在我們需要通過mybatis來實(shí)現(xiàn)

      6. 增加jar包:

         

         

      7. 復(fù)制相關(guān)的配置文件:log4j和MyBatisConfig

         

         

      8. 修改config.properties(這個(gè)其實(shí)就是jdbc配置文件)

        driver=com.mysql.jdbc.Driver
        url=jdbc:mysql://192.168.59.143:3306/db3
        username=root
        password=itheima
      9. 修改MyBatisConfig主配置文件:

        <!--引入數(shù)據(jù)庫連接的配置文件-->
        <properties resource="config.properties"/>
        起別名的配置刪掉
        <!--配置映射關(guān)系-->
        <mappers>
        <package name="com.itheima.dao"/>
        </mappers>
      10. 刪除StudentDaoImpl,我們不需要實(shí)現(xiàn)類,我們會(huì)通過接口代理的方式來實(shí)現(xiàn)

      11. 修改StudentDao,給接口方法通過注解的方式配置sql語句

        package com.itheima.dao;
        
        import com.itheima.domain.Student;
        import org.apache.ibatis.annotations.Delete;
        import org.apache.ibatis.annotations.Insert;
        import org.apache.ibatis.annotations.Select;
        import org.apache.ibatis.annotations.Update;
        
        import java.util.ArrayList;
        
        /*
            Dao層接口
         */
        public interface StudentDao {
            //查詢所有學(xué)生信息
            @Select("SELECT * FROM student")
            public abstract ArrayList<Student> findAll();
        
            //條件查詢,根據(jù)id獲取學(xué)生信息
            @Select("SELECT * FROM student WHERE sid=#{sid}")
            public abstract Student findById(Integer sid);
        
            //新增學(xué)生信息
            @Insert("INSERT INTO student VALUES (#{sid},#{name},#{age},#{birthday})")
            public abstract int insert(Student stu);
        
            //修改學(xué)生信息
            @Update("UPDATE student SET name=#{name},age=#{age},birthday=#{birthday} WHERE sid=#{sid}")
            public abstract int update(Student stu);
        
            //刪除學(xué)生信息
            @Delete("DELETE FROM student WHERE sid=#{sid}")
            public abstract int delete(Integer sid);
        }
        
      12. 修改StudentServiceImpl,刪除之前的DaoImpl的邏輯

        package com.itheima.service.impl;
        
        import com.itheima.domain.Student;
        import com.itheima.service.StudentService;
        
        import java.util.List;
        
        /**
         * 學(xué)生的業(yè)務(wù)層實(shí)現(xiàn)類
         * @author 黑馬程序員
         * @Company http://www.
         */
        public class StudentServiceImpl implements StudentService {
        
            @Override
            public List<Student> findAll() {
               
            }
        
            @Override
            public Student findById(Integer sid) {
        
            }
        
            @Override
            public void save(Student student) {
        
            }
        
            @Override
            public void update(Student student) {
        
            }
        
            @Override
            public void delete(Integer sid) {
        
            }
        }
        

      4.3 代碼改造

      • 我們主要是將原來的jdbc實(shí)現(xiàn)的方式改為mybatis實(shí)現(xiàn)

      • 新建com.itheima.utils.MyBatisUtils.java

        package com.itheima.utils;
        
        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;
        
        /*
            工具類
         */
        public class MyBatisUtils {
            // 私有構(gòu)造方法
            private MyBatisUtils(){}
        
            // 聲明連接工廠對象
            private static SqlSessionFactory sqlSessionFactory;
        
            // 靜態(tài)代碼塊,讀取核心配置文件并工廠對象賦值
            static {
                try {
                    sqlSessionFactory = new SqlSessionFactoryBuilder().build(Resources.getResourceAsStream("MyBatisConfig.xml"));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        
            // 提供靜態(tài)方法,返回SqlSession對象
            public static SqlSession getSqlSession() {
                return sqlSessionFactory.openSession(true);
            }
        }
        
      • 修改StudentServiceImpl代碼

        package com.itheima.service.impl;
        
        import com.itheima.dao.StudentDao;
        import com.itheima.domain.Student;
        import com.itheima.service.StudentService;
        import com.itheima.utils.MyBatisUtils;
        import org.apache.ibatis.session.SqlSession;
        
        import java.util.ArrayList;
        import java.util.List;
        
        /**
         * 學(xué)生的業(yè)務(wù)層實(shí)現(xiàn)類
         * @author 黑馬程序員
         * @Company http://www.
         */
        public class StudentServiceImpl implements StudentService {
        
            @Override
            public List<Student> findAll() {
                // 獲取SqlSession對象
                SqlSession sqlSession = MyBatisUtils.getSqlSession();
        
                // 獲取StudentDao接口的實(shí)現(xiàn)類對象
                StudentDao mapper = sqlSession.getMapper(StudentDao.class);
        
                // 調(diào)用實(shí)現(xiàn)類對象相應(yīng)的功能
                ArrayList<Student> list = mapper.findAll();
        
                // 釋放資源
                sqlSession.close();
        
                // 返回結(jié)果
                return list;
            }
        
            @Override
            public Student findById(Integer sid) {
                // 獲取SqlSession對象
                SqlSession sqlSession = MyBatisUtils.getSqlSession();
        
                // 獲取StudentDao接口的實(shí)現(xiàn)類對象
                StudentDao mapper = sqlSession.getMapper(StudentDao.class);
        
                // 調(diào)用實(shí)現(xiàn)類對象相應(yīng)的功能
                Student stu = mapper.findById(sid);
        
                // 釋放資源
                sqlSession.close();
        
                // 返回結(jié)果
                return stu;
            }
        
            @Override
            public void save(Student student) {
                // 獲取SqlSession對象
                SqlSession sqlSession = MyBatisUtils.getSqlSession();
        
                // 獲取StudentDao接口的實(shí)現(xiàn)類對象
                StudentDao mapper = sqlSession.getMapper(StudentDao.class);
        
                // 調(diào)用實(shí)現(xiàn)類對象相應(yīng)的功能
                mapper.insert(student);
        
                // 釋放資源
                sqlSession.close();
        
            }
        
            @Override
            public void update(Student student) {
                // 獲取SqlSession對象
                SqlSession sqlSession = MyBatisUtils.getSqlSession();
        
                // 獲取StudentDao接口的實(shí)現(xiàn)類對象
                StudentDao mapper = sqlSession.getMapper(StudentDao.class);
        
                // 調(diào)用實(shí)現(xiàn)類對象相應(yīng)的功能
                mapper.update(student);
        
                // 釋放資源
                sqlSession.close();
            }
        
            @Override
            public void delete(Integer sid) {
                // 獲取SqlSession對象
                SqlSession sqlSession = MyBatisUtils.getSqlSession();
        
                // 獲取StudentDao接口的實(shí)現(xiàn)類對象
                StudentDao mapper = sqlSession.getMapper(StudentDao.class);
        
                // 調(diào)用實(shí)現(xiàn)類對象相應(yīng)的功能
                mapper.delete(sid);
        
                // 釋放資源
                sqlSession.close();
            }
        }
        package com.itheima.service.impl;
        
        import com.itheima.dao.StudentDao;
        import com.itheima.domain.Student;
        import com.itheima.service.StudentService;
        import com.itheima.utils.MyBatisUtils;
        import org.apache.ibatis.session.SqlSession;
        
        import java.util.ArrayList;
        import java.util.List;
        
        /**
         * 學(xué)生的業(yè)務(wù)層實(shí)現(xiàn)類
         * @author 黑馬程序員
         * @Company http://www.
         */
        public class StudentServiceImpl implements StudentService {
        
            @Override
            public List<Student> findAll() {
                // 獲取SqlSession對象
                SqlSession sqlSession = MyBatisUtils.getSqlSession();
        
                // 獲取StudentDao接口的實(shí)現(xiàn)類對象
                StudentDao mapper = sqlSession.getMapper(StudentDao.class);
        
                // 調(diào)用實(shí)現(xiàn)類對象相應(yīng)的功能
                ArrayList<Student> list = mapper.findAll();
        
                // 釋放資源
                sqlSession.close();
        
                // 返回結(jié)果
                return list;
            }
        
            @Override
            public Student findById(Integer sid) {
                // 獲取SqlSession對象
                SqlSession sqlSession = MyBatisUtils.getSqlSession();
        
                // 獲取StudentDao接口的實(shí)現(xiàn)類對象
                StudentDao mapper = sqlSession.getMapper(StudentDao.class);
        
                // 調(diào)用實(shí)現(xiàn)類對象相應(yīng)的功能
                Student stu = mapper.findById(sid);
        
                // 釋放資源
                sqlSession.close();
        
                // 返回結(jié)果
                return stu;
            }
        
            @Override
            public void save(Student student) {
                // 獲取SqlSession對象
                SqlSession sqlSession = MyBatisUtils.getSqlSession();
        
                // 獲取StudentDao接口的實(shí)現(xiàn)類對象
                StudentDao mapper = sqlSession.getMapper(StudentDao.class);
        
                // 調(diào)用實(shí)現(xiàn)類對象相應(yīng)的功能
                mapper.insert(student);
        
                // 釋放資源
                sqlSession.close();
        
            }
        
            @Override
            public void update(Student student) {
                // 獲取SqlSession對象
                SqlSession sqlSession = MyBatisUtils.getSqlSession();
        
                // 獲取StudentDao接口的實(shí)現(xiàn)類對象
                StudentDao mapper = sqlSession.getMapper(StudentDao.class);
        
                // 調(diào)用實(shí)現(xiàn)類對象相應(yīng)的功能
                mapper.update(student);
        
                // 釋放資源
                sqlSession.close();
            }
        
            @Override
            public void delete(Integer sid) {
                // 獲取SqlSession對象
                SqlSession sqlSession = MyBatisUtils.getSqlSession();
        
                // 獲取StudentDao接口的實(shí)現(xiàn)類對象
                StudentDao mapper = sqlSession.getMapper(StudentDao.class);
        
                // 調(diào)用實(shí)現(xiàn)類對象相應(yīng)的功能
                mapper.delete(sid);
        
                // 釋放資源
                sqlSession.close();
            }
        }
      • 員工管理也有增刪改查,大家可以作為課下作業(yè)

         

         

         

      •  

       

        本站是提供個(gè)人知識管理的網(wǎng)絡(luò)存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點(diǎn)。請注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點(diǎn)擊一鍵舉報(bào)。
        轉(zhuǎn)藏 分享 獻(xiàn)花(0

        0條評論

        發(fā)表

        請遵守用戶 評論公約

        類似文章 更多