是否可以在普通的JAVA类中使用PersistenceContext作为JPA的注释?如果没有,你能告诉我如何在没有任何注释的情况下使用PersistenceContext吗?
答案 0 :(得分:0)
是的,您可以在任何Java类中使用@PersistenceContext。但是,您必须在Spring配置中指定annotation-config,如以下示例所示:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config/>
</beans>
指定后,您可以使用@PersistenceContext,如下所示:
package com.sample.dao.impl
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
public class CustomerDaoImpl {
@PersistenceContext
private EntityManager em;
public Customer getCustomerByName(String customerName) {
Query query = em.createQuery("SELECT c FROM Customer c WHERE c.name = ?1");
query.setParameter(1, customerName);
List<Customer> results = query.getResultList();
if (results.size() > 0) {
return results.get(0);
}
return null;
}
}