jpa TypedQuery 怎么使用,写个例子
时间: 2023-06-06 22:04:39 浏览: 62
好的,关于 jpa TypedQuery 的使用,下面是一个例子:
```java
// 假设你有一个叫做 User 的实体类
@Entity
public class User {
@Id
private Long id;
private String name;
private Integer age;
// 省略 getter、setter、构造函数等
}
// 那么你可以这样使用 TypedQuery
@Entity
public class UserRepository {
@PersistenceContext
private EntityManager entityManager;
public List<User> findByNameAndAge(String name, Integer age) {
CriteriaBuilder cb = entityManager.getCriteriaBuilder();
CriteriaQuery<User> cq = cb.createQuery(User.class);
Root<User> root = cq.from(User.class);
cq.select(root).where(cb.and(
cb.equal(root.get("name"), name),
cb.equal(root.get("age"), age)
));
TypedQuery<User> query = entityManager.createQuery(cq);
return query.getResultList();
}
}
```
上面的例子中,我们使用了 Criteria API 来构建查询条件,最终得到了一个 TypedQuery 对象。然后我们调用 getResultList 方法来获取查询结果。注意,这里的 User 类要使用 @Entity 注解进行标记,而 UserRepository 类中的 entityManager 要使用 @PersistenceContext 注解进行标记,以便容器可以自动注入 EntityManager 实例。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)