栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

14-Spring5 整合JdbcTemplate的步骤

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

14-Spring5 整合JdbcTemplate的步骤

1.什么是 JdbcTemplate

Spring 框架对 JDBC 进行封装,使用 JdbcTemplate 方便实现对数据库操作

2.导入需要的jar包

这是实现JdbcTemplate操作需要的jar包

3.编写代码

1.创建数据库


2.编写java代码

配置文件bean1.xml



    
    

    
    
    
        
        
        
        
    

    
    
    
        
        
    


BookService

package com.limi.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

@Service
public class BookService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

	//获取书的数量
    public int getBookCount(){
        String sql ="select count(*) from t_book";
        Integer count = jdbcTemplate.queryForObject(sql, Integer.class);
        return count;
    }
}

测试类MyTest

package com.limi.test;
import com.limi.service.BookService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;

public class MyTest {

    @Test
    public void test1(){
        //1.加载bean的xml文件, 以src为根目录
        ApplicationContext context = new ClassPathXmlApplicationContext("bean1.xml");

        //2.获取配置的对象, 参数1:bean的id值, 参数2: 类名.class
        BookService bookService = context.getBean("bookService", BookService.class);

        //3.使用对象
        System.out.println("书的数量="+bookService.getBookCount());

    }
}


3.测试结果

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/462128.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号