JPA性能调优简介

2016 Nov 1

(主要参考Hibernate和EclipseLink的文档。)

Fetching strategies

对于entity的association到底应该lazy fetch还是eager fetch。 需要为不同的场景指定合适的fetch策略。 不该eager的时候eager fetch费内存;不该lazy的时候lazy fetch会增加和数据库间的通信次数。

The Hibernate recommendation is to statically mark all associations lazy and to use dynamic fetching strategies for eagerness. This is unfortunately at odds with the JPA specification which defines that all one-to-one and many-to-one associations should be eagerly fetched by default. Hibernate, as a JPA provider, honors that default.

Hibernate推荐把association的fetch策略先定义为lazy的(statically,比如@ManyToOne(fetch = FetchType.LAZY)), 然后在需要eager fetch的时候再动态地指定fetch策略。

比如可以通过JPQL或者Criteria以Fetch Join的方式来eager fetch,

SELECT mag FROM Magazine mag LEFT JOIN FETCH mag.articles WHERE mag.id = 1
-- 如果不想返回重复结果,可以加上DISTINCT

builder.createQuery(Employee.class).from(Employee.class).fetch("projects", JoinType.LEFT)...

通过entity graph(@NamedEntityGraph)或者Hibernate profile(@FetchProfile)可以为不同的场景指定fetch的策略。

另外,在lazy fetch的情况下,还可以通过指定batch size来减少fetch的次数。

Pagination

如果结果集太大,则考虑通过setFirstResult()setMaxResults()以“分页”的方式来返回结果集。

JVM的noverify选项

2016 Oct 16

遇到java.lang.VerifyError错误可以用-noverify来关闭bytecode verification。

书籍推荐:Java SE8 for the Really Impatient

2016 Oct 13

推荐一本非常好的关于Java 8的书,Java SE 8 for the Really Impatient

亚马逊链接豆瓣链接

Java SE 8 for the Really Impatient

Javascript Engine in Java

2016 Oct 13

A colleague recently asked me to extract some information/text from a json file in a Docker container. This Docker container has no things like Python or Perl included, and it’s dedicated to Java application only. Parsing json with grep/awk seems a bit intimidating. At last, I recalled that Java is shipped with a Javascript engine and after simply googling found the jjs. We used Javascript as the script language and jjs as the script interpreter to solve the problem.

Java SE 8 will instead ship with a new engine called Oracle Nashorn, which is based on JSR 292 and invokedynamic. It provides better compliance with the ECMA normalized JavaScript specification …

To do so, builds of Oracle’s JDK or OpenJDK include a command-line tool called jjs. It can be found in the bin/ folder of a JDK installation along with the well-known java, javac, or jar tools.

More details in this doc

书籍推荐:深入理解Java虚拟机

2016 Oct 1

深入理解Java虚拟机是关于Java的垃圾回收、类加载和性能优化等的一本好书。非常值得一读。 InfoQ之前推出过一本迷你书,The Java Garbage Collection Mini-Book,主要内容是Java的垃圾回收。 不过这本迷你书目前处于重新勘误中,还没提供新版本的下载。

豆瓣链接

深入理解Java虚拟机

Next →