内容简介:将Java 8 Optional视为处理所有的空值的“银弹”可能会带来更多弊大于利。合适它们是最好的方法。本文的应用程序是在实体和查询中如何正确使用Java 8 Optional的概念证明。关键点:
将 Java 8 Optional视为处理所有的空值的“银弹”可能会带来更多弊大于利。合适它们是最好的方法。
本文的应用程序是在实体和查询中如何正确使用Java 8 Optional的概念证明。
关键点:
- 使用Spring Data内置查询方法返回Optional(例如findById())
- 编写我们自己的查询返回Optional
- 在实体getter使用Optional
- 为了运行不同的场景,检查文件:data-mysql.sql
源代码可以在 这里 找到 。
@Entity <b>public</b> <b>class</b> TennisPlayer implements Serializable { <b>private</b> <b>static</b> <b>final</b> <b>long</b> serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) <b>private</b> Long id; <b>private</b> String name; @ManyToOne(fetch=FetchType.LAZY) @JoinColumn(name = <font>"tournament_id"</font><font>) <b>private</b> Tournament tournament; <b>public</b> Long getId() { <b>return</b> id; } <b>public</b> <b>void</b> setId(Long id) { <b>this</b>.id = id; } <b>public</b> Optional<String> getName() { <b>return</b> Optional.ofNullable(name); } <b>public</b> <b>void</b> setName(String name) { <b>this</b>.name = name; } <b>public</b> Optional<Tournament> getTournament() { <b>return</b> Optional.ofNullable(tournament); } <b>public</b> <b>void</b> setTournament(Tournament tournament) { <b>this</b>.tournament = tournament; } @Override <b>public</b> <b>boolean</b> equals(Object obj) { <b>if</b> (<b>this</b> == obj) { <b>return</b> <b>true</b>; } <b>if</b> (!(obj instanceof TennisPlayer)) { <b>return</b> false; } <b>return</b> id != <b>null</b> && id.equals(((TennisPlayer) obj).id); } @Override <b>public</b> <b>int</b> hashCode() { <b>return</b> 2018; } } </font>
@Repository <b>public</b> <b>interface</b> TennisPlayerRepository <b>extends</b> JpaRepository<TennisPlayer, Long> { @Transactional(readOnly=<b>true</b>) Optional<TennisPlayer> findByName(String name); }
以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网
猜你喜欢:- 表单 – 如何使用实体列表(CRUD)从模板中删除实体?
- 使用CRF++实现命名实体识别(NER)
- MyBatis Generator配置文件--指定生成实体类使用实际的表列名作为实体类的属性名
- c# – 实体框架6 – 使用我的getHashCode()
- HTML实体:何时使用十进制与十六进制
- 在OQL上使用UPDLOCK锁定查询结果,安全的更新实体数据
本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
Ajax Design Patterns
Michael Mahemoff / O'Reilly Media / 2006-06-29 / USD 44.99
Ajax, or Asynchronous JavaScript and XML, exploded onto the scene in the spring of 2005 and remains the hottest story among web developers. With its rich combination of technologies, Ajax provides a s......一起来看看 《Ajax Design Patterns》 这本书的介绍吧!