从零开始的数据访问层:兼容

Spring JDBC 实践
本文介绍如何在Spring框架中使用JDBC进行数据库操作,包括通过JdbcTemplate和MyBatis实现数据的增删改查,并探讨了如何确保代码的兼容性和高效性。

我们面临的问题往往不是真正的从零开发,而是公司已经有了大量的旧有代码。指望每一个代码都按照我们的意思修改显然不可能,所以,我们要尽量兼容之前的写法。保证兼容性。

spring-jdbc

一个简单的JdbcTemplate的使用实例如下
一般而言,使用spring-jdbc主要由以下几种方式
使用JdbcTemplate

@Repository
public class UserDao {

    @Autowired
    private JdbcTemplate template;

    /**
     * 增加
     * @param user
     * @return
     */
    public int addUser(User user){
        String sql = "insert into User(userName,sex) values(?,?)";

        return template.update(sql, user.getUserName(),user.getSex());

使用提供的工具类JdbcDaoSupport


@Repository
public class UserDao2 extends JdbcDaoSupport{

    @Autowired
    public void setTemplate(JdbcTemplate template) {
        setJdbcTemplate(template);
    }


    public User getUserById(int userId){
        String sql = " select * from User where id = ? ";
        return getJdbcTemplate().queryForObject(sql, new BeanPropertyRowMapper<>(User.class), userId);

在spring注册bean的阶段,我们把里面所需的JdbcTemplate注入进去。

                    DataSource dataSource = bean.getClass().getAnnotation(DataSource.class);
                    TableShardingRuler tableShardingRuler = bean.getClass().getAnnotation(TableShardingRuler.class);
                    javax.sql.DataSource db = getDataSourceForThisDao(bean, beanName, dataSource, tableShardingRuler);
                    Method m = clazz.getDeclaredMethod("setDataSource", javax.sql.DataSource.class);
                    m.invoke(bean, db);

最后,底层实现如下

 public int upate(String sql, Object[] parameter, String dbtype) {
        int result = 0;
        JdbcTemplate jdbcTemplate = getJdbcTemplateWithDbType(dbtype, sql);
        if (parameter != null) {
            result = jdbcTemplate.update(sql, parameter);
        } else {
            result = jdbcTemplate.update(sql);
        }
        return result;
    }

MyBaits

对付Mybaits,我们要利用Mybaits的自带的拦截器机制.主要是根据在Mapper上的注解选择合适的数据源。

public Object intercept(Invocation invocation) throws Throwable {
    DataSource dataSource = Class.forName(className).getAnnotation(DataSource.class);
    String dataSourceAnotationValue = dataSource.value();
    MultiDataSourcesSwitcher.setDataSourceType(dataSourceAnotationValue);
    return invocation.proceed();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值