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