# JPA 2.1: Programmatic Named Queries

本文详细介绍了JPA2.1中如何使用动态方式创建命名查询,包括在EJB启动阶段通过@Singleton注解创建命名查询,并展示了如何在方法中调用这些查询来获取特定数据。示例代码和应用实例均托管于作者的GitHub账户,供读者自行验证和实践。

JPA 2.1: Programmatic Named Queries

In JPA 2.0 or the early version, you can define a named query by add a @NamedQuery annotation on the entity class.

JPA 2.1 brings a new programmatic approach to create a named query dynamically.

<pre> @Startup @Singleton public class ApplicationInitializer { @PersistenceContext EntityManager em; @PostConstruct public void postConstruct(){ System.out.println("@@@application is iniitlized..."); Query query = em.createQuery("select count(vu)from Post p join treat(p.comments as VoteUp) vu where p.id=:id"); em.getEntityManagerFactory().addNamedQuery(Constants.NQ_COUNT_VOTE_UP, query); } } </pre>

In the above the codes, use a @Singleton EJB to create the named queries at EJB @Startup stage.

Replace the query string in the voteUp method with the following content.

<pre> private void fetchVoteDown() { this.voteDown = ((Long) (em.createNamedQuery(Constants.NQ_COUNT_VOTE_UP) .setParameter("id", this.id) .getSingleResult())).intValue(); } </pre>

The sample codes are hosted on my github.com account, check out and play it yourself.

https://github.com/hantsy/ee7-sandbox

转载于:https://my.oschina.net/hantsy/blog/182316

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值