1. 程式人生 > >企業分布式微服務雲SpringCloud SpringBoot mybatis (七)Spring Boot中使用JdbcTemplate訪問數據庫

企業分布式微服務雲SpringCloud SpringBoot mybatis (七)Spring Boot中使用JdbcTemplate訪問數據庫

ger sele 應該 創建 測試環境 oid reg tis eat

本文介紹在Spring Boot基礎下配置數據源和通過JdbcTemplate編寫數據訪問的示例。

數據源配置

在我們訪問數據庫的時候,需要先配置一個數據源,下面分別介紹一下幾種不同的數據庫配置方式。

首先,為了連接數據庫需要引入jdbc支持,在pom.xml中引入如下配置:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

  

嵌入式數據庫支持

嵌入式數據庫通常用於開發和測試環境,不推薦用於生產環境。Spring Boot提供自動配置的嵌入式數據庫有H2、HSQL、Derby,你不需要提供任何連接配置就能使用。

比如,我們可以在pom.xml中引入如下配置使用HSQL

<dependency>
    <groupId>org.hsqldb</groupId>
    <artifactId>hsqldb</artifactId>
    <scope>runtime</scope>
</dependency>

  

連接生產數據源

以MySQL數據庫為例,先引入MySQL連接的依賴包,在pom.xml中加入:

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.21</version>
</dependency>

  

src/main/resources/application.properties中配置數據源信息

spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=dbuser
spring.datasource.password=dbpass
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

  

連接JNDI數據源

當你將應用部署於應用服務器上的時候想讓數據源由應用服務器管理,那麽可以使用如下配置方式引入JNDI數據源。

spring.datasource.jndi-name=java:jboss/datasources/customers

使用JdbcTemplate操作數據庫

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

舉例:我們在創建User表,包含屬性nameage,下面來編寫數據訪問對象和單元測試用例。

  • 定義包含有插入、刪除、查詢的抽象接口UserService
    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中定義的數據訪問操作
    @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的單元測試用例,通過創建、刪除和查詢來驗證數據庫操作的正確性。
    @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,就可以直接在自己的對象中註入使用。

企業分布式微服務雲SpringCloud SpringBoot mybatis (七)Spring Boot中使用JdbcTemplate訪問數據庫