zoukankan      html  css  js  c++  java
  • Springboot-H2DB

    为什么在Springboot中用H2DB

    用Springboot开发需要连接数据库的程序的时候,使用H2DB作为内存数据库可以很方便的调试程序。

    怎么用

    1.加入依赖

    <dependency>
       <groupId>com.h2database</groupId>
       <artifactId>h2</artifactId>
       <scope>runtime</scope>
    </dependency>

    2.创建实体类,并指明表的名称,这个实体类是放在src/main/java 下的,注意,这个实体类是应用程序会用到的,不是为了测试而写的。不用我们先CreateDB,再在DB下create 一个 Table,H2DB根据实体类会帮我们create 好Table 放在H2DB里面。

    package com.springboot.h2;
    
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.Id;
    import javax.persistence.Table;
    
    @Entity
    @Table(name = "T_CUSTOMER")
    public class Customer {
    
        @Id
        @Column(name = "customer_id")
        private Long customerId;
    
        @Column(name = "customer_name")
        private String customerName;
    
        public Long getCustomerId() {
        return customerId;
        }
    
        public void setCustomerId(Long customerId) {
        this.customerId = customerId;
        }
    
        public String getCustomerName() {
        return customerName;
        }
    
        public void setCustomerName(String customerName) {
        this.customerName = customerName;
        }
    
        public String toString() {
        return String.format("Customer id: %d ,Customer name: %s", customerId, customerName);
        }
    
    }

    3.在src/test/resource 下面放置 准备测试数据的SQL文件

    4.此时,开始写测试类

    package com.springboot.h2;
    
    import java.util.List;
    
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.boot.test.context.SpringBootTest;
    import org.springframework.test.context.junit4.SpringRunner;
    
    @RunWith(SpringRunner.class)
    @SpringBootTest(classes = {Application.class})
    public class H2DBTest {
    
        @Autowired
        private CustomerRepository repository;
        
        @Test
        public void getAllCustomerTest() {
        
        List<Customer> customers = repository.findAll();
        
        for(Customer c : customers) {
            System.out.println(c);
        }
        
        }
    }

    当run测试类的H2DB 会首先执行放在 src/test/resource  下面的SQL文件,准备好测试数据。

    在 @Test 方法里就可以测试程序的逻辑了。

    源码如下,请笑纳 :)

    https://github.com/XLuffyStory/springboot-h2DB-test

  • 相关阅读:
    Web2.0技能评测
    [收藏]流程设计和优化原则
    [读书笔记1] 卓有成效的管理者(彼得.德鲁克)
    [读书笔记3] 卓有成效的管理者聚焦贡献
    [读书笔记2] 卓有成效的管理者管理时间
    动态生成的Web软件 应该如何设计???
    Logs
    JQuery推荐插件(200+)
    Spring AOP 实例
    《JavaScript凌厉开发Ext详解与实践》一书说了些什么
  • 原文地址:https://www.cnblogs.com/luffystory/p/11160847.html
Copyright © 2011-2022 走看看