java jpa hibernate_在JPA和Hibernate中使用Java 8 Optional

在JPA和Hibernate中使用Java 8 Optional

Java 8引入了java.util.Optional 这样容器对象,可以包含或不包含值,结合Optional和Stream是非常方便,可以将某些实体属性是空的值表达为Optional。

假设下面实体模型:

0ba698f027d646e8505e493f15502d89.png

Post实体是我们的实体聚合,有多个PostComment关联,每个PostComment有一个Attachment,Attachment可使用Optional来表达。

java.util.Optional并不实现Serializable,因此,我们不能映射实体属性作为Optional,因为这样会限制实体的使用。比如:假如detached实例需要保存在HttpSession,每个保存在HttpSession的对象都应该是Serializable,这样在集群下会话中对象能够跨节点复制,而能够被网络复制的对象都应该是Serializable。

虽然字段属性不能直接使用Optional,但是get/set方法是可以使用的。

@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

}

下面是测试:

使用:

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);

假设有一个PostComment集合list:

List comments = entityManager.createQuery(

"select pc " +

"from PostComment pc " +

"join pc.post p " +

"where p.id = :postId", PostComment.class)

.setParameter("postId", 1L)

.getResultList();

能如下处理Attachment(s):

Attachment notAvailable = getNotAvaillableImage();

List attachments = comments

.stream()

.map(pc -> pc.getAttachment()

.orElse(notAvailable))

.collect(Collectors.toList());

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值