SpringBoot中JdbcTemplate和事务的实现(配置类 不用xml文件)

SpringBoot中JdbcTemplate和事务的实现

  • 首先导入pom依赖
  • 配置类
@Configuration
@ComponentScan(basePackages = "org.ljw")//扫描基准包
@EnableTransactionManagement(proxyTargetClass = true)//开启事务管理 解析注解@Transactional   true开启cglib代理
public class SpringConfig {
    //通过druid链接池获取数据源
    @Bean //注解后   交给spring管理的bean
    public DruidDataSource getDruidDataSource(){
            //这种方式更通用
            //    Thread.currentThread() 当前线程对象
            //    getContextClassLoader() 是线程对象的方法,可以获取到当期线程的类加载器对象
            //    getResourceAsStream() 直接返回一个流对象
        DruidDataSource dataSource = new DruidDataSource();
        InputStream inputStream = null;
        try {
            inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("druid.properties");
            Properties properties = new Properties();
            properties.load(inputStream);
            //从properties文件中获取驱动并赋给数据源
            dataSource.setDriverClassName(properties.getProperty("driver"));
            dataSource.setUrl(properties.getProperty("url"));
            dataSource.setUsername(properties.getProperty("user"));
            dataSource.setPassword(properties.getProperty("pwd"));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                //关闭流
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return dataSource;
    }
    //获取jdbcTemplate类
    @Bean
    public JdbcTemplate getJdbcTemplate(DruidDataSource dataSource){
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        jdbcTemplate.setDataSource(dataSource);
        return jdbcTemplate;
    }
    //事务管理
    @Bean
    public DataSourceTransactionManager getDataSourceTransactionManager(DruidDataSource dataSource){
        DataSourceTransactionManager transactionManager = new DataSourceTransactionManager();
        transactionManager.setDataSource(dataSource);
        return transactionManager;
    }
}
  • properties文件
driver:com.mysql.cj.jdbc.Driver
url:jdbc:mysql://localhost:3306/shopping_system?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai&rewriteBatchedStatements=true
user:root
pwd:root
  • bean
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Goods {
    private Integer goodId;
    private Integer typeId;
    private String goodName;
    private Integer goodNum;
    private Float goodPrice;



    public Goods(Integer typeId, String goodName, Integer goodNum, Float goodPrice) {
        this.typeId = typeId;
        this.goodName = goodName;
        this.goodNum = goodNum;
        this.goodPrice = goodPrice;
    }
}
  • dao接口
public interface GoodsDao {
    public List<Goods> findAll();
    public Integer save(Goods goods);
    public Integer update(Goods goods);
    public Integer delete(Integer id);

}
  • dao实现
@Controller
public class GoodsDaoImpl implements GoodsDao {
    @Autowired
    JdbcTemplate jdbcTemplate;
    @Override
    public List<Goods> findAll() {
        String sql = "select * from goods";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Goods.class));
    }

    @Override
    public Integer save(Goods goods) {
        String sql = "INSERT INTO goods VALUES(NULL,?,?,?,?)";
        return jdbcTemplate.update(sql,goods.getTypeId(),goods.getGoodName(),goods.getGoodNum(),goods.getGoodPrice());
    }


    @Override
    public Integer update(Goods goods) {
        String sql = "UPDATE goods SET type_id=?,good_name=?,good_num=?,good_price=? WHERE good_id=?";
        return jdbcTemplate.update(sql,goods.getTypeId(),goods.getGoodName(),goods.getGoodNum(),goods.getGoodPrice(),goods.getGoodId());
    }

    @Override
    public Integer delete(Integer id) {
        String sql = "delete from goods where good_id = ?";
        return jdbcTemplate.update(sql,id);
    }
}

  • service接口
public interface GoodsService {
    public List<Goods> findAll();
    public Integer saveAndUpdate();
    public Integer delete(Integer id);


}
  • service实现
@Service
@Transactional     //开启事务层
public class GoodsServiceImpl implements GoodsService {
    @Autowired
    GoodsDao goodsDao;
    @Override
    public List<Goods> findAll() {
        return goodsDao.findAll();
    }

    @Override
    public Integer saveAndUpdate() {
        //添加的对象
        Goods goods = new Goods(3, "test66", 2, 2f);
        //修改的对象
        Goods goods2 = new Goods(60, 3, "test666", 2, 2f);
        Integer rows = goodsDao.save(goods);
        Integer rows2 = goodsDao.update(goods2);
        return rows + rows2;
    }


    @Override
    public Integer delete(Integer id) {
        return goodsDao.delete(id);
    }

}

事务开启后saveAndUpdate()方法中添加和修改必须同时成功,有一个失败则数据库不更新

  • 测试
public class MyTestOrg {
    @Test
    public void test01(){
        ApplicationContext context = new AnnotationConfigApplicationContext(SpringConfig.class);
        GoodsService goodsService = context.getBean("goodsServiceImpl",GoodsServiceImpl.class);
        int rows = goodsService.saveAndUpdate();

        System.out.println(rows);

    }
}
上一篇:14-Spring5 整合JdbcTemplate的步骤


下一篇:当JDBCTemplate需要返回参数时