gpt4 book ai didi

java - EntityManager 为空

转载 作者:行者123 更新时间:2023-11-29 07:07:48 39 4
gpt4 key购买 nike

我是 EJB 的新手,创建一个用于娱乐/学习 EJB 的应用程序,下面是代码。

@Entity
@Table(name = "PERSON", schema = "experiment")
@NamedQuery(name = "Person.fetchAllPerson" , query = "select p from Person p")
public class Person implements Serializable {

private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Long id;
@Column(name = "name", length = 500)
private String name;
@Column(name = "age")
private Integer age;

public Long getId() {
return id;
}

// public void setId(Long id) {
// this.id = id;
// }

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Integer getAge() {
return age;
}

public void setAge(Integer age) {
this.age = age;
}

@Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}

@Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Person)) {
return false;
}
Person other = (Person) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}

@Override
public String toString() {
return "Person id ::: "+this.id + " | "+"name ::: "+this.name+" | "+"age ::: "+this.age;
}
}

上面是实体类:::下面是我的 bean (SessionBean)::

    @Stateless
public class PersonSessionBean implements PersonSessionBeanLocal {

@PersistenceContext(unitName = "OCDPU")
private EntityManager em;

private static final Logger LOGGER = Logger.getLogger(PersonSessionBean.class);

public void addPerson(Person p) {
LOGGER.info("ENTITY MANAGER ::: "+em);
em.persist(p);
}

public static PersonSessionBean getPersonSessionBean() {
return new PersonSessionBean();
}
}

下面是我的 persistence.xml:::

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.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_2_0.xsd">
<persistence-unit name="OCDPU" transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jta-data-source>java:/jndi_postgresql2</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect" />
<property name="hibernate.show_sql" value="true" />
</properties>
</persistence-unit>
</persistence>

以下是我的 .zul 文件 Controller :::

    public class Index2Controller extends GenericForwardComposer<Component> {

private final static Logger LOGGER = Logger.getLogger(Index2Controller.class);

private Textbox idTB,personTB,ageTB;
private Button btn;
private Window win;

// @Inject
// private PersonDao pd;

private PersonSessionBean psb;

{
psb = PersonSessionBean.getPersonSessionBean();
LOGGER.info("PersonSessionBean ::: "+psb);
}

public void onClick$btn(Event e) {
if(personTB.getText().equals("") ||ageTB.getText().equals("")){
//| idTB.getText().equals("")) {
this.alert("Enter all values");
return;
}

LOGGER.info("ONCLICK ::: PersonSessionBean ::: "+this.psb);

Integer i;
i = Integer.valueOf(Integer.parseInt(ageTB.getText()));
Person p = new Person();
p.setName(personTB.getText());
p.setAge(i);
LOGGER.error("Person is ::: "+p);
psb.addPerson(p);
personTB.setRawValue(null);
ageTB.setRawValue(null);
showNotification("Saved", win);
}

public void showNotification(String msg, Component ref) {
Clients.showNotification(msg, "info", ref, 700, 0, 1000);
}
}

错误::::

