ITPub博客

首页 > IT职业 > IT职场 > H2 Database入门

H2 Database入门

IT职场 作者:wangsys 时间:2021-09-09 09:14:17 0 删除 编辑

H2 Database做为轻量级的内嵌数据库,功能十分强大,而且运行时只需要一个jar包即可,下表是官网的描述:

图片描述

更详细的对比见官网页面: http://www.h2database.com/html/features.html#comparison

 

下面是开发入门步骤:

一、maven中添加依赖项

 1         
2             com.h2database
3             h2
4             1.3.176            
5         

二、Spring配置文件

a) 数据源配置

 1     
 3         
 4             
 5                 <!-- 内存模式 -->
 6                 
 7                 <!-- 文件模式 -->
 8                 <!--  -->                 
 9                 
10                 
11             
12         
13     

注:密码不要留空(可以根据需要修改成其它值),否则运行时会报" 用户名、密码错之类"的Error

b) 初始化数据库脚本

1     <!-- 初始化数据表结构 -->
2     
4         
5         
6     

配置这个以后,每次应用启动前,会先执行create-table.sql,然后再执行import-data.sql,十分方便测试前,先初始化db环境

 

c) hibernate支持


 1     
 3         
 4         
 5             
 6                 com.cnblogs.yjmyzz.entity
 7             
 8         
 9         
10             
11                 classpath*:hibernate/**/*.hbm.xml
12             
13         
14         
15             
16                 org.hibernate.dialect.H2Dialect
17                 <!-- thread -->
18                 true
19                 true
20                 true
21                 3
22                 20
23                 20
24                 false
25             
26         
27     

关键是16行,数据库方言的设置

 

d)mybatis分页插件设置

 1     
 2         
 3         
 4         
 5         
 6         
 7             
 8                 
10                     
12                 
13             
14         
15     

关键是11行,方言的设置

 

三、代码测试:

 1     @Test
 2     public void testConnH2() throws SQLException, IOException {
 3         ApplicationContext ctx = new ClassPathXmlApplicationContext(
 4                 "spring-datasource.xml");
 5         OrderMapper orderMapper = ctx.getBean(OrderMapper.class);
 6         List orders = orderMapper.getAllOrder();
 7         for (TOrder o : orders) {
 8             System.out.println(o.getClientname());
 9         }
10         ((ClassPathXmlApplicationContext) ctx).close();
11 
12     }

上面演示了mybatis结合H2的使用示例

 

四、控制台界面

H2还提供了一个可视化界面

图片描述

Windows开始菜单->H2->H2 console,点击connect连接就行了

图片描述

有不熟悉的函数啥的,直接在SQL输入区,输入 help,然后run,下面就有帮助信息 

完整的示例代码下载  (基于struts2的rest-plugin showcase,增加了mybatis3 + hibernate4 + spring4 + velocity支持)

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/3244/viewspace-2808833/ ,如需转载,请注明出处,否则将追究法律责任。

请登录后发表评论 登录
全部评论

注册时间:2019-09-06

  • 博文量
    94
  • 访问量
    7081