Как подключиться к внешнему серверу MySQL из Glassfish - PullRequest
0 голосов
/ 17 октября 2011

Я пытаюсь подключиться к удаленному серверу MySQL. Я успешно установил соединение из Eclipse (представление DataSource) и теперь могу просматривать содержимое базы данных.

Но теперь я хочу иметь возможность использовать эту базу данных в своем приложении Java EE 6, и она не работает. Что я пробовал:

Добавлены имя пользователя, пароль, имя сервера, URL, порт в качестве свойств в панели администрирования.

Это URL, который я использую: jdbc: mysql: // MYHOST: 3306 / MYDATABASE, вероятно, в этом нет ничего плохого. Я также добавил свой IP-адрес в удаленный список в CPanel, поэтому мне разрешено удаленное подключение. Я скачал этот драйвер: http://www.java.net/external?url=http://dev.mysql.com/downloads/connector/j/ и добавил его в папку domains / domain1 / lib.

Я также вижу там 4 другие папки; базы данных, ext, applibs и классы, поэтому я добавил драйвер в эти папки, чтобы быть уверенным. Это неправильно? Нужно ли добавлять драйвер в какую-то папку в моем проекте Eclipse, чтобы он работал?

Тип ресурса: javax.sql.DataSource Имя класса источника данных: com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource

UPDATE

HTTP-статус 500 -

тип Отчет об исключении

сообщение

descriptionСервер обнаружил внутреннюю ошибку (), которая помешала это от выполнения этого запроса.

исключение

javax.servlet.ServletException: WELD-000049 Невозможно вызвать [метод] @PostConstruct public no.breakpoint.sertifikat.interfaces.QuestionController.intialize () на no.breakpoint.sertifikat.interfaces.QuestionController@10614f3d

первопричина

org.jboss.weld.exceptions.WeldException: WELD-000049 Невозможно вызвать [метод] @PostConstruct public no.breakpoint.sertifikat.interfaces.QuestionController.intialize () на no.breakpoint.sertifikat.interfaces.QuestionController@10614f3d

первопричина

java.lang.reflect.InvocationTargetException

первопричина

javax.ejb.EJBException

первопричина

java.lang.NullPointerException

note Примечание. Полные трассировки стека исключения и его первопричины: доступно в журналах GlassFish Server с открытым исходным кодом версии 3.1.1. GlassFish Server с открытым исходным кодом, версия 3.1.1

EJB:

    @Override
    public List<Question> all() {

//      List<Question> list = new ArrayList<Question>();
//      Question question = new Question();
//      question.setDescription("SDfasfasdfasf");
//      question.setId(32);
//      question.setImage("sdafasdf");
//      list.add(question);
//      
//      return list;
//      
        return questionDao.all();

    }

JSF bean

@Named
@RequestScoped
public class QuestionController {

    @EJB
    private QuestionLocalBusiness questionManager;

    private List<Question> questions;

    @PostConstruct
    public void intialize() {
        questions = questionManager.all();      
    }

    public void setQuestions(List<Question> list) {
        questions = list;
    }

    public List<Question> getQuestions() {
        return questions;
    }
}

Журнал ошибок:

WARNING: StandardWrapperValve[FacesServlet]: PWC1406: Servlet.service() for servlet FacesServlet threw exception
org.jboss.weld.exceptions.WeldException: WELD-000049 Unable to invoke [method] @PostConstruct public com.bpoint.interfaces.QuestionController.intialize() on com.bpoint.interfaces.QuestionController@10614f3d
    at org.jboss.weld.bean.AbstractClassBean.defaultPostConstruct(AbstractClassBean.java:595)
    at org.jboss.weld.bean.ManagedBean$ManagedBeanInjectionTarget.postConstruct(ManagedBean.java:200)
    at org.jboss.weld.bean.ManagedBean.create(ManagedBean.java:340)
    at org.jboss.weld.context.AbstractContext.get(AbstractContext.java:121)
    at org.jboss.weld.bean.proxy.ContextBeanInstance.getInstance(ContextBeanInstance.java:99)
    at org.jboss.weld.bean.proxy.ProxyMethodHandler.invoke(ProxyMethodHandler.java:87)
    at no.breakpoint.sertifikat.interfaces.org$jboss$weld$bean-SertifikatWeb_war-ManagedBean-class_no$breakpoint$sertifikat$interfaces$QuestionController_$$_WeldClientProxy.getQuestions(org$jboss$weld$bean-SertifikatWeb_war-ManagedBean-class_no$breakpoint$sertifikat$interfaces$QuestionController_$$_WeldClientProxy.java)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at javax.el.BeanELResolver.getValue(BeanELResolver.java:302)
    at com.sun.faces.el.DemuxCompositeELResolver._getValue(DemuxCompositeELResolver.java:176)
    at com.sun.faces.el.DemuxCompositeELResolver.getValue(DemuxCompositeELResolver.java:203)
    at com.sun.el.parser.AstValue.getValue(AstValue.java:116)
    at com.sun.el.parser.AstValue.getValue(AstValue.java:163)
    at com.sun.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:219)
    at org.jboss.weld.el.WeldValueExpression.getValue(WeldValueExpression.java:55)
    at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:109)
    at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:194)
    at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:182)
    at javax.faces.component.UIData.getValue(UIData.java:731)
    at javax.faces.component.UIData.getDataModel(UIData.java:1798)
    at javax.faces.component.UIData.getRowCount(UIData.java:356)
    at org.primefaces.component.datatable.DataTableRenderer.encodeTbody(DataTableRenderer.java:456)
    at org.primefaces.component.datatable.DataTableRenderer.encodeRegularTable(DataTableRenderer.java:201)
    at org.primefaces.component.datatable.DataTableRenderer.encodeMarkup(DataTableRenderer.java:180)
    at org.primefaces.component.datatable.DataTableRenderer.encodeEnd(DataTableRenderer.java:85)
    at javax.faces.component.UIComponentBase.encodeEnd(UIComponentBase.java:875)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1763)
    at javax.faces.render.Renderer.encodeChildren(Renderer.java:168)
    at javax.faces.component.UIComponentBase.encodeChildren(UIComponentBase.java:845)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1756)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1759)
    at javax.faces.component.UIComponent.encodeAll(UIComponent.java:1759)
    at com.sun.faces.application.view.FaceletViewHandlingStrategy.renderView(FaceletViewHandlingStrategy.java:401)
    at com.sun.faces.application.view.MultiViewHandler.renderView(MultiViewHandler.java:131)
    at javax.faces.application.ViewHandlerWrapper.renderView(ViewHandlerWrapper.java:288)
    at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:121)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
    at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:139)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:594)
    at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1539)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:281)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:98)
    at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:91)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:162)
    at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:330)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:174)
    at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:828)
    at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:725)
    at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1019)
    at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:225)
    at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
    at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
    at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
    at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
    at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
    at java.lang.Thread.run(Thread.java:662)
