JBoss AS 7 + Spring + JPA EntityManager исключение нулевого указателя
Я работаю над этим некоторое время. Я хочу использовать OpenShift для моего публичного сервера. Так что локально я тоже использую JBoss AS 7. Я прочитал много форумов, некоторые похожие проблемы, но ни один из них не решил мою проблему. Я использую JPA, Spring 3, Hibernate. Я думаю, что у меня что-то не так в файле springDispatcher-servlet.xml.
В чем проблема?! В DAO, где я использую EntityManager, я получаю исключение nullpointerException, когда я хочу использовать запрос по этому вопросу. Однако сам entityManager не является нулевым. Позвольте мне показать вам, что у меня есть.
Часть моего springDispatcher-servlet.xml
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean" >
<property name="persistenceUnitName" value="primary"/>
</bean>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<context:component-scan base-package="com.company.db" />
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"
p:entityManagerFactory-ref="entityManagerFactory" />
Я хочу использовать источник данных, который дает мой jboss в standalone.xml. Поэтому я использую файл persistence.xml для настроек. Вот постоянное имя, указанное в..-servlet.xml
<persistence-unit name="primary" transaction-type="JTA">
<jta-data-source>java:jboss/datasources/MysqlDS</jta-data-source>
<properties>
<!-- Properties for Hibernate -->
<property name="hibernate.hbm2ddl.auto" value="create-drop" />
<property name="hibernate.show_sql" value="true" />
</properties>
</persistence-unit>
У меня есть подключение к базе данных. Он создает аннотированную таблицу при запуске из-за настройки "create-drop" выше. Ну это хорошо.
Классы в пакете com.company.db очень просты:
Интерфейс DAO:
public interface LocationDAO {
public List<Location> getList();
}
Реализация DAO:
@Repository("locationDAO")
public class LocationDAOImpl implements LocationDAO {
@PersistenceContext
private EntityManager entityManager;
@SuppressWarnings("unchecked")
@Override
public List<Location> getList() {
List<Location> retVal = new ArrayList<Location>();
Query query = entityManager.createQuery("select l from Location l");
if (query != null) {
retVal = query.getResultList();
}
return retVal;
}
public void setEntityManager(EntityManager entityManager) {
this.entityManager = entityManager;
};
}
Здесь проблема. При вызове createQuery из entityManager (entityManager не является нулевым).
Мой интерфейс транзакций:
public interface LocationDataService {
public List<Location> getLocations();
}
И реализация:
@Service("locationDataService")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class LocationDataServiceImpl implements LocationDataService {
@Autowired
private LocationDAO locationDAO;
public LocationDataServiceImpl() {
}
@Override
public List<Location> getLocations() {
List<Location> retVal = new ArrayList<Location>();
retVal = locationDAO.getList();
return retVal;
}
}
И я почти забыл класс Location:
@Entity
@Table(name = "location")
public class Location {
@Id
@GeneratedValue
@Column(name = "id")
private Integer id;
@Column(name = "country")
private String country;
@Column(name = "city")
private String city;
@Column(name = "post_code")
private String postCode;
public Location() {
}
public Location(Integer id, String country, String city, String postCode) {
this.id = id;
this.country = country;
this.city = city;
this.postCode = postCode;
}
//getters, setters are here
}
Есть ли у вас какие-либо предложения, что я пропустил в конфигурации?
Это было бы очень полезно, потому что я думаю, что мне нужно немного изменить на этом этапе.
Это трассировка стека:
14:10:16,924 ERROR [org.apache.catalina.core.ContainerBase.[jboss.web].[default-host].[/].[springDispatcher]] (http-localhost-127.0.0.1-8080-1) Servlet.service() for servlet springDispatcher threw exception: java.lang.NullPointerException
at org.hibernate.engine.transaction.internal.jta.JtaStatusHelper.getStatus(JtaStatusHelper.java:73) [hibernate-core-4.0.1.Final.jar:4.0.1.Final]
at org.hibernate.engine.transaction.internal.jta.JtaStatusHelper.isActive(JtaStatusHelper.java:115) [hibernate-core-4.0.1.Final.jar:4.0.1.Final]
at org.hibernate.engine.transaction.internal.jta.CMTTransaction.join(CMTTransaction.java:149) [hibernate-core-4.0.1.Final.jar:4.0.1.Final]
at org.hibernate.ejb.AbstractEntityManagerImpl.joinTransaction(AbstractEntityManagerImpl.java:1207) [hibernate-entitymanager-4.0.1.Final.jar:4.0.1.Final]
at org.hibernate.ejb.AbstractEntityManagerImpl.postInit(AbstractEntityManagerImpl.java:176) [hibernate-entitymanager-4.0.1.Final.jar:4.0.1.Final]
at org.hibernate.ejb.EntityManagerImpl.<init>(EntityManagerImpl.java:89) [hibernate-entitymanager-4.0.1.Final.jar:4.0.1.Final]
at org.hibernate.ejb.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:125) [hibernate-entitymanager-4.0.1.Final.jar:4.0.1.Final]
at org.hibernate.ejb.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:120) [hibernate-entitymanager-4.0.1.Final.jar:4.0.1.Final]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.6.0_31]
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) [rt.jar:1.6.0_31]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) [rt.jar:1.6.0_31]
at java.lang.reflect.Method.invoke(Unknown Source) [rt.jar:1.6.0_31]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.invokeProxyMethod(AbstractEntityManagerFactoryBean.java:423) [spring-orm-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean$ManagedEntityManagerFactoryInvocationHandler.invoke(AbstractEntityManagerFactoryBean.java:485) [spring-orm-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at $Proxy38.createEntityManager(Unknown Source) at org.springframework.orm.jpa.EntityManagerFactoryUtils.doGetTransactionalEntityManager(EntityManagerFactoryUtils.java:195) [spring-orm-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:211) [spring-orm-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at $Proxy39.createQuery(Unknown Source) at com.company.db.dao.LocationDAOImpl.getList(LocationDAOImpl.java:31) [classes:]
at com.company.db.service.LocationDataServiceImpl.getLocations(LocationDataServiceImpl.java:33) [classes:]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.6.0_31]
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) [rt.jar:1.6.0_31]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) [rt.jar:1.6.0_31]
at java.lang.reflect.Method.invoke(Unknown Source) [rt.jar:1.6.0_31]
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:309) [spring-aop-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183) [spring-aop-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150) [spring-aop-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110) [spring-tx-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172) [spring-aop-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202) [spring-aop-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at $Proxy40.getLocations(Unknown Source) at com.company.something.SomethingSearchController.populateLocationList(SomethingSearchController.java:117) [classes:]
at com.company.something.SomethingSearchController.initForm(SomethingSearchController.java:58) [classes:]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [rt.jar:1.6.0_31]
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) [rt.jar:1.6.0_31]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) [rt.jar:1.6.0_31]
at java.lang.reflect.Method.invoke(Unknown Source) [rt.jar:1.6.0_31]
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:176) [spring-web-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:426) [spring-webmvc-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:414) [spring-webmvc-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:790) [spring-webmvc-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:719) [spring-webmvc-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:644) [spring-webmvc-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:549) [spring-webmvc-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:734) [jboss-servlet-api_3.0_spec-1.0.0.Final.jar:1.0.0.Final]
at javax.servlet.http.HttpServlet.service(HttpServlet.java:847) [jboss-servlet-api_3.0_spec-1.0.0.Final.jar:1.0.0.Final]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:329) [jbossweb-7.0.13.Final.jar:]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248) [jbossweb-7.0.13.Final.jar:]
at org.jboss.weld.servlet.ConversationPropagationFilter.doFilter(ConversationPropagationFilter.java:62) [weld-core-1.1.5.AS71.Final.jar:2012-02-10 15:31]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:280) [jbossweb-7.0.13.Final.jar:]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248) [jbossweb-7.0.13.Final.jar:]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:368) [spring-security-web-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:109) [spring-security-web-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:83) [spring-security-web-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380) [spring-security-web-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:97) [spring-security-web-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380) [spring-security-web-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:100) [spring-security-web-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380) [spring-security-web-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54) [spring-security-web-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380) [spring-security-web-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:35) [spring-security-web-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380) [spring-security-web-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:177) [spring-security-web-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380) [spring-security-web-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:187) [spring-security-web-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380) [spring-security-web-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105) [spring-security-web-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380) [spring-security-web-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:79) [spring-security-web-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:380) [spring-security-web-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:169) [spring-security-web-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:237) [spring-web-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:167) [spring-web-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:280) [jbossweb-7.0.13.Final.jar:]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248) [jbossweb-7.0.13.Final.jar:]
at org.tuckey.web.filters.urlrewrite.UrlRewriteFilter.doFilter(UrlRewriteFilter.java:391) [urlrewritefilter-3.2.0.jar:3.2.0]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:280) [jbossweb-7.0.13.Final.jar:]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248) [jbossweb-7.0.13.Final.jar:]
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88) [spring-web-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76) [spring-web-3.0.5.RELEASE.jar:3.0.5.RELEASE]
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:280) [jbossweb-7.0.13.Final.jar:]
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248) [jbossweb-7.0.13.Final.jar:]
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:275) [jbossweb-7.0.13.Final.jar:]
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:161) [jbossweb-7.0.13.Final.jar:]
at org.jboss.as.jpa.interceptor.WebNonTxEmCloserValve.invoke(WebNonTxEmCloserValve.java:50) [jboss-as-jpa-7.1.1.Final.jar:7.1.1.Final]
at org.jboss.as.web.security.SecurityContextAssociationValve.invoke(SecurityContextAssociationValve.java:153) [jboss-as-web-7.1.1.Final.jar:7.1.1.Final]
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:155) [jbossweb-7.0.13.Final.jar:]
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102) [jbossweb-7.0.13.Final.jar:]
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109) [jbossweb-7.0.13.Final.jar:]
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:368) [jbossweb-7.0.13.Final.jar:]
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:877) [jbossweb-7.0.13.Final.jar:]
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:671) [jbossweb-7.0.13.Final.jar:]
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:930) [jbossweb-7.0.13.Final.jar:]
at java.lang.Thread.run(Unknown Source) [rt.jar:1.6.0_31]
1 ответ
Задача решена.
Два XML-файла, которые мне пришлось изменить, теперь выглядят так:
фрагмент springDispatcher-servlet.xml:
<context:component-scan base-package="com.company.db" />
<tx:annotation-driven />
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="primary" />
</bean>
<bean id="transactionManager" class="org.springframework.transaction.jta.JtaTransactionManager">
<property name="transactionManagerName" value="java:/TransactionManager" />
</bean>
persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0"
xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<persistence-unit name="primary" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>java:jboss/datasources/MysqlDS</jta-data-source>
<class>com.company.db.Location</class>
<properties>
<property name="hibernate.transaction.manager_lookup_class"
value="org.hibernate.transaction.JBossTransactionManagerLookup" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />
<property name="hibernate.hbm2ddl.auto" value="create-drop" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
<!-- Auto-detect entity classes -->
<property name="hibernate.archive.autodetection" value="class, hbm" />
</properties>
</persistence-unit>
</persistence>
Это все. Теперь я могу использовать БД MySQL с Hibernate и JBoss AS 7.