1. 程式人生 > >使用JdbcTemplate操作資料庫(二十九)

使用JdbcTemplate操作資料庫(二十九)

使用JdbcTemplate操作資料庫

Spring的JdbcTemplate是自動配置的,你可以直接使用@Autowired來注入到你自己的bean中來使用。

舉例:我們在建立User表,包含屬性nameage,下面來編寫資料訪問物件和單元測試用例。

  • 定義包含有插入、刪除、查詢的抽象介面UserService
    1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 public  interface  UserService {        /**       * 新增一個使用者
          * @param name       * @param age       */     
    void  create(String name, Integer age);        /**       * 根據name刪除一個使用者高       * @param name       */      void  deleteByName(String name);        /**       * 獲取使用者總量       */      Integer getAllUsers();        /**       * 刪除所有使用者       */      void  deleteAllUsers();   }

     

  • 通過JdbcTemplate實現UserService中定義的資料訪問操作
    1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 @Service public  class  UserServiceImpl  implements  UserService {        @Autowired      private  JdbcTemplate jdbcTemplate;        @Override      public  void  create(String name, Integer age) {          jdbcTemplate.update( "insert into USER(NAME, AGE) values(?, ?)" , name, age);      }        @Override      public  void  deleteByName(String name) {          jdbcTemplate.update( "delete from USER where NAME = ?" , name);      }        @Override      public  Integer getAllUsers() {          return  jdbcTemplate.queryForObject( "select count(1) from USER" , Integer. class );      }        @Override      public  void  deleteAllUsers() {          jdbcTemplate.update( "delete from USER" );      } }

     

  • 建立對UserService的單元測試用例,通過建立、刪除和查詢來驗證資料庫操作的正確性。
    1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 @RunWith (SpringJUnit4ClassRunner. class ) @SpringApplicationConfiguration (Application. class ) public  class  ApplicationTests {        @Autowired      private  UserService userSerivce;        @Before      public  void  setUp() {          // 準備,清空user表          userSerivce.deleteAllUsers();      }        @Test      public  void  test()  throws  Exception {          // 插入5個使用者          userSerivce.create( "a" 1 );          userSerivce.create( "b" 2 );          userSerivce.create( "c" 3 );          userSerivce.create( "d" 4 );          userSerivce.create( "e" 5 );            // 查資料庫,應該有5個使用者          Assert.assertEquals( 5 , userSerivce.getAllUsers().intValue());            // 刪除兩個使用者          userSerivce.deleteByName( "a" );          userSerivce.deleteByName( "e" );            // 查資料庫,應該有5個使用者          Assert.assertEquals( 3 , userSerivce.getAllUsers().intValue());        }   }

    上面介紹的JdbcTemplate只是最基本的幾個操作,更多其他資料訪問操作的使用請參考:JdbcTemplate API

    通過上面這個簡單的例子,我們可以看到在Spring Boot下訪問資料庫的配置依然秉承了框架的初衷:簡單。我們只需要在pom.xml中加入資料庫依賴,再到application.properties中配置連線資訊,不需要像Spring應用中建立JdbcTemplate的Bean,就可以直接在自己的物件中注入使用。