Apache Karaf,无法注入实体经理

时间:2016-07-12 11:18:48

标签: java jpa osgi persistence apache-karaf

我想从容器中使用实体管理器,但是当我尝试访问它时,我得到了

  

java.lang.IllegalStateException:需要主动协调

的persistence.xml

<persistence-unit name="data-point" transaction-type="JTA">
<jta-data-source>osgi:service/javax.sql.DataSource/(osgi.jndi.service.name=dvdrental)</jta-data-source>
<properties>
  <property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQL82Dialect"/>
  <property name="hibernate.show_sql" value="true"/>
  <property name="hibernate.hbm2ddl.auto" value="update"/>
  <property name="hibernate.connection.driver_class" value="org.postgresql.Driver"/>
  <property name="hibernate.archive.autodetection" value="class"/>
</properties>

bluprint.xml

<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.osgi.org/xmlns/blueprint/v1.0.0 https://osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd"
       default-activation="eager"
       xmlns:tx="http://aries.apache.org/xmlns/transactions/v1.2.0"
       xmlns:jpa="http://aries.apache.org/xmlns/jpa/v2.0.0">

<jpa:enable />
<tx:enable-annotations />
<service id="filesEntityManager" ref="filesEntityManagerImpl" interface="ru.bia.karaf.dao.FilesEntityManager"/>
<bean id="filesEntityManagerImpl" class="ru.bia.karaf.dao.FilesEntityManagerImpl"/>
<bean id="testBean" class="ru.bia.karaf.web.TestBean" init-method="test">
    <property name="filesEntityManager" ref="filesEntityManagerImpl"/>
</bean>

TestBean.java

public class TestBean {
    private FilesEntityManagerImpl filesEntityManager;

    public void test(){
    System.out.println("hey bro from init");
    System.out.println("filesEntityManager = " + filesEntityManager);
    System.out.println("filesEntityManager.getEm() = " + filesEntityManager.getEm());
}

public FilesEntityManagerImpl getFilesEntityManager() {
    return filesEntityManager;
}

public void setFilesEntityManager(FilesEntityManagerImpl filesEntityManager) {
    this.filesEntityManager = filesEntityManager;
    }
}

FilesEntityManagerImpl.java

@OsgiServiceProvider(classes = {FilesEntityManager.class})
@Transactional
public class FilesEntityManagerImpl implements FilesEntityManager {
    @PersistenceContext(unitName="data-point")
    EntityManager em;
...
}

1 个答案:

答案 0 :(得分:1)

注入FilesEntityManagerImpl的EntityManager是EntityManager的线程本地代理。它的生命周期必然会受到协调。

如果您在协调之外访问em,则会收到此错误。您可以使用@Transactional注释确保协调处于活动状态。如果你 不需要实际的事务,但只有协调才使用@Transactional(TxType.SUPPORTS)。

您通常也不应该在注入它的对象之外访问EntityManager。