SpringBoot+Spring Data JPA integrates H2 database

foreword

  • H2 database is an open source relational database. H2 is written in java language, not limited by the platform, supports both online and embedded versions, has good compatibility, and supports fairly standard sql standards
  • Provide JDBC, ODBC access interfaces, and provide a very friendly web-based database management interface

Official website: http://www.h2database.com/

Maven dependencies

<!--jpa-->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!--web-->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--h2-->
<dependency>
	<groupId>com.h2database</groupId>
	<artifactId>h2</artifactId>
	<scope>runtime</scope>
</dependency>
<!--lombok-->
<dependency>
	<groupId>org.projectlombok</groupId>
	<artifactId>lombok</artifactId>
	<optional>true</optional>
</dependency>

controls

@RestController
public class UserController {
    
    

    @Autowired
    UserRepository userRepository;

   @RequestMapping("/list")
    public List<User> findAll(){
    
    
       List<User> userList = userRepository.findAll();
       return userList;
   }

   @RequestMapping("/save")
   public String save(User user){
    
    
       userRepository.save(user);
       return "保存成功";
   }

   @RequestMapping("/update")
   public String update(User user){
    
    
       userRepository.save(user);
       return "更新成功";
   }

   @RequestMapping("/delete")
   public String delete(Integer id){
    
    
       userRepository.deleteById(id);
       return "删除成功";
   }

}

entity class

@AllArgsConstructor
@NoArgsConstructor
@Entity
@Data
@Table(name = "user")
public class User {
    
    

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    private String name;

    private Integer age;

    private Integer gender;

}

Repository

@Repository
public interface UserRepository extends JpaRepository<User,Integer> {
    
    

}

database script file

Schema (DDL) Script Resource Reference
schema.sql

drop table if exists user;
create table user(
    `id` int primary key auto_increment,
    `name` varchar(255) not null,
    `age` int not null,
    `gender` int not null
);

Data (DML) Script Resource Reference

insert into user (id,name,age,gender) values (null, '张三',18,1);
insert into user (id,name,age,gender) values (null, '李四',19,1);
insert into user (id,name,age,gender) values (null, '王五',20,1);
insert into user (id,name,age,gender) values (null, '李六',21,1);

configuration file

#---------服务器配置-----------
server.port=8080

#---------数据源配置-----------
spring.datasource.driver-class-name=org.h2.Driver
spring.datasource.url=jdbc:h2:file:./data;AUTO_SERVER=TRUE
spring.datasource.username=sa
spring.datasource.password=
#架构 (DDL) 脚本资源引用
spring.datasource.schema=classpath:db/schema.sql
#数据 (DML) 脚本资源引用
spring.datasource.data=classpath:db/data.sql
#SQL脚本编码
spring.datasource.sql-script-encoding=UTF-8
#初始化模式
spring.datasource.initialization-mode=ALWAYS
#如果在初始化数据库时发生错误,是否停止
spring.datasource.continue-on-error=true

#---------JPA配置-------------
#要操作的目标数据库
spring.jpa.database=h2
#控制台显示SQL语句
spring.jpa.show-sql=true
#更新或者创建数据表结构
spring.jpa.hibernate.ddl-auto=update
#物理命名策略的完全限定名称
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
#是否在启动时初始化架构
spring.jpa.generate-ddl=true

#----------H2配置--------------
#http://localhost:8080/h2-console
spring.h2.console.path=/h2-console
#启用控制台
spring.h2.console.enabled=true

Startup project

Access the H2 database

Visit: http://localhost:8080/h2-console

View all data

Since the database script is set, the SpringBoot project will run the sql file every time it starts

#架构 (DDL) 脚本资源引用
spring.datasource.schema=classpath:db/schema.sql
#数据 (DML) 脚本资源引用
spring.datasource.data=classpath:db/data.sql
#SQL脚本编码
spring.datasource.sql-script-encoding=UTF-8
#初始化模式
spring.datasource.initialization-mode=ALWAYS
#如果在初始化数据库时发生错误,是否停止
spring.datasource.continue-on-error=true

H2 database file

The database file location spring.datasource.urlis specified by

spring.datasource.url=jdbc:h2:file:./data;AUTO_SERVER=TRUE

Operation mode

1. Run in memory The
database only runs in memory. After closing the connection, the database will be emptied, which is suitable for the test environment
. Connection string:

jdbc:h2:mem:DBName;DB_CLOSE_DELAY=-1

2. The embedded
database is persistently stored as a single file
connection string:

jdbc:h2:file:~/.h2/DBName;AUTO_SERVER=TRUE

3. Service Mode
H2 supports three service modes:

  • web server: This mode of operation supports using a browser to access the H2 Console
  • TCP server: supports client/server connection
  • PG server: supports PostgreSQL client

Example of connection string to start tcp service:

jdbc:h2:tcp://localhost/~/test 使用用户主目录
jdbc:h2:tcp://localhost//data/test 使用绝对路径

4. Connection String Parameters

  • DB_CLOSE_DELAY: ask to not close the database after the last connecting connection is disconnected

  • MODE=MySQL: Compatibility mode, H2 is compatible with multiple databases, the value can be: DB2, Derby, HSQLDB, MSSQLServer, MySQL, Oracle, PostgreSQL

  • AUTO_RECONNECT=TRUE: Automatically reconnect after connection loss

  • AUTO_SERVER=TRUE: Enable automatic mixing mode, allowing multiple connections to be opened, this parameter does not support running mode in memory

  • TRACE_LEVEL_SYSTEM_OUT、TRACE_LEVEL_FILE: Output the trace log to the console or file, the value is 0 for OFF, 1 for ERROR (default), 2 for INFO, and 3 for DEBUG

  • SET TRACE_MAX_FILE_SIZE mb: Set the size of the trace log file, the default is 16M

Guess you like

Origin blog.csdn.net/qq_31762741/article/details/122967384