有时候为了做些测试需要创建数据库及相关表,安装MySQL等轻量数据库虽然简单但还是有点麻烦?而且用于自己临时测试的数据库对象一般不会被多次使用,还是浪费?内存数据库结合ORM可以很好解决这个问题。

  H2,Derby,HSQLDB 都是很好的内存数据库,大家可以根据自己的需要选择:

  H2 Derby HSQLDB MySQL PostgreSQL
Pure Java Yes Yes Yes No No
Memory Mode Yes Yes Yes No No
Encrypted Database Yes Yes Yes No No
ODBC Driver Yes No No Yes Yes
Fulltext Search Yes No No Yes Yes
Multi Version Concurrency Yes No Yes Yes Yes
Footprint (jar/dll size) ~1 MB ~2 MB ~1 MB ~4 MB ~6 MB

  Spring已经对使用内存数据库提供很完美的支持:

  配置类:

 @Configuration
public class HibernateConfiguration {
@Autowired
private DataSource dataSource;
@Bean
public AnnotationSessionFactoryBean sessionFactoryBean() {
Properties props = new Properties();
//配置H2方言
props.put("hibernate.dialect", H2Dialect.class.getName());
props.put("hibernate.format_sql", "true");
AnnotationSessionFactoryBean bean = new AnnotationSessionFactoryBean();
bean.setAnnotatedClasses(new Class[]{Item.class, Order.class});
bean.setHibernateProperties(props);
bean.setDataSource(this.dataSource);
bean.setSchemaUpdate(true);
return bean;
}
@Bean
public HibernateTransactionManager transactionManager() {
return new HibernateTransactionManager( sessionFactoryBean().getObject() );
} /**
* 设置内存数据库类型,可以更改为Derby,HSQL
* @return
*/
@Bean
public DataSource dataSource(){
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
builder.setType(EmbeddedDatabaseType.H2);
return builder.build();
}

  然后我们可以写entity类及相关测试用例:

  Order Entity类:

 @Entity
@Table(name="T_ORDER")
public class Order { @Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id; private String customer; @OneToMany(cascade=CascadeType.ALL)
@JoinColumn(name="ORDER_ID")
private Collection<Item> items = new LinkedHashSet<Item>();
/**
* @return the customer
*/
public String getCustomer() {
return customer;
}
/**
* @param customer the customer to set
*/
public void setCustomer(String customer) {
this.customer = customer;
}
/**
* @return the items
*/
public Collection<Item> getItems() {
return items;
}
/**
* @param items the items to set
*/
public void setItems(Collection<Item> items) {
this.items = items;
}
/**
* @return the id
*/
public Long getId() {
return id;
} }

  Item Entity类

 @Entity
public class Item {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
@ManyToOne
private Order order;
private String product;
private double price;
private int quantity;
/**
* @return the order
*/
public Order getOrder() {
return order;
}
/**
* @return the product
*/
public String getProduct() {
return product;
}
/**
* @param product
* the product to set
*/
public void setProduct(String product) {
this.product = product;
}
/**
* @return the price
*/
public double getPrice() {
return price;
}
/**
* @param price
* the price to set
*/
public void setPrice(double price) {
this.price = price;
}
/**
* @return the quantity
*/
public int getQuantity() {
return quantity;
}
/**
* @param quantity
* the quantity to set
*/
public void setQuantity(int quantity) {
this.quantity = quantity;
}
/**
* @return the id
*/
public Long getId() {
return id;
}
}

  Junit测试类

 @ContextConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
public class OrderPersistenceTests {
@Autowired
private SessionFactory sessionFactory;
@Test
@Transactional
public void testSaveOrderWithItems() throws Exception {
Session session = sessionFactory.getCurrentSession();
Order order = new Order();
order.getItems().add(new Item());
session.save(order);
session.flush();
assertNotNull(order.getId());
}
@Test
@Transactional
public void testSaveAndGet() throws Exception {
Session session = sessionFactory.getCurrentSession();
Order order = new Order();
order.getItems().add(new Item());
session.save(order);
session.flush();
// Otherwise the query returns the existing order (and we didn't set the
// parent in the item)...
session.clear();
Order other = (Order) session.get(Order.class, order.getId());
assertEquals(1, other.getItems().size());
assertEquals(other, other.getItems().iterator().next().getOrder());
}
@Test
@Transactional
public void testSaveAndFind() throws Exception {
Session session = sessionFactory.getCurrentSession();
Order order = new Order();
Item item = new Item();
item.setProduct("foo");
order.getItems().add(item);
session.save(order);
session.flush();
// Otherwise the query returns the existing order (and we didn't set the
// parent in the item)...
session.clear();
Order other = (Order) session
.createQuery( "select o from Order o join o.items i where i.product=:product")
.setString("product", "foo").uniqueResult();
assertEquals(1, other.getItems().size());
assertEquals(other, other.getItems().iterator().next().getOrder());
}
}

Spring使用内存数据库的更多相关文章

  1. Spring使用内存数据库二