18:33:27,395 INFO  [com.discusit.ctrl.Index2Controller] (http--0.0.0.0-8080-5) ONCLICK ::: PersonSessionBean ::: com.discusit.bean.PersonSessionBean@3f2c4ca
18:33:27,396 ERROR [com.discusit.ctrl.Index2Controller] (http--0.0.0.0-8080-5) Person is ::: Person id ::: null | name ::: Naman | age ::: 26
18:33:27,397 INFO [com.discusit.bean.PersonSessionBean] (http--0.0.0.0-8080-5) ENTITY MANAGER ::: null
18:33:27,400 SEVERE [org.zkoss] (http--0.0.0.0-8080-5) >>java.lang.NullPointerException
>> at com.discusit.bean.PersonSessionBean.addPerson(PersonSessionBean.java:27)
>> at com.discusit.ctrl.Index2Controller.onClick$btn(Index2Controller.java:60)
>> at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
>> at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
>> at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
>> at java.lang.reflect.Method.invoke(Method.java:606)
>> at org.zkoss.zk.ui.event.GenericEventListener.onEvent(GenericEventListener.java:88)
>> at org.zkoss.zk.ui.AbstractComponent.onEvent(AbstractComponent.java:2742)
>> at org.zkoss.zk.ui.AbstractComponent.service(AbstractComponent.java:2713)
>> at org.zkoss.zk.ui.AbstractComponent.service(AbstractComponent.java:2654)
>> at org.zkoss.zk.ui.impl.EventProcessor.process(EventProcessor.java:136)
>> at org.zkoss.zk.ui.event.Events.sendEvent(Events.java:325)
>> at org.zkoss.zk.ui.event.Events.sendEvent(Events.java:348)
>> at org.zkoss.zk.ui.AbstractComponent$ForwardListener.onEvent(AbstractComponent.java:3180)
>> at org.zkoss.zk.ui.AbstractComponent.onEvent(AbstractComponent.java:2742)
>> at org.zkoss.zk.ui.AbstractComponent.service(AbstractComponent.java:2713)
>> at org.zkoss.zk.ui.AbstractComponent.service(AbstractComponent.java:2654)
>> at org.zkoss.zk.ui.impl.EventProcessor.process(EventProcessor.java:136)
>> at org.zkoss.zk.ui.impl.UiEngineImpl.processEvent(UiEngineImpl.java:1717)
>> at org.zkoss.zk.ui.impl.UiEngineImpl.process(UiEngineImpl.java:1502)
>> at org.zkoss.zk.ui.impl.UiEngineImpl.execUpdate(UiEngineImpl.java:1212)
>> at org.zkoss.zk.au.http.DHtmlUpdateServlet.process(DHtmlUpdateServlet.java:600)
>> at org.zkoss.zk.au.http.DHtmlUpdateServlet.doGet(DHtmlUpdateServlet.java:482)
>> at org.zkoss.zk.au.http.DHtmlUpdateServlet.doPost(DHtmlUpdateServlet.java:491)
>> at javax.servlet.http.HttpServlet.service(HttpServlet.java:754)
>> at javax.servlet.http.HttpServlet.service(HttpServlet.java:847)
>> at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:329)
>> at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248)
>> at org.jboss.weld.servlet.ConversationPropagationFilter.doFilter(ConversationPropagationFilter.java:62)
>> at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:280)
>> at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:248)
>> at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:275)
>> at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:161)
>> at org.jboss.as.jpa.interceptor.WebNonTxEmCloserValve.invoke(WebNonTxEmCloserValve.java:50)
>> at org.jboss.as.web.security.SecurityContextAssociationValve.invoke(SecurityContextAssociationValve.java:153)
>> at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:155)
>> at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
>> at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
>> at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:368)
>> at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:877)
>> at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:671)
>> at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:930)
>> at java.lang.Thread.run(Thread.java:724)

我正在使用 JBoss AS 7.1.1 final。我在其中创建了一个连接池。它连接到我局域网上的数据库。无法弄清楚出了什么问题。先感谢您。

我想我在 pom.xml 中遗漏了一些东西这是我的 pom:::

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.discusit</groupId>
<artifactId>OrgChartDemo</artifactId>
<version>1.0</version>
<packaging>war</packaging>

<name>OrgChartDemo</name>

<properties>
<endorsed.dir>${project.build.directory}/endorsed</endorsed.dir>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<dependencies>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>6.0</version>
<scope>provided</scope>
</dependency>

<!-- ZK DEPENDENCIES -->
<dependency>
<groupId>org.zkoss.zk</groupId>
<artifactId>zkplus</artifactId>
<version>6.5.2</version>
</dependency>
<dependency>
<groupId>org.zkoss.zk</groupId>
<artifactId>zhtml</artifactId>
<version>6.5.2</version>
</dependency>
<dependency>
<groupId>org.zkoss.zk</groupId>
<artifactId>zkbind</artifactId>
<version>6.5.2</version>
</dependency>
<dependency>
<groupId>org.zkoss.zk</groupId>
<artifactId>zul</artifactId>
<version>6.5.2</version>
</dependency>
<!-- ZK Dependencies ends -->

<!-- log4j -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<!-- log4j ends -->

<!-- javax.persistence 2.0 implementation -->
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.1.Final</version>
</dependency>
<!-- javax.persistence 2.0 ends -->
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.6</source>
<target>1.6</target>
<compilerArguments>
<endorseddirs>${endorsed.dir}</endorseddirs>
</compilerArguments>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.1.1</version>
<configuration>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>2.1</version>
<executions>
<execution>
<phase>validate</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<outputDirectory>${endorsed.dir}</outputDirectory>
<silent>true</silent>
<artifactItems>
<artifactItem>
<groupId>javax</groupId>
<artifactId>javaee-endorsed-api</artifactId>
<version>6.0</version>
<type>jar</type>
</artifactItem>
</artifactItems>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

最佳答案

像这样的资源注入(inject):

@PersistenceContext(unitName = "OCDPU")
private EntityManager em;

仅适用于其生命周期由容器管理的客户端类,即 EJB、JSF ManagedBean、CDI bean 或 servlet。在您的例子中,客户端类 PersonSessionBean 是一个 EJB,这没关系。错误在 PersonSessionBean 的实例化中:

psb = PersonSessionBean.getPersonSessionBean();

这一行是错误的,因为 EJB 应该通过 @EJB 注解注入(inject):

@EJB PersonSessionBean psb;

或通过 JNDI 查找检索。

但您还必须知道,客户端类 Index2Controller 也是容器管理的,从发布的代码来看,情况似乎并非如此。

有用的链接:Accessing Enterprise Beans来自 Oracle 的 Java EE 6 教程。

关于java - EntityManager 为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17835042/

39 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com