问题
I am new to EJB, creating an application for fun/learning EJB following is the code.
@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;
}
}
Above is the Entity class ::: Below is my 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();
}
}
below is my 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>
Following is my .zul file 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);
}
}
THE ERROR ::::
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)
I am using JBoss AS 7.1.1 final.In which I created a connection pool.Which is connected to my database on my lan. Unable to figure out whats wrong. Thank you in advance.
I guess I am missing something in pom.xml here is my 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>
回答1:
Resource injection like this:
@PersistenceContext(unitName = "OCDPU")
private EntityManager em;
only works in a client class whose lifecycle is managed by the container, i.e. an EJB, a JSF ManagedBean, a CDI bean or a servlet. In your case, the client class PersonSessionBean
is an EJB, and that's OK. The error is in the instantiation of PersonSessionBean
:
psb = PersonSessionBean.getPersonSessionBean();
This line is wrong, because an EJB should be either injected through @EJB
annotation:
@EJB PersonSessionBean psb;
or retrieved through JNDI lookup.
But you also must be aware that the client class Index2Controller
is container-managed too, and from the code posted it looks like it's not the case.
Useful link: Accessing Enterprise Beans from Oracle's Java EE 6 Tutorial.
来源:https://stackoverflow.com/questions/17835042/entitymanager-is-null