【发布时间】:2016-03-26 06:18:03
【问题描述】:
我正在尝试使用以下代码获取 jdbc 连接。
我使用 mysql 数据库 jpa2 和 spring 4。如何获取 jdbc 连接并从 mysql 数据库中检索此值
import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.sql.DataSource;
import org.springframework.jdbc.core.JdbcTemplate;
@ManagedBean
@ViewScoped
public class JDBCTest implements Serializable{
private JdbcTemplate jdbcTemplate;
void setDataSource(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
}
private static final long serialVersionUID = 1L;
public void testDB(){
Connection con=null;
try {
con = getJdbcTemplate().getDataSource().getConnection();
PreparedStatement pst=con.prepareStatement("select * from global_class");
ResultSet st=pst.executeQuery();
while(st.next()){
System.out.println("Class Name :"+st.getString(1));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
}
当在这段代码之上运行时,我得到了这个异常
WARNING: #{jDBCTest.testDB}: java.lang.NullPointerException
javax.faces.FacesException: #{jDBCTest.testDB}: java.lang.NullPointerException
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:118)
at org.springframework.faces.webflow.FlowActionListener.processAction(FlowActionListener.java:71)
at org.springframework.faces.model.SelectionTrackingActionListener.processAction(SelectionTrackingActionListener.java:64)
at javax.faces.component.UICommand.broadcast(UICommand.java:315)
【问题讨论】:
-
请发布您的完整代码,以便我为您提供帮助。
-
“当我执行 this 代码时,我得到...” 这里的
this是什么?代码在哪里? -
你从spring容器中注入数据源对象了吗?
-
我将使用@ManagedProperty("#{jdbcTemplate}") 解决这个问题
标签: java spring hibernate jdbc