为什么80%的码农都做不了架构师?>>>   

#Data crossstore between Mongo and JPA

Spring Data Mongo provides another attractive feature, when you mix to use Mongo and JPA in your projects, you can unite the models of Mongo and JPA.

Model

The Conference and Signup are still used as example models, Conference is JPA entity class and Signup is a Mongo Document.

<pre> @Entity public class Conference { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "id") private Long id; @RelatedDocument private Signup signup; } </pre>

The Signup Document is defined as the following.

<pre> @Document public class Signup { @Id private String id; } </pre>

@RelatedDocument annotation indicates the signup property of Conference is a reference of Signup Mongo Document. This annotation will be processed by a AspectJ aspect which provided in Spring Data Mongo.

You have to add some code fragments to Spring configuration.

<pre> &lt;!-- Mongo cross-store aspect config --> &lt;bean class="org.springframework.data.mongodb.crossstore.MongoDocumentBacking" factory-method="aspectOf"> &lt;property name="changeSetPersister" ref="mongoChangeSetPersister" /> &lt;/bean> &lt;bean id="mongoChangeSetPersister" class="org.springframework.data.mongodb.crossstore.MongoChangeSetPersister"> &lt;property name="mongoTemplate" ref="mongoTemplate" /> &lt;property name="entityManagerFactory" ref="entityManagerFactory" /> &lt;/bean> </pre>

Firstly, this aspect will mark this property as @Transient and prevent JPA recognize it as a persistent property.

Then register a transaction synchronization to entity lifecycle events of the host JPA Entity( Conference ) to synchronize the @RelatedDocument data into Mongo Document.

We also use Junit @Before to initialize the data.

<pre> @Before public void beforeTestCase() { log.debug("==================before test case========================="); conferenceRepository.save(newConference()); } </pre>

The newConference() method is use for create a new Conference object, we also create a new Singup as the value of signup property.

<pre> @Test public void retrieveConference() { log.debug("==================enter retrieveConference========================="); assertTrue(null != id); Conference conf = em.find(Conference.class, id); log.debug("conf@@@" + conf); assertTrue(null != conf); assertTrue(null == conf.getSignup()); } </pre>

When you run this Test, pass!

Everything is OK?

Spring Data Mongo provides a LoggingEventListener to tracking the Mongo events.

<pre> &lt;bean class="org.springframework.data.mongodb.core.mapping.event.LoggingEventListener" /> </pre>

After you enable this listener, you should see the Mongo log info about saving Conference. But we run this Test again, we can not see it at all.

Add another line code in the first line of the test method.

<pre> em.clear(); </pre>

Run the Test, failed.

No doubt the Signup was not stored in Mongo when saving Conference object.

As motioned before, the crosssotre synchronization is fired by the entity lifecycle events. If JPA event @PostPersist is not fired in a transaction, the Mongo event will not be fired.

<pre> @Before // @Transactional(propagation = Propagation.REQUIRED) public void beforeTestCase() { log.debug("==================before test case========================="); transactionTemplate = new TransactionTemplate(transactionManager); transactionTemplate.execute(new TransactionCallback&lt;Void>() { @Override public Void doInTransaction(TransactionStatus status) { } } } </pre>

Alternatively, we change the initial codes slightly, and use a TranscationTemplate to process the Conference saving action as an unit of work.

Run this test again, pass.

##More ...

If possible store a Collection of data into Mongo like this,

<pre> @RelatedDocument private List&lt;Signup> signups; </pre>

Unfortunately, it does not work.

But you wrap the List into standalone Document like.

<pre> @Document public class SignupInfo { @Id private String id; @DBRef private List&lt;Signup> signups = new ArrayList&lt;Signup>(); } </pre>

And change the relation to SignupInfo.

<pre> @RelatedDocument private SignupInfo signupinfo; </pre>

But you have to save the Signup objects in Mongo firstly, because Spring Data Mongo does not support Cascade saving feature like JPA.

I have some wishes for the crossstore.

  1. Store reverse when store a Document.

Update to now, there is no way to do the work reverse. When you store a Mongo Document it does not support to store the related JPA entity into database.

  1. Query cross different data storage. Obviously, it is impossible to execute query cross different stores.

Summary

Personally, I think the Mongo and JPA crossstore is only a toy, and the provided feature is too weak. I hope it can be improved in future, and provides seamless integration between different data stores as I expected.

转载于:https://my.oschina.net/hantsy/blog/143519

