[英]Retrieving entities in JPQL, EclipseLink and MySQL
我在一個名為Books的數據庫中堅持使用一些Book實體。 這是我的persistence.xml:
<persistence-unit name="mysqltest" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<!-- list all classes -->
<class>it.mysql.beginner.User</class>
<class>it.mysql.beginner.Book</class>
<class>it.mysql.beginner.Kind</class>
<properties>
<!-- some properties needed by persistence provider:
- driver
- db url
- db user name
- db user password -->
<property name="javax.persistence.target-database" value="MySQL"/>
<property name="javax.persistence.logging.level" value="INFO"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost/Books"/>
<property name="javax.persistence.jdbc.user" value="lory"/>
<property name="javax.persistence.jdbc.password" value="brookhaven12#"/>
<property name="eclipselink.ddl-generation.output-mode" value="database" />
<property name="eclipselink.ddl-generation" value="create-tables" />
</properties>
</persistence-unit>
這是一個通用的jpaDAO
public abstract class jpaDAO<E> {
protected Class<E> entityClass;
@PersistenceContext(unitName = "mysqltest")
protected EntityManager em;
@SuppressWarnings("unchecked")
public jpaDAO() {
ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass();
this.entityClass = (Class<E>) genericSuperclass.getActualTypeArguments()[0];
}
public List<E> findAll() {
TypedQuery<E> q = em.createQuery("SELECT h FROM " + entityClass.getSimpleName() + " h", entityClass);
return q.getResultList();
}
...
這是一本BookDAO:
public class BookDAO extends jpaDAO<Book> {
public List<Book> findByAuthor(String author) {
List<Book> bookList;
TypedQuery<Book> query = em.createQuery("SELECT b FROM Book b WHERE b.author = author", entityClass);
query.setParameter("author", author);
bookList = query.getResultList();
return bookList;
}
}
在我執行的主程序中:
List<Book> allBooks;
BookDAO bookDAO = new BookDAO();
allBooks = bookDAO.findByAuthor("Stephen King");
然后是bookDao.findAll()和bookDao.findByAuthor(“作者”)但我得到NullPointerException所以我想這個列表allBooks是空的。 我不明白......數據庫中存有書籍,為什么不能得到它們?
你正在調用new BookDAO()
。 但是BookDAO構造函數,而不是超類構造函數,都沒有初始化em
字段。 所以它是null。 因此,當您在em
上調用方法時,會出現NullPointerException。
EntityManager應該由容器注入(如果你在EJB / CDI容器內部運行,或者如果你使用的是Spring,則沒有指定)。 但是,只有從容器中獲取BookDAO實例才有可能。 如果您自己實例化,容器對此對象一無所知,因此無法注入此對象的任何字段。
因此,您的BookDAO應該注入其調用者(它本身應該由容器實例化)。
如果不知道呼叫者是什么,以及你在哪個環境中運行,就不可能提供更多細節。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.