我正在尝试使用以下代码建立jdbc连接。

我使用mysql数据库jpa2和spring4。如何获得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)

最佳答案

在上下文文件中指定数据库配置,如下所示

 <bean id="dataSource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">

    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="url" value="jdbc:mysql://localhost:3306/db" />
    <property name="username" value="root" />
    <property name="password" value="password" />
</bean>


然后开始使用spring依赖项注入将此数据源对象注入JDBCTest类。
例如:

 @autowired
 public void setDataSource(DataSource dataSource) {
        this.jdbcTemplate = new JdbcTemplate(dataSource);
    }


要么

 <bean id="jdbcTest" class="JDBCTest"><property name="dataSource" ref="datasource"/></bean>

09-05 11:56