Data crossstore between Mongo and JPA相关推荐

  1. spring data jpa 详解

    2019独角兽企业重金招聘Python工程师标准>>> 本篇进行Spring-data-jpa的介绍,几乎涵盖该框架的所有方面,在日常的开发当中,基本上能满足所有需求.这里不讲解JP ...

  2. Spring Data JPA 原理与实战第二天 掌握Repoitory和DQM

    02 Spring Data Common 之 Repoitory 如何全面掌握? 通过上一课时,我们知道了 Spring Data 对整个数据操作做了很好的封装,其中 Spring Data Com ...

  3. Spring Boot 、Spring Data JPA、Hibernate集成

    ###什么是JPA JPA是用于管理Java EE 和Java SE环境中的持久化,以及对象/关系映射的JAVA API 最新规范为"JSR 338:Java Persistence 2.1 ...

  4. 01 | Spring Data JPA 初识

    课程正式开始了,这里我会以一个案例的形式来和你讲解如何通过 Spring Boot 结合 Spring Data JPA 快速启动一个项目.如何使用 UserRepository 完成对 User 表 ...

  5. Spring Data JPA的持久层

    1.概述 本文将重点介绍Spring 3.1,JPA和Spring Data的持久层的配置和实现. 有关使用基于Java的配置和项目的基本Maven pom设置Spring上下文的分步介绍,请参阅本文 ...

  6. jpa 原生sql 查询返回一个实体_spring data系列之jpa

    Springdata 系列之spring data jpa 背景:随着互联网技术的发展,现在的企业开发中用到的用于数据存储的产品,不再仅仅是关系型数据库,而是要根据场景需要选择不同的存储技术,比如用于 ...

  7. Spring Data JPA 查询方法的命名语法与参数

    3 Spring Data JPA 查询方法的命名语法与参数 在⼯作中,你是否经常为⽅法名的语义.命名规范⽽发愁?是否要为不同的查询条件写各种的 SQL 语句?是否为同⼀个实体的查询,写⼀个超级通⽤的 ...

  8. mongo报错:not authorized on bb to execute command { create: \“xxx\“...}

    mongo报错: {"ok" : 0,"errmsg" : "not authorized on bb to execute command { cr ...

  9. Spring Data:企业级Java的现代数据访问技术(影印版)

    <Spring Data:企业级Java的现代数据访问技术(影印版)> 基本信息 原书名:Spring Data:Modern Data Access for Enterprise Jav ...

  10. 操作方法:具有多个Mongo存储库和Kotlin的Spring Boot 2 Web应用程序

    首先,免责声明:如果您正在编写微服务 (每个人现在都对吗?)并希望它是惯用的 ,那么通常不会在其中使用几个不同的数据源. 图片取自Pixabay© https: //pixabay.com/illus ...

最新文章

  1. 插槽 查看硬盘状态_摄影路上的“全能”伴侣 | LaCie DJI Copilot 移动硬盘
  2. centos7 ssr一键脚本_RHEL7(Centos7)下使用shell脚本一键部署服务
  3. 马尔可夫“折棍子”过程 Markovian Stick-breaking Process 在直方图平滑中的应用
  4. mssql自定义函数中使用游标
  5. leetcode 191. 位1的个数(位运算)
  6. Linphone编译【转载】
  7. python求最大值最小值_Python求可变参数的最大值最小值以及参数个数
  8. gb50243-2016通风与空调工程施工质量验收规范_【规范】现行建筑标准规范集合:(六)专业工程...
  9. P Laguna/ A database for evaluation of algorithms for measurement of QT and other waveform interval
  10. 使用python把txt文件转为csv文件并且利用自己想要的分割符号
  11. max232cpe管脚电压
  12. 如何获得静态IP资源?
  13. centos系统 -官网下载mysql
  14. 红黑树(四)之 C++的实现 http://www.cnblogs.com/skywang12345/p/3624291.html?utm_source=tuicoolutm_medium=refe
  15. NGS 分析流程 (一)
  16. 基于MySQL毕业设计题目50例
  17. android视频播放异常,Android 播放视频常见问题小结
  18. python最佳身高_Python+sklearn使用线性回归算法预测儿童身高
  19. CT图像之Hu值变换与窗宽窗位调整
  20. 长波红外相机和相机内核2022年全球行业分析报告

热门文章

  1. 递归与二叉树_leetcode235
  2. vsftp 配置参数详解
  3. HDU Fibonacci
  4. 当信贷风控遇见机器学习,模型还是规则?
  5. k8s数据持久化实验
  6. 分页插件pagehelper ,在sql server 中是怎么配置的
  7. pip 升级 pip
  8. current_session_context_class
  9. background相关属性
  10. web.config从.net framework3.5向4.0迁移注意事项