Note that there are some explanatory texts on larger screens.

plurals
  1. POGlassfish JPA: Problems injecting EntityManager
    primarykey
    data
    text
    <p>I am new to Java EE. I tried to get some first examples running (JPA). I am using Glassfish v3. The trouble is that I don't get the App Server injecting the EntityManager. Hear is one example <a href="http://www.adam-bien.com/roller/abien/entry/ejb_3_persistence_jpa_for" rel="nofollow noreferrer">http://www.adam-bien.com/roller/abien/entry/ejb_3_persistence_jpa_for</a> which I extended with a JSP client.</p> <p>Entity:</p> <pre><code> package beans; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; @Entity public class Book { @Id @GeneratedValue private Long id; private String title; private String subtitle; public Book() { } public Book(String title) { this.title = title; } } </code></pre> <p>BookService Interface:</p> <pre><code> package beans; import javax.ejb.Local; @Local public interface BookService { Book createOrUpdate(Book book); void remove(Book book); Book find(Object id); } </code></pre> <p>BookServiceBean:</p> <pre><code> package beans; import javax.ejb.Stateless; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; @Stateless public class BookServiceBean implements BookService { @PersistenceContext private EntityManager em; public Book createOrUpdate(Book book) { return em.merge(book); } public void remove(Book book) { em.remove(em.merge(book)); } public Book find(Object id) { return em.find(Book.class, id); } } </code></pre> <p>persistence.xml:</p> <pre><code>&lt;persistence&gt; &lt;persistence-unit name="sample" transaction-type="JTA"&gt; &lt;jta-data-source&gt;jdbc/MarcelsDataSource&lt;/jta-data-source&gt; &lt;properties&gt; &lt;property name="eclipselink.ddl-generation" value="create-tables"/&gt; &lt;/properties&gt; &lt;/persistence-unit&gt; &lt;/persistence&gt; </code></pre> <p>index.jsp:</p> <pre><code>&lt;%@ page import="beans.BookServiceBean" %&gt; &lt;%@ page import="beans.Book" %&gt; &lt;html&gt; &lt;body&gt; &lt;% BookServiceBean bs = new BookServiceBean(); Book b = new Book("Superman"); bs.createOrUpdate(b); %&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>If I run the example I get a java.lang.NullPointerException in the createOrUpdate() method so the entityManager is obviously not injected correctly. I tried to find a remedy for days now and some help would be highly appreciated. </p> <p>Thanks</p> <p>Marcel </p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload