Use embedded database in Spring -H2

  • Spring3 later began to support embedded database, embedded database currently in the market have a good variety, HSQL, DERBY, H2 ... h2 today to talk about the main use
    for a database products, mainly how to store and read data the data. The so-called embedded in the project is run directly, no need to install additional products. It means a jar package, you can start and end with the project ended, it has the following characteristics:

advantage:

  • Small and simple, but the data can be stored is still very large, probably about 512G;
  • No extra installation, used for testing and some small tools better and better
  • Some common relational databases such as mysql most of the features of all support it, such as transactions, clusters and other structures
  • It was developed by the Java jar packets, and other applications, like Jar, high portability

Disadvantages:

  • Because it is a type of memory, and thus would not persistent data

This mode of operation are mainly two:

  1. MySql very similar and server mode, after running, can be connected to a plurality of instances, Download http://www.h2database.com/html/main.html
  2. The use of embedded applications, because it is a jar package, it can be placed in the application, but it is only one instance of the connection, i.e. only during the current application, can not operate in other applications ( mainly on this model)

    Next, we use the database connection SpringJdbc operation, of course, also be other orm frame, is used to simplify the code SpringJdbc

Operating environment:

JDK1.8+Spring4以上
  • maven introduced dependence (dependence is of course related Spring must,)
    <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>
        <!-- 2.Spring dao依赖 -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.1.10.RELEASE</version>
        </dependency>
  • Configuring Spring configuration file
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/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">


    <!--当然是配置datasource了-->
    <jdbc:embedded-database id="dataSource" type="H2">
        <!--一定要是先DDL,即数据库定义语言-->
        <jdbc:script location="classpath:sql/h2-schema.sql"/>
        <!--然后才是DML,数据库操作语言-->
        <jdbc:script location="classpath:sql/h2-data.sql" encoding="UTF-8"/>
    </jdbc:embedded-database>

    <!--定义springjdbctemplate-->
    <bean class="org.springframework.jdbc.core.JdbcTemplate" id="jdbcTemplate">
        <property name="dataSource" ref="dataSource"/>
    </bean>
</beans>
  • Note that these two sql, one is used to initialize the database, and the other is used to add data, must pay attention to the order, of course, write in a sql file can also be
--  h2-schame.sql
drop table if exists teacher ;

-- 创建表
create table teacher(
    id int  primary key auto_increment,
    name varchar(20),
  age int
);
 -- 插入表数据 h2-data.sql
insert into teacher(name,age) values('张老师',23);
insert into teacher(name,age) values('李老师',24);

Here is the datasource jdbc namespace by definition, because we chose to run the model is embedded. One of the easiest things to understand that only in this application is running, the only access to the database, other times can not be connected using an external tool, such as the idea datasource tool

spring

  • Entity class
public class Teacher {
    private int id;
    private String name;
    private int age;

//省略set和get
}
  • Test 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));
    }

Here's operating results, of course, you can see some information about the datasource of
spring
the code we give the program an exit, it has been run (if it is a web application, as long as the start, would have been run), using the idea about this connection database

spring

But you can not see through this tool teahcer table, the same, you add this tool tables and data will not be using the program to take, because it itself is the connection between the instances are separate, it is safe to do so .

If you are using SpringBoot words:

Operating environment: SpirngBoot + SpringJdbc

Here SpringBoot does not create a new project, but the use of Java annotations ways to register bean (environment SpirngBoot would be so used)

  • Configuration class
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;
    }
}
  • Test category
 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));
    }

Spring Series Study Notes

Guess you like

Origin www.cnblogs.com/Lyn4ever/p/12216141.html