获得实体经理

时间:2014-07-17 01:19:08

标签: spring hibernate jpa spring-data

我正在使用spring data jpa,但我想执行一些服装查询,以便如何在我的java类中获取entity manager来制作entityManager.createQuery(..)

   <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
      <property name="persistenceUnitName" value="persistenceYous" />
      <property name="dataSource" ref="dataSource" />
      <property name="packagesToScan" value="persistence" />
      <property name="jpaVendorAdapter" ref="jpaVendorAdapter" />

   </bean>

3 个答案:

答案 0 :(得分:2)

您可以像在任何其他spring应用程序中一样获取EntityManager:

public class ProductDaoImpl implements ProductDao {
    private EntityManager em;

    @PersistenceContext
    public void setEntityManager(EntityManager em) {
        this.em = em;
    }

    public Collection loadProductsByCategory(String category) {
        em. .... 
        ....
    }
}

请参阅:http://docs.spring.io/spring/docs/4.0.0.RELEASE/spring-framework-reference/html/orm.html#orm-jpa-straight

答案 1 :(得分:2)

在applicationContext.xml中,检查您是否拥有以下内容:

<context:annotation-config />

这将添加对注入@PersistenceContext的几个注释(例如EntityManager)的支持。所以在Spring管理的bean中,你可以这样做:

public class MyClass {
    private EntityManager entityManager;

    @PersistenceContext
    public void setEntityManager(EntityManager em) {
        this.entityManager = em
    }

    public void myMethod() {
        Query q = entityManager.createQuery(...);
        // ...
    }
}

如果您想为 @PersistenceContext添加suport,而不是<context:annotation-config />支持的其他注释,则可以从applicationContext.xml中删除该注释并添加具体的BeanPostProcessor

<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" scope="singleton">
   <!-- Optional configuration of PersistenceAnnotationBeanPostProcessor, for advanced use cases -->
</bean>

答案 2 :(得分:-1)

首先按照此链接获取实施所需的步骤。
check this link

第二步他使用@Autowired private JdbcOperations operations;
但这并不适合我,所以我使用了以下代码..这对我有用。

@Component
public class MayorRepositoryImpl extends JdbcDaoSupport implements MayorRepositoryCustom {

    @Override
    public List<Employee> getUsers(String role) {
        return getJdbcTemplate().query("Write your custom query",new RowMapper<Employee>(){
            @Override 
            public Employee mapRow(ResultSet rs, int rownumber) throws SQLException {   
                // Mapping each row and adding to list and returning the list 
                Employee employeeBean=new Employee();  
                employeeBean.setId(rs.getInt("id"));  
                employeeBean.setEmployeeNumber(rs.getString("employeeNumber"));
                employeeBean.setName(rs.getString("name"));
                employeeBean.setWorkEmailAddress(rs.getString("workEmailAddress"));
                employeeBean.setPersonalEmailAddress(rs.getString("personalEmailAddress"));
                return employeeBean;  
            }  
        });
    }

}
这对我来说非常有用..
如果您发现任何困难让我知道,以帮助您。

干杯