    在上篇<Spring 使用内存数据库>中我们使用Hibernate作为ORM的框架,直接调用Hibernate的API进行相关的持久化操作,但在实际项目中,可能会由于公司规定等原因要求统一 ...

  2. 从Spring看Web项目开发

    之前简单介绍过Spring框架,本文换个角度重新诠释Spring.使用Java语言开发的项目,几乎都绕不过Spring,那么Spring到底是啥,为何被如此广泛的应用,下面从以下两个问题出发来剖析Sp ...

  3. 基于mockito做有效的单元测试

    概述 本文讲解的主要是有效和单元的思想,并不是说如何编写单元测试,用于改善和提高开发效率.编码风格.编码可读性和单测效率,不盲目追求覆盖率. 背景 现在很多单元测试只是利用@Test注解把代码或者整个 ...

  4. 2018-08-20 中文代码之Spring Boot集成H2内存数据库

    续前文: 中文代码之Spring Boot添加基本日志, 源码库地址相同. 鉴于此项目中的数据总量不大(即使万条词条也在1MB之内), 当前选择轻量级而且配置简单易于部署的H2内存数据库比较合理. 此 ...

  5. 中文代码之Spring Boot集成H2内存数据库

    续前文: 中文代码之Spring Boot添加基本日志, 源码库地址相同. 鉴于此项目中的数据总量不大(即使万条词条也在1MB之内), 当前选择轻量级而且配置简单易于部署的H2内存数据库比较合理. 此 ...

  6. 在Spring Boot中使用内存数据库

    文章目录 H2数据库 HSQLDB Apache Derby SQLite 在Spring Boot中使用内存数据库 所谓内存数据库就是可以在内存中运行的数据库,不需要将数据存储在文件系统中,但是相对 ...

  7. 在Spring Boot使用H2内存数据库

    文章目录 添加依赖配置 数据库配置 添加初始数据 访问H2数据库 在Spring Boot使用H2内存数据库 在之前的文章中我们有提到在Spring Boot中使用H2内存数据库方便开发和测试.本文我 ...

  8. Java Spring mvc 操作 Redis 及 Redis 集群

    本文原创,转载请注明:http://www.cnblogs.com/fengzheng/p/5941953.html 关于 Redis 集群搭建可以参考我的另一篇文章 Redis集群搭建与简单使用 R ...

  9. Spring Batch在大型企业中的最佳实践

    在大型企业中,由于业务复杂.数据量大.数据格式不同.数据交互格式繁杂,并非所有的操作都能通过交互界面进行处理.而有一些操作需要定期读取大批量的数据,然后进行一系列的后续处理.这样的过程就是" ...

随机推荐

  1. 解决Android中图片圆角——.9图

    目录:  一.问题概述 二..9图介绍 三..9图制作 1.开发工具 2.打开图片 3.制作图片 4.保存图片 一.问题概述 在html开发中,可以通过设置css的border-radius来设置圆角 ...

  2. Python3爬虫:利用Fidder抓取手机APP的数据

    1.什么是Fiddler? Fiddler是一个http协议调试代理工具,它能够记录并检查所有你的电脑和互联网之间的http通讯,设置断点,查看所有的“进出”Fiddler的数据(指cookie,ht ...

  3. HDU 4548 美素数 素数题解

    本题就是能够直接打表的,推断能否够打表也须要技巧的: 1 推断最大的数值为1000000.百万下面的数打表都是能够的 2 能够线性预处理好.使用素数筛子法是能够接近线性预处理的. 故此能够打表了. 须 ...

  4. NLP系列(4)_朴素贝叶斯实战与进阶(转)

    http://blog.csdn.net/han_xiaoyang/article/details/50629608 作者: 寒小阳 && 龙心尘 时间:2016年2月. 出处:htt ...

  5. 转:[大数据竞赛]协同过滤在这个问题上是否work

    http://bbs.aliyun.com/read/154433.html?spm=5176.7189909.0.0.gzyohy&fpage=2 看到主办方之前发的一篇文章里提到,这个购买 ...

  6. 【转】深入理解line-height

    原文: http://www.cnblogs.com/dolphinX/p/3236686.html https://www.cnblogs.com/yangjie-space/p/4858132.h ...

  7. thinkphp5在URL地址里隐藏模块名

    新的Thinkphp5的路由功能很强大,完全可以自定义以满足自己的要求   ThinkPHP5.0的路由规则如下:http://serverName/index.php/module/controll ...

  8. artTemplate子模板include

    art.Template:https://github.com/aui/art-template 下面来实现利用模版来实现递归调用生成tree <script type="text/h ...

  9. Javascript 闭包(Closures)

    本文内容 闭包 闭包和引用 参考资料 闭包是 JavaScript 的重要特性,非常强大,可用于执行复杂的计算,可并不容易理解,尤其是对之前从事面向对象编程的人来说,对 JavaScript 认识和编 ...

  10. AngularJs - Javascript MVC 框架

    在2012年6月google发布了AngularJs 1.0稳定版, 并宣称:AngularJS可以让你扩展HTML的语法,以便清晰.简洁地表示应用程序中的组件,并允许将标准的HTML作为你的模板语言 ...