1. 程式人生 > >SpringBoot數據庫訪問(一)--------關系型數據庫訪問(RDBMS)

SpringBoot數據庫訪問(一)--------關系型數據庫訪問(RDBMS)

rdb epo edr oracle 組件 output 連接 spa stat

關系型數據庫訪問(RDBMS)

采用JdbcTemplate、MyBatis、JPA、Hibernate等技術。

一、JdbcTemplate工具

  • 在pom.xml添加boot-starter-jdbc定義

    <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>1.4.7.RELEASE</
    version> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </
    properties> <dependencies> <dependency><!-- jdbc --> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <
    groupId>com.oracle</groupId><!-- oracle的版本--> <artifactId>ojdbc6</artifactId> <version>11.2.0.3</version> </dependency> </dependencies>

  • 在application.properties添加鏈接參數定義

    spring.datasource.username=SCOTT
    spring.datasource.password=TIGER
    spring.datasource.url=jdbc:oracle:thin:@localhost:1521:XE
    spring.datasource.driverClassName=oracle.jdbc.OracleDriver

  • 根據DEPT表編寫Dept實體類

    public class Dept implements Serializable{
    
        private Integer deptno;
        private String dname;
        private String loc;
    
        //set和get省略
    }

  • 定義DeptDao接口

    public interface DeptDao {
    
        public List<Dept> findAll();
    
    }

  • 定義JdbcDeptDao實現類

    @Repository("deptDao")
    public class JdbcDeptDao implements DeptDao {
    
        @Autowired
        private JdbcTemplate jdbcTemplate;
    
        public List<Dept> findAll() {
            String sql = "select * from DEPT";
            //BeanPropertyRowMapper功能同名加載。查詢結果集列名和實體類屬性名一致,類似寫了一個Maper
            RowMapper<Dept> rowMapper = new BeanPropertyRowMapper<Dept>(Dept.class);
            List<Dept> list = jdbcTemplate.query(sql, rowMapper);
            return list;
        }
    
    }

  • 定義主啟動類,開啟自動配置和掃描等功能

    @SpringBootApplication
    public class MyBootApplication {
    
    }

  • 測試程序

    public static void main(String[] args) {
        ApplicationContext ac =  SpringApplication.run(MyBootApplication.class);
        DeptDao deptDao = ac.getBean("deptDao",DeptDao.class);
        List<Dept> list = deptDao.findAll();
        for(Dept dept:list){
            System.out.println(dept.getDeptno()
                +" "+dept.getDname()+" "+dept.getLoc());
        }
    }

    二、MyBatis工具

    1. 在pom.xml添加boot-starter-jdbc、mybatis-boot定義

      <parent>
          <groupId>org.springframework.boot</groupId>
          <artifactId>spring-boot-starter-parent</artifactId>
          <version>1.4.7.RELEASE</version>
      </parent>
      
      <properties>
          <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
          <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
          <java.version>1.8</java.version>
      </properties>
      
      <dependencies>
      
          <dependency>
              <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot-starter-jdbc</artifactId>
          </dependency>
      
          <dependency>
              <groupId>com.oracle</groupId>
              <artifactId>ojdbc6</artifactId>
              <version>11.2.0.3</version>
          </dependency>
      
          <!-- mybatis、mybatis-spring、autocofigurer -->
          <dependency>
              <groupId>org.mybatis.spring.boot</groupId>
              <artifactId>mybatis-spring-boot-starter</artifactId>
              <version>1.3.0</version>
          </dependency>
      
      </dependencies>

    2. 在application.properties添加數據庫連接參數定義

      spring.datasource.username=SCOTT
      spring.datasource.password=TIGER
      spring.datasource.url=jdbc:oracle:thin:@localhost:1521:XE
      spring.datasource.driverClassName=oracle.jdbc.OracleDriver

    3. 根據DEPT表定義Dept實體類

      同上
      
    4. 定義Mapper映射器DeptDao接口、利用註解定義SQL

      public interface DeptDao {
      
          @Select("select * from DEPT") 
          public List<Dept> selectAll();
      
          @Select("select * form DEPT where DEPTNO=#{no}")
          public Dept selectById(int id);
      
          @Insert("insert into DEPT(DEPTNO,DNAME,LOC) values (#{deptno},#{dname},#{loc})")
          public void save(Dept dept);
      
      }

    5. 定義主啟動類,添加MapperScan標記

      @SpringBootApplication
      @MapperScan(basePackages={"cn.xdl.dao"}) //掃描指定包中的dao類
      public class MyBootApplication {
      
      }

    6. 測試程序

      public static void main(String[] args) {
          ApplicationContext ac =  SpringApplication.run(MyBootApplication.class, args);
          DeptDao deptDao = ac.getBean("deptDao",DeptDao.class);
          List<Dept> list = deptDao.selectAll();
          for(Dept dept:list){
              System.out.println(dept.getDeptno()+" "+dept.getDname());
          }
      }

    7. 追加pageHelper分頁處理

      <dependency>
          <groupId>com.github.pagehelper</groupId>
          <artifactId>pagehelper-spring-boot-starter</artifactId>
          <version>1.2.3</version>
      </dependency> <!-- 指定添加一個分頁組件pageHelp-->

      然後在調用查詢方法前,執行下PageHelper.startPage()方法即可

      PageHelper.startPage(2, 3);
      List<Dept> list = deptDao.selectAll();

    Mybatis使用註意問題

    1. SQL參數使用#{}和${}的區別

      • 采用#{}格式,預編譯SQL執行機制,SQL發送時采用?
      • ${}采用Statement執行機制,參數值拼到SQL中
      • SQL字段值位置使用#{},字段名或表名位置使用${}
    2. 異常:"無效列類型:1111"

      參數#{}遇到null值情況,會提示上述異常。在可能為null參數位置,使用#{}時,需要指定jdbcType屬性,例如#{xx,jdbcType=XXX}技術分享圖片

      三、JPA工具

      1. 在pom.xml追加boot-jdbc、boot-data-jpa包定義

        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>2.0.1.RELEASE</version>
        </parent>
        
        <properties>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
            <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
            <java.version>1.8</java.version>
        </properties>
        
        <dependencies>
        
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-jdbc</artifactId>
            </dependency>
        
            <dependency>
                <groupId>com.oracle</groupId>
                <artifactId>ojdbc6</artifactId>
                <version>11.2.0.3</version>
            </dependency>
        
            <!-- jpa -->
            <dependency>
                <groupId>org.springframework.boot</groupId><!-- 導入jpa的jar包 -->
                <artifactId>spring-boot-starter-data-jpa</artifactId>
            </dependency>
        
        </dependencies>

      2. 在application.properties文件追加數據庫連接參數定義

        spring.datasource.username=SCOTT
        spring.datasource.password=TIGER
        spring.datasource.url=jdbc:oracle:thin:@localhost:1521:XE
        spring.datasource.driverClassName=oracle.jdbc.OracleDriver

      3. 根據DEPT表編寫Dept實體類,並追加映射註解標記

        @Entity  //標識為實體類
        @Table(name="DEPT")  //標識為數據庫中的表名
        public class Dept implements Serializable{
        
            @Id  //指定前的字段為主鍵
            @Column(name="DEPTNO") //指定目標字段與當前字段相同
            private Integer deptno;
        
            @Column(name="DNAME")
            private String dname;
        
            @Column(name="LOC")
            private String loc;
        
            //省略set和get方法       
        
        }

      4. 定義DeptDao接口,可以繼承JpaRepository

        public interface DeptDao extends JpaRepository<Dept, Integer>{
        
        }

        Repository:頂級接口,無任何操作

        CrudRepository:繼承了Repository,增加了增刪改查操作方法

        PagingAndSortingRepository:繼承CrudRepository,增加了分頁和排序操作

        JpaRepository:繼承了PagingAndSortingRepository,增加批處理操作

      5. 測試程序

        public static void main(String[] args) {
            ApplicationContext ac = 
                SpringApplication.run(MyBootApplication.class, args);
            DeptDao deptDao = ac.getBean("deptDao",DeptDao.class);
            List<Dept> list = deptDao.findAll();
            for(Dept dept:list){
                System.out.println(dept.getDeptno()+" "+dept.getDname());
            }
        }
        Sql語句中常用連接詞
        技術分享圖片



        四、Hibernate工具(後續講解)

      6. 未完待續.........

SpringBoot數據庫訪問(一)--------關系型數據庫訪問(RDBMS)