Home > Java > javaTutorial > body text

## SELECT NEW in JPQL: Power Tool or Potential Pitfall?

Linda Hamilton
Release: 2024-10-25 10:18:31
Original
972 people have browsed it

## SELECT NEW in JPQL: Power Tool or Potential Pitfall?

JPQL's Power or Peril: Using SELECT NEW to Create Objects

The realm of Java Persistence Query Language (JPQL) offers a powerful feature known as SELECT NEW, enabling the creation of new objects within a select statement. Instead of retrieving instances managed by the persistence context, this construct facilitates the manipulation of transient objects. However, the question remains: is SELECT NEW a tool to be embraced or avoided?

Justified Embraces

According to the EJB 3.0 JPA Specification, SELECT NEW serves specific purposes:

  • Returns custom Java instances, including non-mapped classes.
  • Type-safe retrieval of specific properties from joined entities.

An example would be a query retrieving customer details without the full customer entity:

SELECT NEW com.acme.example.CustomerDetails(c.id, c.status, o.count)
FROM Customer c JOIN c.orders o
WHERE o.count > 100
Copy after login

When to Avoid

While SELECT NEW offers conveniences, it should not be employed indiscriminately. Its prudent use is limited to scenarios where:

  • Avoiding full entity retrieval for improved performance or specific use cases.
  • Retrieving properties from entities that are not fully joined or mapped.

Embracing Good Practices

Far from discouraging SELECT NEW usage, it is crucial to embrace it while adhering to good practices:

  • Avoid using it as a substitute for properly designed joins.
  • Consider the potential performance implications when creating large collections of unmanaged objects.
  • Limit its use to cases where it enhances the expressiveness or efficiency of the query.

Conclusion

SELECT NEW is a valuable tool when applied appropriately. By embracing its benefits while adhering to best practices, developers can leverage the power of JPQL while avoiding pitfalls. Whether SELECT NEW should be embraced or avoided is thus a question of judicious application, recognizing its utility in specific contexts without succumbing to excessive reliance.

The above is the detailed content of ## SELECT NEW in JPQL: Power Tool or Potential Pitfall?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!