技术控

    今日:19| 主题:49390
收藏本版 (1)
最新软件应用技术尽在掌握

[其他] The best way to map a Java 1.8 Optional entity attribute with JPA and Hibernate

[复制链接]
初吻给了香烟 发表于 2016-10-3 19:14:14
146 8

立即注册CoLaBug.com会员,免费获得投稿人的专业资料,享用更多功能,玩转个人品牌!

您需要 登录 才可以下载或查看,没有帐号?立即注册

x
Follow @vlad_mihalcea  Introduction

   StackOverflow is a neverending source of great questions. This time, we are covering this question about using  Java 1.8 Optional with JPA and Hibernate  .
   Java 1.8 introduced the java.util.Optional container object that may or may not contain a certain value. Combining Optional and streams is very handy. Therefore, you might want that some nullable entity attributes be exposed as Optional .
   This article is going to demonstrate what are caveats of using Optional with entity attributes, and how you can overcome them.
  Domain Model

  Let’s assume we have the following entity model:
   
The best way to map a Java 1.8 Optional entity attribute with JPA and Hibernate-1 (following,multiple,overcome,question,article)

   The Post entity is the root in our entity aggregate. There can be multiple PostComment(s) associated with a Post , and each PostComment can have an Attachment . Because the Attachment is not mandatory, it makes sense to use an Optional container for it.
  Optional and Serializable

   The java.util.Optional does not implement the Serializable interface. For this reason, we should never map an entity attribute as Optional because that will restrict the entity usage.
   For instance, we could have a detached instance stored in the HttpSession because we are operating a long conversation workflow . Every object stored in the HttpSession should be Serializable because the session may be clustered on several web nodes.
   If you’re using Java EE and Stateful Session Beans, then you must ensure that all entities are `Serializable, as otherwise the passivisation process would fail .
   For all these reasons, an entity attribute should not be mapped as a java.util.Optional .
  All is not lost

   But just because we cannot map an entity attribute as Optional , it does not mean we cannot expose it using an Optional container. If we are using field-based access persistence, then the underlying entity attribute can be mapped using the actual persisted type, while the getter method can use an Optional instead.
  [code]@Entity(name = "PostComment")
@Table(name = "post_comment")
public static class PostComment
    implements Serializable {

    @Id
    @GeneratedValue
    private Long id;

    private String review;

    @ManyToOne(fetch = FetchType.LAZY)
    private Post post;

    @ManyToOne(fetch = FetchType.LAZY)
    private Attachment attachment;

    public Optional getAttachment() {
        return Optional.ofNullable(attachment);
    }

    public void setAttachment(Attachment attachment) {
        this.attachment = attachment;
    }
   
    //Other getters and setters omitted for brevity
}[/code]  That’s it!
   If you’re using property-based access, then the getter must expose the actual persisted type, in which case you need to have a separate @Transient method that uses the Optional method return type.
  Testing time

  Assuming we have the following entities:
  [code]byte[] coverContent = new byte[] {1, 2, 3};

Post post = new Post();
post.setId(1L);
post.setTitle("High-Performance Java Persistence");
entityManager.persist(post);

PostComment comment1 = new PostComment();
comment1.setPost(post);

entityManager.persist(comment1);

Attachment cover = new Attachment();
cover.setContent(coverContent);
entityManager.persist(cover);

PostComment comment2 = new PostComment();
comment2.setPost(post);
comment2.setAttachment(cover);

entityManager.persist(comment2);[/code]   If we alaready have a list of PostComment(s) :
  [code]List comments = entityManager.createQuery(
    "select pc " +
    "from PostComment pc " +
    "join pc.post p " +
    "where p.id = :postId", PostComment.class)
.setParameter("postId", 1L)
.getResultList();[/code]   We can process Attachment(s) as follows:
  [code]Attachment notAvailable = getNotAvaillableImage();

List attachments = comments
.stream()
.map(pc -> pc.getAttachment()
.orElse(notAvailable))
.collect(Collectors.toList());[/code]   If there is not Attachment already set, we can use a default N/A image.
   If you enjoyed this article, I bet you are going to love my book as well.

The best way to map a Java 1.8 Optional entity attribute with JPA and Hibernate-2 (following,multiple,overcome,question,article)

  Conclusion

   When using JPA and Hibernate, you can make use of the Java 1.8 Optional in your Domain Model entities. However, you have to make sure not to use it as a persistent property type.
     Follow @vlad_mihalcea    If you liked this article, you might want to subscribe to my newsletter too.
友荐云推荐




上一篇:The Quantum Version of the One-Time Pad is Teleportation
下一篇:Find the minimum value of m that satisfies ax + by = m and all values after m al
酷辣虫提示酷辣虫禁止发表任何与中华人民共和国法律有抵触的内容!所有内容由用户发布,并不代表酷辣虫的观点,酷辣虫无法对用户发布内容真实性提供任何的保证,请自行验证并承担风险与后果。如您有版权、违规等问题,请通过"联系我们"或"违规举报"告知我们处理。

明杨.校园 发表于 2016-10-4 01:14:38
洗洗更白白,顶顶更健康!
回复 支持 反对

使用道具 举报

范冬梅 发表于 2016-10-4 01:29:39
生活可以将就,生活也可以讲究!
回复 支持 反对

使用道具 举报

qjss 发表于 2016-10-4 02:31:15
放假前的节奏
回复 支持 反对

使用道具 举报

989541i 发表于 2016-10-4 05:32:53
元芳你怎么看?
回复 支持 反对

使用道具 举报

烨霖 发表于 2016-10-23 22:18:22
敢进男厕所的女汉子别隐身
回复 支持 反对

使用道具 举报

ljdms 发表于 2016-10-25 11:27:31
男人偷腥时的智商仅次于爱因斯坦!  
回复 支持 反对

使用道具 举报

乐瑶 发表于 2016-11-17 18:54:41
泥泞路上的奔驰,永远跑不过高速路上的夏利。说明:”平台很重要!”
回复 支持 反对

使用道具 举报

eqiverson 发表于 2016-11-20 23:06:19
爱情就像两个拉着橡皮筋的人,受伤的总是不愿意放手的那一个!
回复 支持 反对

使用道具 举报

*滑动验证:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

我要投稿

推荐阅读

扫码访问 @iTTTTT瑞翔 的微博
回页顶回复上一篇下一篇回列表手机版
手机版/CoLaBug.com ( 粤ICP备05003221号 | 文网文[2010]257号 )|网站地图 酷辣虫

© 2001-2016 Comsenz Inc. Design: Dean. DiscuzFans.

返回顶部 返回列表