小试SpringJdbcTemplate

本文介绍如何在Spring框架中使用JdbcTemplate进行数据库操作,包括配置、基本CRUD操作、批量操作及事务管理等。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

小试SpringJdbcTemplate

maven下的jdbcTemplate

spring.xml配置

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
    <context:property-placeholder location="classpath:dbconfig.properties"/>
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
        <property name="driverClassName" value="${driverClassName}"/>
        <property name="url" value="${url}"/>
        <property name="username" value="${user}"/>
        <property name="password" value="${password}"/>
        <property name="initialSize" value="${initialSize}"/>
        <property name="minIdle" value="${minIdle}"/>
        <property name="maxActive" value="${maxActive}"/>
        <property name="maxWait" value="${maxWait}"/>
        <property name="filters" value="${filters}"/>
    </bean>

    <!--注入灵魂-->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <constructor-arg name="dataSource" ref="dataSource"/>
    </bean>

    <!--注入大法师灵魂,当你有多个参数需要传递时,请注入他-->
    <bean id="namedParameterJdbcTemplate" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
        <constructor-arg name="dataSource" ref="dataSource"/>
    </bean>

    <!--注入事务管理-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>
    <!--加入注解方式调味-->
    <tx:annotation-driven transaction-manager="transactionManager"/>

    <!--别忘了加点包的扫描-->
    <context:component-scan base-package="com.wanmait.template.dao"/>
</beans>``

DAO

package com.wanmait.template.dao;

import com.wanmait.template.pojo.Department;
import com.wanmait.template.pojo.Doctor;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

/*spring管理数据访问层*/
@Repository
public class DoctorDAO {

    /*注入灵魂*/
    @Resource
    private JdbcTemplate jdbcTemplate;
    /*注入大法师灵魂,参数比较多的话则注入此灵魂*/
    @Resource
    private NamedParameterJdbcTemplate namedParameterJdbcTemplate;

    /*查全部*/
    public List<Doctor> findAll()
    {
        String sql = "select * from doctor";
        return jdbcTemplate.query(sql,new BeanPropertyRowMapper<Doctor>(Doctor.class));
    }

    /*模糊查询*/
    public List<Doctor> findAll(String info)
    {
        String sql = "select * from doctor where visible=1 and info like ?";
        return jdbcTemplate.query(sql,new BeanPropertyRowMapper<Doctor>(Doctor.class),"%"+info+"%");
    }

    /*根据Id查询单条记录并返回此对象*/
    //BeanPropertyRowMapper 只要列名能和属性名一致,就能自动设置属性
    //如果根据给定的id查不到数据,会报异常EmptyResultDataAccessException
    public Doctor findById(Integer id)
    {
        Doctor doctor = null;
        String sql = "select * from doctor where visible=1 and id=?";
        try {
            doctor = jdbcTemplate.queryForObject(sql,new BeanPropertyRowMapper<Doctor>(Doctor.class),id);
        } catch (DataAccessException e) {

        }
        return doctor;
    }

    /*假删除*/
    public void deleteById(Integer id)
    {
        String sql = "update doctor set visible=0 where id=?";
        jdbcTemplate.update(sql,id);
    }

    /*根据Id更新单条数据*/
    public void updateById(Doctor doctor)
    {
        String sql = "update doctor set name=?,info=? where id=?";
        jdbcTemplate.update(sql,doctor.getName(),doctor.getInfo(),doctor.getId());
    }

    /*添加一条新数据*/
    public void insert(Doctor doctor)
    {
        String sql = "insert into doctor(name,scope) values(?,?)";
        jdbcTemplate.update(sql,doctor.getName(),doctor.getScope());
    }

    /*如果参数比较多,使用命名参数这种方式比较方便*/
    public void insert2(Doctor doctor)
    {
        //:title 命名参数 参数名一定要和javabean类的属性名一致
        String sql = "insert into doctor(name,info) values(:name,:info)";
        SqlParameterSource sqlParameterSource = new BeanPropertySqlParameterSource(doctor);
        namedParameterJdbcTemplate.update(sql,sqlParameterSource);
    }

    /*添加新数据后马上获取该条数据的主键Id*/
    public void testInsert3(Doctor doctor)
    {
        String sql = "insert into doctor(name,info) values(:name,:info)";
        SqlParameterSource sqlParameterSource = new BeanPropertySqlParameterSource(doctor);
        KeyHolder keyHolder = new GeneratedKeyHolder();
        namedParameterJdbcTemplate.update(sql,sqlParameterSource,keyHolder);
        doctor.setId(keyHolder.getKey().intValue());
    }

    /*获取总数*/
    public Integer getCount()
    {
        String sql = "select count(*) from doctor where visible=1";
        return jdbcTemplate.queryForObject(sql,Integer.class);
    }

    /*多表联合查询*/
    public List<Doctor> findAllMessage()
    {
        List<Doctor>doctors = null;
        StringBuilder stringBuilder = new StringBuilder("select doctor.name,doctor.info,doctor.department_id,department.title")
                .append(" from doctor")
                .append(" join department on department.id=doctor.department_id")
                .append(" where doctor.visible=1");
        doctors = jdbcTemplate.query(stringBuilder.toString(),new DoctorRowMapper());
        return doctors;
    }

