PersistenceContext を通常の JAVA クラスで JPA のアノテーションとして使用することは可能ですか? そうでない場合は、注釈なしで PersistenceContext を使用する方法を教えてください。
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 に答える