SpringBoot---h2嵌入式数据库

嵌入式数据库 
一、 添加依赖

          <dependency>    

                   <groupId>com.h2database</groupId>    

                   <artifactId>h2</artifactId>    

                  <scope>runtime</scope>  

          </dependency> 

二、 配置

        spring.datasource.url=jdbc:h2:~/test;AUTO_SERVER=TRUE;DB_CLOSE _ON_EXIT=FALSE                                                     spring.datasource.username=sa

        spring.datasource.password=

       注: 1."~"这个符号代表的就是当前登录到操作系统的用户对应的用户目录

                2.账号密码我们指定之后,就会自动创建 

       指定路径:     spring.datasource.url=jdbc:h2:file:D:/roncoo_h2/roncoo_spring_boot;AUTO_SERVER=TRUE;DB_CLOSE_ON_EXIT=FALSE 

       内存模式: spring.datasource.url=jdbc:h2:mem:test 

三、 进入控制台 
路径:http://localhost:8888/h2-console(密码为空)

项目结构如下:

application-dev.properties 配置文件:

#开发环境
server.port=8888

#MySql
#spring.datasource.url=jdbc:mysql://localhost:3306/springboot?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
#spring.datasource.username=root
#spring.datasource.password=root
#spring.datasource.driver-class-name=com.mysql.jdbc.Driver
#spring.jackson.time-zone=Asia/Chongqing

#h2
#
#   ~  代表用户的 家目录
#
#spring.datasource.url=jdbc:h2:~/test;AUTO_SERVER=TRUE;DB_CLOSE_ON_EXIT=FALSE
#
#    通过file 指定 本地数据库  所在的位置  lhg_h2 为数据库名称#
#    username  password 写上 多少  就会给我们创建一个带有用户密码的数据库
#
spring.datasource.url=jdbc:h2:file:F:/springboot_h2/lhg_h2;AUTO_SERVER=TRUE;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.username=sa
spring.datasource.password=

# JPA
spring.jpa.hibernate.ddl-auto=update
#显示 sql 语句
spring.jpa.show-sql=true 

dao接口层和Service层 没有改变可以参考上一篇博客的内容,测试类如下:

package com.nyist.h2;

import com.nyist.h2.dao.RoncooUserLogDao;
import com.nyist.h2.model.RoncooUserLog;
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.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.Date;
import java.util.List;

@RunWith(SpringRunner.class)
@SpringBootTest
public class H2ApplicationTests {

    @Autowired
    private RoncooUserLogDao roncooUserLogDao;

    @Test
    public void insert() {
        RoncooUserLog entity = new RoncooUserLog();
        entity.setUserName("无境");
        entity.setUserIp("192.168.0.1");
        entity.setCreateTime(new Date());
        roncooUserLogDao.save(entity);
    }

//    @Test
//    public void delete() {
//        roncooUserLogDao.delete(1);
//    }

    @Test
    public void update() {
        RoncooUserLog entity = new RoncooUserLog();
        entity.setId(2);
        entity.setUserName("无境2");
        entity.setUserIp("192.168.0.1");
        entity.setCreateTime(new Date());
        roncooUserLogDao.save(entity);
    }

//    @Test
//    public void select() {
//        RoncooUserLog result = roncooUserLogDao.findOne(1);
//        System.out.println(result);
//    }

    @Test
    public void select2() {
        List<RoncooUserLog> result = roncooUserLogDao.findByUserName("无境");
        System.out.println(result);
    }

    @Test
    public void select3() {
        List<RoncooUserLog> result = roncooUserLogDao.findByUserNameAndUserIp("无境", "192.168.0.1");
        System.out.println(result);
    }

    // 分页
    @Test
    public void queryForPage() {
        Pageable pageable = new PageRequest(0, 20, new Sort(new Sort.Order(Sort.Direction.DESC, "id")));
        Page<RoncooUserLog> result = roncooUserLogDao.findByUserName("无境", pageable);
        System.out.println(result.getContent());
    }

}

我们插入一条数据,在h2console 中查看结果如下:

可以看到 有一条数据插入进来了,证明我们嵌入式h2数据库成功,可以正常使用

我们在测试删除一天数据试试,运行结果如下:

至此h2嵌入式数据库引入成功。

Spring BootH2 数据库结合是一个常见的轻量级开发场景,H2 是一个内存型的嵌入式数据库,常用于快速原型开发和测试。下面是一个简单的 Spring Boot 应用使用 H2 的例子: 首先,在 `pom.xml` 文件中添加 H2 数据源依赖: ```xml <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <scope>runtime</scope> <!-- 只在运行时添加 --> </dependency> </dependencies> ``` 然后,配置数据源和 JPA 配置: ```java @Configuration @EnableJpaRepositories(basePackages = "com.example.demo.repository") // 指定仓库模块位置 public class DatabaseConfig { @Value("${spring.datasource.url}") private String url; @Value("${spring.datasource.username}") private String username; @Value("${spring.datasource.password}") private String password; @Bean public DataSource dataSource() { return new EmbeddedDatabaseBuilder() .setType(EmbeddedDatabaseType.H2) // 使用H2 .addScript("schema.sql") // 加载初始化脚本 .build(); } @Bean public PlatformTransactionManager transactionManager(DataSource dataSource) { return new JpaTransactionManager(entityManagerFactory(dataSource)); } @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) { HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); Map<String, Object> jpaProperties = new HashMap<>(); jpaProperties.put("hibernate.dialect", H2Dialect.class); jpaProperties.put("hibernate.show_sql", true); // 显示SQL日志 LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean(); factory.setDataSource(dataSource); factory.setJpaVendorAdapter(vendorAdapter); factory.setPackagesToScan("com.example.demo.entity"); // 扫描实体类包 factory.setJpaProperties(jpaProperties); return factory; } } ``` 在这个例子中,你需要创建一个 `schema.sql` 脚本来定义数据库结构。现在你可以创建一个简单的实体类 (`User.java`),并创建对应的 Repository 接口 (`UserRepository.java`)。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值