0

是否可以在普通的 JAVA 类中使用 PersistenceContext 作为 JPA 的注释?如果没有,你能告诉我如何在没有任何注释的情况下使用 PersistenceContext 吗?

4

1 回答 1

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;
    }
}
于 2012-11-15T18:04:54.080 回答