Spring + JDBC无法连接数据库

时间:2015-07-22 08:11:40

标签: java mysql spring maven jdbc

我正在尝试使用spring框架在mysql数据库上做一些crud操作。 我添加了maven依赖项,这是我的datasource.xml:

    <beans xmlns="http://www.springframework.org/schema/beans"
           xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

      <bean id="dataSource"
            class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost/Rubrica?" />
        <property name="username" value="user" />
        <property name="password" value="password" />
      </bean>

      <bean id="JDBCEntryDAO" class="net.tirasa.jdbc_spring_addressbook">  
        <property name="JDBC_Spring_EntryDAO" ref="JDBC_Spring_EntryDAO" />
      </bean>       
    </beans>

当我运行应用程序时,我得到一个Nullpointer异常(在指定的行),我无法连接到数据库,这是抛出异常的方法:

    @Override
    public List<Entry> list() {
        List<Entry> res = new ArrayList<Entry>();
        String sql = "SELECT * FROM Person";

        try {
            //open connection            

            Connection conn = datasource.getConnection(); //<----NULL POINTER EXCEPTION 

            //prepare the statement
            PreparedStatement ps = conn.prepareStatement(sql);

            //execute 
            ResultSet resultSet = ps.executeQuery(sql);

            //populate entry
            while (resultSet.next()) {
                Entry entry = new Entry();
                entry.setId(resultSet.getInt("id"));
                entry.setCn(resultSet.getString("cn"));
                entry.setSn(resultSet.getString("sn"));
                entry.setPn(resultSet.getString("pn"));
                res.add(entry);
            }
            resultSet.close();
            ps.close();
            conn.close();
        } catch (SQLException ex) {
            Logger.getLogger(JDBC_Spring_EntryDAO.class.getName()).log(Level.SEVERE, null, ex);
        }
        return res;
    }

1 个答案:

答案 0 :(得分:1)

我认为你需要注入数据源

  <bean id="JDBCEntryDAO" class="net.tirasa.jdbc_spring_addressbook">  
    <property name="JDBC_Spring_EntryDAO" ref="JDBC_Spring_EntryDAO" />
    <property name="dataSource" ref="dataSource" />
  </bean>