在spring应用程序中实现jdbc dao支持的问题

时间:2014-06-13 08:10:05

标签: spring-mvc jdbc dao

我尝试使用jdbcdao访问数据库,如下例所示: http://www.mkyong.com/spring/spring-jdbctemplate-jdbcdaosupport-examples/

userdao,userdaoimpl,daocontext和datacontext.xml如下:

DAOIMPL

public class UserDAOImpl extends JdbcDaoSupport implements UserDAO {    

    /*Creates User */
    public void insertUser(User user){
        String sql = "INSERT INTO Users " +
            "(id, username, password,role) VALUES (?, ?, ?,?)";

        getJdbcTemplate().update(sql, new Object[] { user.getUserId(),
                user.getUserName(),user.getPassWord() 
        });

    }
}

DAO

import java.util.List;

import spring.web.models.User;

public interface UserDAO {
    public void insertUser(User user);

}

DAOCONTEXT.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-4.0.xsd">

    <bean id="userDAO" class="spring.web.dao.impl.UserDAOImpl">
        <property name="primaryDataSource" ref="oracleDataSource" />
    </bean>

</beans>

DATA-context.xml中

<?xml version="1.0"?>
<beans
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://www.springframework.org/schema/beans">

    <bean  id="oracleDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property value="oracle.jdbc.OracleDriver" name="driverClassName" />
        <property value="jdbc:oracle:thin:@192.168.72.68:1521:d2he"
            name="url" />
        <property value="aaryal_1" name="username" />
        <property value="oracle" name="password" />
    </bean>
</beans>

我面临的错误如下:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userDAO' defined in class path resource [dao-context.xml]:
Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: 
Invalid property 'primaryDataSource' of bean class [spring.web.dao.impl.UserDAOImpl]: 
Bean property 'primaryDataSource' is not writable or has an invalid setter method.
 Does the parameter type of the setter match the return type of the getter?

请建议我错过了什么。

1 个答案:

答案 0 :(得分:1)

您需要在UserDAOImpl类中使用setPrimaryDataSource方法。错误说明了一切。它期待你班级中有一个名为primaryDataSource的属性,但找不到它。因此错误。

你需要这样做:

private DataSource dataSource;

public void setPrimaryDataSource(DataSource dataSource) {
    this.dataSource = dataSource;
}

编辑:

如果您浏览JdbcDaoSupport的API,则setDataSource方法已存在。因此,要解决您的错误,您可以执行上述操作,或者只需将DataSource bean名称重命名为dataSource