    class DoctorRowMapper implements RowMapper<Doctor>
    {
        @Override
        public Doctor mapRow(ResultSet resultSet, int i) throws SQLException {
           Doctor doctor = new Doctor();
           doctor.setName(resultSet.getString("name"));
           doctor.setInfo(resultSet.getString("info"));
            Department department = new Department();
            department.setId(resultSet.getInt("department_id"));
            department.setTitle(resultSet.getString("title"));
            doctor.setDepartment(department);
            return doctor;
        }
    }
}

test测试一下

package com.wanmait.template.dao.test;

import com.wanmait.template.dao.DoctorDAO;
import com.wanmait.template.pojo.Doctor;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import javax.annotation.Resource;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class DoctorDAOTest {

    @Resource
    private DoctorDAO doctorDAO;

    /*查全部*/
    @Test
    public void testFindAll()
    {
        Assert.assertNotNull(doctorDAO.findAll());
    }

    /*模糊查询*/
    @Test
    public void testFindByInfo()
    {
        String info = "病";
        Assert.assertNotNull(doctorDAO.findAll(info));
    }

    /*根据Id查询单条记录并返回此对象*/
    @Test
    public void testFindById()
    {
        Integer id = 18;
        Assert.assertNotNull(doctorDAO.findById(id));
    }

    /*假删除*/
    @Test
    public void testDelete()
    {
        Integer id = 1;
        doctorDAO.deleteById(id);
    }

    /*根据Id更新单条数据*/
    @Test
    public void testUpdateById()
    {
        Doctor doctor = new Doctor();
        doctor.setId(2);
        doctor.setName("江老哥");
        doctor.setInfo("B阶段个人项目奋力中");
        doctorDAO.updateById(doctor);
    }

    /*添加一条新数据*/
    @Test
    public void testInsert()
    {
        Doctor doctor = new Doctor();
        doctor.setName("萧萧");
        doctor.setScope("你长阿德");
        doctorDAO.insert(doctor);
    }

    /*添加一条新数据,多个参数*/
    @Test
    public void testInsert2()
    {
        Doctor doctor = new Doctor();
        doctor.setName("刘老狗");
        doctor.setInfo("哈哈哈武清");
        doctorDAO.insert2(doctor);
    }

    /*添加新数据后马上获取该条数据的主键Id*/
    @Test
    public void testInsert3()
    {
        Doctor doctor = new Doctor();
        doctor.setName("刘老狗");
        doctor.setInfo("哈哈哈武清");
        doctorDAO.testInsert3(doctor);
        System.out.println(doctor.getId());
    }

    /*获取总数*/
    @Test
    public void testGetCount()
    {
        System.out.println(doctorDAO.getCount());
    }

    /*多表联合查询*/
    @Test
    public void testFindAllMessage()
    {
        System.out.println(doctorDAO.findAllMessage().get(0).getDepartment().getTitle());
    }

}

1. 用户与身体信息管理模块 用户信息管理: 注册登录:支持手机号 / 邮箱注册,密码加密存储,提供第三方快捷登录(模拟) 个人资料:记录基本信息(姓名、年龄、性别、身高、体重、职业) 健康目标:用户设置目标(如 “减重 5kg”“增肌”“维持健康”)及期望周期 身体状态跟踪: 体重记录:定期录入体重数据,生成体重变化曲线(折线图) 身体指标:记录 BMI(自动计算)、体脂率(可选)、基础代谢率(根据身高体重估算) 健康状况:用户可填写特殊情况(如糖尿病、过敏食物、素食偏好),系统据此调整推荐 2. 膳食记录与食物数据库模块 食物数据库: 基础信息:包含常见食物(如米饭、鸡蛋、牛肉)的名称、类别(主食 / 肉类 / 蔬菜等)、每份重量 营养成分:记录每 100g 食物的热量(kcal)、蛋白质、脂肪、碳水化合物、维生素、矿物质含量 数据库维护:管理员可添加新食物、更新营养数据,支持按名称 / 类别检索 膳食记录功能: 快速记录:用户选择食物、输入食用量(克 / 份),系统自动计算摄入的营养成分 餐次分类:按早餐 / 午餐 / 晚餐 / 加餐分类记录,支持上传餐食照片(可选) 批量操作:提供常见套餐模板(如 “三明治 + 牛奶”),一键添加到记录 历史记录:按日期查看过往膳食记录,支持编辑 / 删除错误记录 3. 营养分析模块 每日营养摄入分析: 核心指标计算:统计当日摄入的总热量、蛋白质 / 脂肪 / 碳水化合物占比(按每日推荐量对比) 微量营养素分析:检查维生素(如维生素 C、钙、铁)的摄入是否达标 平衡评估:生成 “营养平衡度” 评分(0-100 分),指出摄入过剩或不足的营养素 趋势分析: 周 / 月营养趋势:用折线图展示近 7 天 / 30 天的热量、三大营养素摄入变化 对比分析:将实际摄入与推荐量对比(如 “蛋白质摄入仅达到推荐量的 70%”) 目标达成率:针对健
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值