Caused by: java.lang.reflect.InvocationTargetException  at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.jboss.weld.util.reflection.SecureReflections$13.work(SecureReflections.java:305)
    at org.jboss.weld.util.reflection.SecureReflectionAccess.run(SecureReflectionAccess.java:54)
    at org.jboss.weld.util.reflection.SecureReflectionAccess.runAsInvocation(SecureReflectionAccess.java:163)
    at org.jboss.weld.util.reflection.SecureReflections.invoke(SecureReflections.java:299)
    at org.jboss.weld.introspector.jlr.WeldMethodImpl.invoke(WeldMethodImpl.java:193)
    at org.jboss.weld.bean.AbstractClassBean.defaultPostConstruct(AbstractClassBean.java:591)
    ... 66 more
Caused by: javax.ejb.EJBException
    at com.sun.ejb.containers.BaseContainer.processSystemException(BaseContainer.java:5193)
    at com.sun.ejb.containers.BaseContainer.completeNewTx(BaseContainer.java:5091)
    at com.sun.ejb.containers.BaseContainer.postInvokeTx(BaseContainer.java:4879)
    at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2039)
    at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:1990)
    at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:222)
    at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:88)
    at $Proxy231.all(Unknown Source)
    at no.breakpoint.sertifikat.interfaces.QuestionController.intialize(QuestionController.java:24)
    ... 76 more
Caused by: java.lang.NullPointerException
    at no.breakpoint.sertifikat.application.QuestionManagerEJB.all(QuestionManagerEJB.java:52)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.glassfish.ejb.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:1052)
    at org.glassfish.ejb.security.application.EJBSecurityManager.invoke(EJBSecurityManager.java:1124)
    at com.sun.ejb.containers.BaseContainer.invokeBeanMethod(BaseContainer.java:5366)
    at com.sun.ejb.EjbInvocation.invokeBeanMethod(EjbInvocation.java:619)
    at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:800)
    at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:571)
    at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.doAround(SystemInterceptorProxy.java:162)
    at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.aroundInvoke(SystemInterceptorProxy.java:144)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:861)
    at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:800)
    at com.sun.ejb.containers.interceptors.InterceptorManager.intercept(InterceptorManager.java:370)
    at com.sun.ejb.containers.BaseContainer.__intercept(BaseContainer.java:5338)
    at com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:5326)
    at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:214)
    ... 79 more

DAO:

package no.breakpoint.sertifikat.infrastructure;

import java.util.List;

@NamedQuery(name = "allQuestions", query = "SELECT q FROM Question q")
public class DefaultQuestionDao implements QuestionDao {

    @PersistenceContext(unitName = "MyDatabasePU")
    private EntityManager entityManager;

    @Override
    public void create(Question question) {
        entityManager.persist(question);
    }

    @Override
    public void delete(Question question) {
        entityManager.remove(question);
    }

    @Override
    public void update(Question question) {
        entityManager.merge(question);
    }

    @Override
    public Question read(Integer id) {
        return entityManager.find(Question.class, id);
    }

    @Override
    public List<Question> all() {
        TypedQuery<Question> query = entityManager.createNamedQuery("allQuestions", Question.class);
        return query.getResultList();
    }
}

Если я раскомментирую то, что я сейчас прокомментировал, таблица данных, которую я использую, работает, и ошибка 500 исчезает. Но когда я пытаюсь получить его из базы данных, это дает мне это.

1 Ответ

2 голосов
/ 17 октября 2011

Вызывается: java.lang.NullPointerException at no.breakpoint.sertifikat.application.QuestionManagerEJB.all (QuestionManagerEJB.java:52)

Итак, EntityManager равно null? @PersistenceContext будет внедрен только в управляемые классы контейнера / инфраструктуры, такие как @Stateless EJB, компонент CDI @Named, JSF @ManagedBean боб и т. Д. Однако ваш DefaultQuestionDao, похоже, вообще не управляется.

Учитывая настройки до сих пор, я бы начал отмечать ваш DefaultQuestionDao как @Stateless EJB. Вся установка, между прочим, в лучшем случае сбивает с толку, трассировка стека говорит о QuestionManagerEJB, который я не вижу в фрагментах кода, только о DefaultQuestionDao и QuestionBusinessLocal. Возможно, вам нужно добавить DefaultQuestionDao как @EJB в ваш QuestionManagerEJB.

Кроме того, есть еще одна проблема: @NamedQuery необходимо аннотировать для класса @Entity или одного из его суперклассов, иначе он не будет найден.

...