get
有什么优势createQuery
呢?
我可以看到不必解析 HQL 可能会稍微提高性能,但是使用 get over createQuery 还有其他主要优势吗?
First, it's much quicker to type, is much more readable, and expresses the intent clearly: get an entity by its ID. And it's basically impossible to make an error, whereas you could have a typo in your HQL query.
Regarding performance, the main advantage is that it executes a select statement only if the entity is not in the session cache yet. An HQL query will be executed every time. And if you have a second-level cache, get()
will avoid executing a query completely if the entity is already in the second-level cache.
get()
直接使用会话来检索对象。
createQuery()
使用 HQL