开发者

Spring - jdbcTemplate

I'm just beginning with Spring framework. I'm also using DBCP pooling and i'm still not sure how to work right with jdbcTemplate.

It is best practice to reuse created/injected jdbcTemplate instance between multiple DAOs or it is right to create jdbcTemplate for each DAO ?

I'm currently using annotation approach:

public class FooDAO  {

  private JdbcTemplate jdbcTemplate;

  @Autowired
  public void setDa开发者_StackOverflow社区tasource( DataSource dataSource ) {
     this.jdbcTemplate = new JdbcTemplate( dataSource );
  }
}

I'm aware about JdbcDaoSupport, but I don't know how to inject datasource, because method setDatasource is marked as final.

But still, I'm not sure if is best practice to reuse created jdbcTemplate or not.


Inject it in and share it. Don't call "new"; that takes control out of the hands of the Spring bean factory.


I'm aware about JdbcDaoSupport, but I don't know how to inject datasource, because method setDatasource is marked as final.

public class JdbcDaoSupportTest extends JdbcDaoSupport {

    public void insert() { 
        this.getJdbcTemplate().execute("insert into  tb_test1 values(1,'ycl','123')");
         System.out.println("complete...");
    }
}

Spring call set Method, don't care whether the method is final or not.

<bean id="jdbcDaoSupportTest" class="com.xxxxx.JdbcDaoSupportTest">
        <property name="dataSource" ref="dataSource" />
</bean>

then in your JdbcDaoSupportTest, you can call this.getJdbcTemplate() to get JdbcTemplate do any operator.


try {
    JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
    String sql = "select user.id as id,user.roll_no as createdId,user.name as name,user.type as company,role.role as year "
            + "from user_role join user on  user.id=user_role.user_id "
            + "join role on role.id=user_role.role_id "
            + "where (user.status='ACTIVE' or user.status='ADMIN') AND user.username='" + userName + "'";
    UserVo userDetails = jdbcTemplate.queryForObject(sql, new BeanPropertyRowMapper<UserVo>(UserVo.class));
    or
    Long company = jdbcTemplate.queryForObject(sql, Long.class);
    or
    List<UserVo> users = jdbcTemplate.query(sql, new BeanPropertyRowMapper<UserVo>(UserVo.class));
    logger.info("Retrieve user details by username");
    return userDetails;
} catch (Exception e) {
    logger.error("error in  getting UserDetails using UserName", e);
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