有时候为了做些测试需要创建数据库及相关表,安装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已经对使用内存数据库提供很完美的支持:

  配置类:

  1. @Configuration
  2. public class HibernateConfiguration {
  3. @Autowired
  4. private DataSource dataSource;
  5. @Bean
  6. public AnnotationSessionFactoryBean sessionFactoryBean() {
  7. Properties props = new Properties();
  8. //配置H2方言
  9. props.put("hibernate.dialect", H2Dialect.class.getName());
  10. props.put("hibernate.format_sql", "true");
  11. AnnotationSessionFactoryBean bean = new AnnotationSessionFactoryBean();
  12. bean.setAnnotatedClasses(new Class[]{Item.class, Order.class});
  13. bean.setHibernateProperties(props);
  14. bean.setDataSource(this.dataSource);
  15. bean.setSchemaUpdate(true);
  16. return bean;
  17. }
  18. @Bean
  19. public HibernateTransactionManager transactionManager() {
  20. return new HibernateTransactionManager( sessionFactoryBean().getObject() );
  21. }
  22.  
  23. /**
  24. * 设置内存数据库类型,可以更改为Derby,HSQL
  25. * @return
  26. */
  27. @Bean
  28. public DataSource dataSource(){
  29. EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
  30. builder.setType(EmbeddedDatabaseType.H2);
  31. return builder.build();
  32. }

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

  Order Entity类:

  1. @Entity
  2. @Table(name="T_ORDER")
  3. public class Order {
  4.  
  5. @Id
  6. @GeneratedValue(strategy=GenerationType.AUTO)
  7. private Long id;
  8.  
  9. private String customer;
  10.  
  11. @OneToMany(cascade=CascadeType.ALL)
  12. @JoinColumn(name="ORDER_ID")
  13. private Collection<Item> items = new LinkedHashSet<Item>();
  14. /**
  15. * @return the customer
  16. */
  17. public String getCustomer() {
  18. return customer;
  19. }
  20. /**
  21. * @param customer the customer to set
  22. */
  23. public void setCustomer(String customer) {
  24. this.customer = customer;
  25. }
  26. /**
  27. * @return the items
  28. */
  29. public Collection<Item> getItems() {
  30. return items;
  31. }
  32. /**
  33. * @param items the items to set
  34. */
  35. public void setItems(Collection<Item> items) {
  36. this.items = items;
  37. }
  38. /**
  39. * @return the id
  40. */
  41. public Long getId() {
  42. return id;
  43. }
  44.  
  45. }

  Item Entity类

  1. @Entity
  2. public class Item {
  3. @Id
  4. @GeneratedValue(strategy = GenerationType.AUTO)
  5. private Long id;
  6. @ManyToOne
  7. private Order order;
  8. private String product;
  9. private double price;
  10. private int quantity;
  11. /**
  12. * @return the order
  13. */
  14. public Order getOrder() {
  15. return order;
  16. }
  17. /**
  18. * @return the product
  19. */
  20. public String getProduct() {
  21. return product;
  22. }
  23. /**
  24. * @param product
  25. * the product to set
  26. */
  27. public void setProduct(String product) {
  28. this.product = product;
  29. }
  30. /**
  31. * @return the price
  32. */
  33. public double getPrice() {
  34. return price;
  35. }
  36. /**
  37. * @param price
  38. * the price to set
  39. */
  40. public void setPrice(double price) {
  41. this.price = price;
  42. }
  43. /**
  44. * @return the quantity
  45. */
  46. public int getQuantity() {
  47. return quantity;
  48. }
  49. /**
  50. * @param quantity
  51. * the quantity to set
  52. */
  53. public void setQuantity(int quantity) {
  54. this.quantity = quantity;
  55. }
  56. /**
  57. * @return the id
  58. */
  59. public Long getId() {
  60. return id;
  61. }
  62. }

  Junit测试类

  1. @ContextConfiguration
  2. @RunWith(SpringJUnit4ClassRunner.class)
  3. public class OrderPersistenceTests {
  4. @Autowired
  5. private SessionFactory sessionFactory;
  6. @Test
  7. @Transactional
  8. public void testSaveOrderWithItems() throws Exception {
  9. Session session = sessionFactory.getCurrentSession();
  10. Order order = new Order();
  11. order.getItems().add(new Item());
  12. session.save(order);
  13. session.flush();
  14. assertNotNull(order.getId());
  15. }
  16. @Test
  17. @Transactional
  18. public void testSaveAndGet() throws Exception {
  19. Session session = sessionFactory.getCurrentSession();
  20. Order order = new Order();
  21. order.getItems().add(new Item());
  22. session.save(order);
  23. session.flush();
  24. // Otherwise the query returns the existing order (and we didn't set the
  25. // parent in the item)...
  26. session.clear();
  27. Order other = (Order) session.get(Order.class, order.getId());
  28. assertEquals(1, other.getItems().size());
  29. assertEquals(other, other.getItems().iterator().next().getOrder());
  30. }
  31. @Test
  32. @Transactional
  33. public void testSaveAndFind() throws Exception {
  34. Session session = sessionFactory.getCurrentSession();
  35. Order order = new Order();
  36. Item item = new Item();
  37. item.setProduct("foo");
  38. order.getItems().add(item);
  39. session.save(order);
  40. session.flush();
  41. // Otherwise the query returns the existing order (and we didn't set the
  42. // parent in the item)...
  43. session.clear();
  44. Order other = (Order) session
  45. .createQuery( "select o from Order o join o.items i where i.product=:product")
  46. .setString("product", "foo").uniqueResult();
  47. assertEquals(1, other.getItems().size());
  48. assertEquals(other, other.getItems().iterator().next().getOrder());
  49. }
  50. }

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. Ios开发之协议protocol

    Protocol是ios开发中的一个难点也是一个重点,要想使用好,或者理解好它,可能需要时间的累积.今天我们就通过一个例子来简单的看一下,怎么样使用protocol. 我们今天用的例子就是模拟电脑插入 ...

  2. iOS runtime探究(三): 从runtime開始理解OC的属性property

    你要知道的runtime都在这里 转载请注明出处 http://blog.csdn.net/u014205968/article/details/67639303 本文主要解说runtime相关知识, ...

  3. 性能测试vs负载测试vs压力测试

    下面我们主要介绍性能测试.负载测试和压力测试. 效率作为ISO 9126内部和外部质量的重要质量属性之一,其含义是在规定条件下,相对于所用的资源的数量,软件产品可提供适当性能的能力.资源可能包括其他软 ...

  4. Provider Pattern for Beginners in .net

    Download ProviderPattern.zip Introduction Provider pattern allows the developers to create pluggable ...

  5. VC++ MFC应用程序项目文件2.cpp

    //GameServer.cpp: 定义应用程序的入口点. // #include "stdafx.h" #include "GameServer.h" #de ...

  6. VS2017专业版使用最新版Qt5.9.2教程

    VS2017专业版使用最新版Qt5.9.2教程(最新教材) 最近三天一直在安装Qt5.9.2,为了能够在自己专业版的VS2017上面使用?可以算是花费了不少的功夫.但是一路上并不是很顺利,就在刚才,终 ...

  7. JS调试必备的5个debug技巧_javascript技巧

    JS调试必备的debug调试javascript技巧 1. debugger; 我以前也说过,你可以在JavaScript代码中加入一句debugger;来手工造成一个断点效果.需要带有条件的断点吗? ...

  8. 转载:Unicode和Utf-8有何区别 转载自知乎 原文作者不详

    作者:于洋链接:https://www.zhihu.com/question/23374078/answer/69732605来源:知乎著作权归作者所有.商业转载请联系作者获得授权,非商业转载请注明出 ...

  9. 在CentOS 7上安装Kafka

    简介 Kafka 是一种高吞吐的分布式发布订阅消息系统,能够替代传统的消息队列用于解耦合数据处理,缓存未处理消息等,同时具有更高的吞吐率,支持分区.多副本.冗余,因此被广泛用于大规模消息数据处理应用. ...

  10. android studio中为项目添加依赖包的方法

    右键项目,Open Module Settings 打开后选择Dependencies选项卡,点最右边的加号: 选择Libriay dependencies,从下拉列表里面选择就可以了.