Springboot整合JDBCTemplate

浪子不回头ぞ 提交于 2019-12-16 11:51:16

概述

前面有关于Springboot整合Mybatis文章,传送门    ,对于JDBCTemlate实际也是用来操作数据库的持久层框架,这里使用Springboot整合JDBCTemlate,如何使用JDBCTemlate操作数据库,和Springboot整合Mybatis一样,数据库连接池还是使用默认的连接池tomcat.jdbc.pool,我们不再配置Druid或者其他连接池,关于Springboot如何整合Druid或者其他连接池。

整合

导入依赖,在idea中通过Sping提供的插件直接引入,如下

 

或者手动导入

<dependency>
   <groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>

创建一个接口

public interface StuDao {
    public int add(Student student);
}

实现类

@Repository
public class StuDaoImpl implements  StuDao {
    @Autowired
    private NamedParameterJdbcTemplate jdbcTemplate;
    @Override
    public int add(Student student) {
        String sql = "insert into tb_stu(id,name) " +
                "values(:id,:name)";
        Map<String, Object> param = new HashMap<>();
        param.put("id",student.getId());
        param.put("name", student.getName());
        return (int) jdbcTemplate.update(sql, param);
    }
}

测试

@RunWith(SpringRunner.class)
@SpringBootTest
public class JdbcApplicationTests {
    @Autowired
    StuDao stuDao;
    @Test
    public void contextLoads() throws SQLException {
        Student student = new Student();
        student.setId(3);
        student.setName("测试123");
        stuDao.add(student);
    }
}

至此 Springboot整合mybatis完成,有疑问可以关注我的公众号 java一号  联系

个人独立站点: www.javayihao.top

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!