大家好,我正在使用rest和mysql作爲我的數據庫。從MySQL獲取空指針異常db db
下面是我的休息獲取代碼用於獲取allbooks(資源)
@GET
@Produces(MediaType.APPLICATION_JSON)
public Response getBooks(@QueryParam("format") String format) {
//line35: return Response.status(Status.OK).entity((new GenericEntity<List<Book>>(bookService.getAllBooks()) {
})).header(HttpHeaders.CONTENT_TYPE, "XML".equalsIgnoreCase(format)
? MediaType.APPLICATION_XML + ";charset=UTF-8" : MediaType.APPLICATION_JSON + ";charset=UTF-8").build();
}
下面是我的服務
public List<Book> getAllBooks() {
//books service line 24 return new ArrayList<Book>(booksDao.getAllBooks());
/* return new ArrayList<Book>(books.values()); */
}
BooksDAO類
public class BooksDAO {
private JdbcTemplate jdbcTemplate;
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public List<Book> getAllBooks() {
//books dao line24: return jdbcTemplate.query("select * from books.books_table", new RowMapper<Book>() {
@Override
public Book mapRow(ResultSet rs, int rownumber) throws SQLException {
Book e = new Book();
e.setId(rs.getInt(1));
e.setName(rs.getString(2));
e.setPrice(rs.getString(3));
e.setAuthor(rs.getString(4));
return e;
}
});
}
下面是我bean.I上午使用springJDBC
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="ds"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/xxxx" />
<property name="username" value="xxxx" />
<property name="password" value="xxxx" />
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="ds"></property>
</bean>
<bean id="edao" class="com.nag.library.database.BooksDAO">
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>
</beans>
在不連接數據庫我很好得到JSON/XML響應,但是當我連接DB其拋出一個空指針異常
Aug 16, 2016 10:43:08 AM org.apache.catalina.core.StandardWrapperValve
invoke
SEVERE: Servlet.service() for servlet Jersey Web Application threw exception
java.lang.NullPointerException
at com.nag.library.database.BooksDAO.getAllBooks(BooksDAO.java:24)
at com.nag.library.service.BookService.getAllBooks(BookService.java:24)
at com.nag.library.resource.BookResource.getBooks(BookResource.java:35)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at java.lang.Thread.run(Unknown Source)
在那裏我做wrong.Please引導我的東西。
謝謝
您在哪一條指令中擁有NPE? 你應該顯示所有BooksDAO類 – davidxxx
NPE嗎?你能說清楚嗎?我很抱歉,我只是一個學習者。 –
沒問題:NPE = NullPointerException – davidxxx