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

更详细的对比见官网页面: http://www.h2database.com/html/features.html#comparison
下面是开发入门步骤:
一、maven中添加依赖项
12 com.h2database 3h2 41.3.176 5
二、Spring配置文件
a) 数据源配置
13 4 135 <!-- 内存模式 --> 6 127 <!-- 文件模式 --> 8 <!-- --> 9 10 11
注:密码不要留空(可以根据需要修改成其它值),否则运行时会报" 用户名、密码错之类"的Error
b) 初始化数据库脚本
1 <!-- 初始化数据表结构 --> 24 5 6
配置这个以后,每次应用启动前,会先执行create-table.sql,然后再执行import-data.sql,十分方便测试前,先初始化db环境
c) hibernate支持
13 4 5 96
8com.cnblogs.yjmyzz.entity 710 1411
13classpath*:hibernate/**/*.hbm.xml 1215 2716 26org.hibernate.dialect.H2Dialect 17 <!--thread --> 18true 19true 20true 213 2220 2320 24false 25
关键是16行,数据库方言的设置
d)mybatis分页插件设置
12 3 4 5 6 7 158
1410 1312
关键是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/ ,如需转载,请注明出处,否则将追究法律责任。