在Spring中使用嵌入式數據庫-H2

  • Spring3以後開始支持嵌入式數據庫,嵌入式數據庫目前在市面上有好多種,HSQL,DERBY,H2...今天就主要講一下h2的使用

    對於一個數據庫產品來說,主要就是如何存儲數據和讀取數據了。所謂嵌入式就是直接運行在項目中,不需要安裝額外的產品。說白了就是一個jar包,可以隨項目啟動和結束而結束,它主要有以下特點:

優點:

  • 小而簡,但是可以存儲的數據還是很大,大概有512G左右;
  • 不用多餘的安裝,用來做測試和一些小工具最好不過了
  • 一些常見的關係型數據庫,如mysql的大多數功能它全都支持,如事務,搭建集群等
  • 它是由Java開發的jar包,所以和其他的Jar應用一樣,高可移植性

缺點:

  • 由於它是內存型的,所以並不會持久化數據

這的運行方式主要有兩種:

  1. 和MySql很相似的服務器模式,運行起來後,可以連接多個實例,下載地址http://www.h2database.com/html/main.html
  2. 使用內嵌入到應用程序中,因為它是一個jar包,所以放應用程序中就可以了,但是它只能連接一個實例,也就是隻能在當前應用程序中連接,不能在其他應用中操作(主要講解這種模式)

接下來我們就使用SpringJdbc連接數據庫進行操作,當然其他orm框架也可以,使用SpringJdbc是為了簡化代碼

運行環境:

JDK1.8+Spring4以上

  • maven引入依賴(當然Spring相關的依賴是必須,)
<code>    <dependency>
<groupid>com.h2database/<groupid>
<artifactid>h2/<artifactid>
<version>1.3.172/<version>
/<dependency>
<dependency>
<groupid>org.springframework/<groupid>
<artifactid>spring-core/<artifactid>
<version>5.1.10.RELEASE/<version>
/<dependency>
<dependency>
<groupid>org.springframework/<groupid>
<artifactid>spring-beans/<artifactid>
<version>5.1.10.RELEASE/<version>
/<dependency>
<dependency>
<groupid>org.springframework/<groupid>
<artifactid>spring-context/<artifactid>
<version>5.1.10.RELEASE/<version>
/<dependency>

<dependency>
<groupid>org.springframework/<groupid>
<artifactid>spring-jdbc/<artifactid>
<version>5.1.10.RELEASE/<version>
/<dependency>/<code>


  • 配置Spring的配置文件
<code>
<beans> xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd">



<embedded-database>




/<embedded-database>


<bean>
<property>
/<bean>
/<beans>/<code>


  • 注意這裡的這兩個sql,一個是用來初始化數據庫,另一個就是用來添加數據,一定要注意順序,當然,寫在一個sql文件中也可以
<code>--    h2-schame.sql
drop table if exists teacher ;

-- 創建表
create table teacher(
id int primary key auto_increment,
name varchar(20),
age int
);/<code>


<code> -- 插入表數據 h2-data.sql
insert into teacher(name,age) values('張老師',23);
insert into teacher(name,age) values('李老師',24);/<code>


這裡的datasource是通過jdbc命名空間定義的,因為我們選擇模式是內嵌式運行。一個最簡單的事情要明白,只有在這個應用運行中,才會訪問到數據庫,其他時間是不能使用外部工具連接的,比如idea的datasource工具

在Spring中使用嵌入式數據庫-H2

  • 實體類
<code>public class Teacher {
private int id;
private String name;
private int age;

//省略set和get
}/<code>
  • 測試代碼
<code>public static void main(String[] args) {

ApplicationContext context = new ClassPathXmlApplicationContext("classpath:application.xml");
JdbcTemplate jdbcTemplate = context.getBean("jdbcTemplate", JdbcTemplate.class);

String selectSql = "select * from teacher";

List query = jdbcTemplate.query(selectSql, new RowMapper() {
@Nullable
@Override
public Object mapRow(ResultSet resultSet, int i) throws SQLException {
Teacher teacher = new Teacher();
teacher.setId(resultSet.getInt(1));
teacher.setName(resultSet.getString(2));
teacher.setAge(resultSet.getInt(3));
return teacher;
}
});

query.forEach(o -> System.out.println(o));
}/<code>

以下就是運行結果,當然你能看到一些關於這個datasource的信息

在Spring中使用嵌入式數據庫-H2

我們給程序一個不退出的代碼,讓它一直運行(如果是一個web應用,只要啟動,就會一直運行),使用idea連接一下這個數據庫

在Spring中使用嵌入式數據庫-H2

但是你通過這個工具是不能看見teahcer表的,同樣,你通過這個工具添加的表和數據也不會使用程序取到的,因為它本身就是連接實例之間是分開的,這樣做是很安全的。

如果是使用SpringBoot的話:


運行環境:SpirngBoot+SpringJdbc

這裡並不創建一個新的SpringBoot項目,而是使用Java註解的方式來註冊bean(在SpirngBoot的環境就可以這樣用)

  • 配置類
<code>package cn.lyn4ever.bean;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;

import javax.sql.DataSource;

@Configuration
public class BeanConfig {

@Bean
public DataSource dataSource() {
try {
EmbeddedDatabaseBuilder dbBuilder = new EmbeddedDatabaseBuilder();
return dbBuilder.setType(EmbeddedDatabaseType.H2)
.addScripts("classpath:sql/h2-schema.sql", "classpath:sql/h2-data.sql")
.build();
} catch (Exception e) {
System.out.println("創建數據庫連接失敗");
return null;
}
}

@Bean
public JdbcTemplate jdbcTemplate(){
JdbcTemplate jdbcTemplate = new JdbcTemplate();
jdbcTemplate.setDataSource(dataSource());
return jdbcTemplate;
}
}

/<code>


  • 測試類
<code> public static void main(String[] args) {

ApplicationContext context = new AnnotationConfigApplicationContext(BeanConfig.class);

JdbcTemplate jdbcTemplate = context.getBean("jdbcTemplate", JdbcTemplate.class);

String selectSql = "select * from teacher";

List query = jdbcTemplate.query(selectSql, new RowMapper() {
@Nullable
@Override
public Object mapRow(ResultSet resultSet, int i) throws SQLException {
Teacher teacher = new Teacher();
teacher.setId(resultSet.getInt(1));
teacher.setName(resultSet.getString(2));
teacher.setAge(resultSet.getInt(3));
return teacher;
}
});

query.forEach(o -> System.out.println(o));
}/<code>


在Spring中使用嵌入式數據庫-H2


分享到:


相關文章: