JdbcTemplate(增删改查以及以注释实现增删改查)

JdbcTemplate介绍

  为了使 JDBC 更加易于使用,Spring 在 JDBCAPI 上定义了一个抽象层,

  以此建立一个JDBC存取框架,Spring Boot Spring Data-JPA。

  作为 SpringJDBC 框架的核心, JDBC 模板的设计目的是为不同类型的JDBC操作提供模板方法.

  每个模板方法都能控制整个过程,并允许覆盖过程中的特定任务。

  通过这种方式,可以在尽可能保留灵活性的情况下,将数据库存取的工作量降到最低。

JdbcTemplate方法介绍

  execute方法:

    可以用于执行任何SQL语句,一般用于执行DDL语句;

  update方法:

    update方法用于执行新增、修改、删除等语句;

  query方法:

    用于执行查询相关语句;

  call方法:

    用于执行存储过程、函数相关语句。

注意:

  使用JdbcTemplate完成对数据库的操作十分易用,可以和Spring框架做到非常完美的整合

  JdbcTemplate仅仅只能支持简单的SQL操作,不支持关联映射和属性注入,所以在SQL方向的操作我们仍需使用MyBatis!

小例子(增删改查)

  查:

  步骤一:导入依赖

<!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>5.1.5.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.32</version>
    </dependency>

  步骤二:创建实体类

public class Student {
    private Integer stuid;
    private String stuname;
    private Integer age;

    public Integer getStuid() {
        return stuid;
    }

    public void setStuid(Integer stuid) {
        this.stuid = stuid;
    }

    public String getStuname() {
        return stuname;
    }

    public void setStuname(String stuname) {
        this.stuname = stuname;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

  步骤三:DAO层

public interface IStudentdao {
    //查询所有学生的方法
    public List<Student> allstu();
}

  步骤四:DAO层实现类

public class IStudentdaoimpl extends JdbcDaoSupport implements IStudentdao {

    //查询
    @Override
    public List<Student> allstu() {
        //获取JDBC模板
        JdbcTemplate jdbcTemplate=getJdbcTemplate();
        String sql="select * from student";
       //执行查询操作
        List<Student> query = jdbcTemplate.query(sql, new RowMapper<Student>() {
            *//**
             *
             * @param rs        结果集
             * @param rowNum    当前行
             * @return          方法返回值
             * @throws SQLException
             *//*
            @Override
            public Student mapRow(ResultSet rs, int rowNum) throws SQLException {
                Student stu = new Student();
                stu.setStuid(rs.getInt("stuid"));
                stu.setStuname(rs.getString("stuname"));
                stu.setAge(rs.getInt("age"));
                return stu;
            }
      /*      //自动映射(可省略上方的query方法)
      RowMapper<Student> rowMapper= new BeanPropertyRowMapper<>(Student.class);      List<Student> query = jdbcTemplate.query(sql, rowMapper);      */
    });
        return query;
    }
}

  步骤五:Service层

public interface IStudentservice {
    //查询所有学生的方法
    public List<Student> allstu();
}

  步骤六:Service实现层

public class IStudentserviceimpl implements IStudentservice {

    private IStudentdao iStudentdao;

    public IStudentdao getiStudentdao() {
        return iStudentdao;
    }

    public void setiStudentdao(IStudentdao iStudentdao) {
        this.iStudentdao = iStudentdao;
    }

    @Override
    public List<Student> allstu() {
        return iStudentdao.allstu();
    }

}

  步骤七:大配置文件(jdbc四个配置)

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/student?useUniCode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull
jdbc.username=root
jdbc.password=123
<?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"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

        <!--加载配置文件-->
        <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>

        <!--DateSource模板
        DriverManagerDataSource:Spring默认的数据源
        数据源还有:c3p0   dbcp
        -->
        <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
            <property name="driverClassName" value="${jdbc.driver}"></property>
            <property name="url" value="${jdbc.url}"></property>
            <property name="username" value="${jdbc.username}"></property>
            <property name="password" value="${jdbc.password}"></property>
        </bean>

        <!--植入JdbcTemplate-->
        <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
            <property name="dataSource" ref="dataSource"></property>
        </bean>

        <!--植入DAO层-->
        <bean id="iStudentdao" class="com.JdbcTemplate.dao.impl.IStudentdaoimpl">
            <property name="jdbcTemplate" ref="jdbcTemplate"></property>

      <!--        如果采用下面这条命令,可省略上面的植入JdbcTemplate的代码      -->
           <!-- <property name="dataSource" ref="dataSource"></property>-->
        </bean>

        <!--植入Service-->
        <bean id="iStudentservice" class="com.JdbcTemplate.service.impl.IStudentserviceimpl">
            <property name="iStudentdao" ref="iStudentdao"></property>
        </bean>
</beans>

  步骤八:测试

@Test
    public void Demo01(){
ApplicationContext atc=new ClassPathXmlApplicationContext("applicationContext.xml");
        IStudentservice stu = (IStudentservice)atc.getBean("iStudentservice");
        //查询stu
        List<Student> allstu = stu.allstu();
        for (Student atu:allstu){
            System.out.println("名称:"+atu.getStuname()+"\t年龄:"+atu.getAge());
        }
    }

  增(在这里,我们可以把读取大配置文件大代码提到外面)

  

public class stutest {
    ApplicationContext atc=new ClassPathXmlApplicationContext("applicationContext.xml");

}

  步骤一:DAO层

public interface IStudentdao {
    //添加学生
    public int addstu(Student stu);
}

  步骤二:

//添加学生
    @Override
    public int addstu(Student stu) {
        //获取JDBC模板
        JdbcTemplate jdbcTemplate=getJdbcTemplate();
        String sql="insert into student values(default,?,?)";
        Object [] obj={stu.getStuname(),stu.getAge()};
        int update = jdbcTemplate.update(sql, obj);
        System.out.println("返回值类型:"+update);
        return update;
    }

  步骤三:Service层

public interface IStudentservice{
    //添加学生
    public int addstu(Student stu);
}

  步骤四:Serviceimpl层

public class IStudentserviceimpl implements IStudentservice {

    private IStudentdao iStudentdao;

    public IStudentdao getiStudentdao() {
        return iStudentdao;
    }

    public void setiStudentdao(IStudentdao iStudentdao) {
        this.iStudentdao = iStudentdao;
    }

    @Override
    public int addstu(Student stu) {
        return iStudentdao.addstu(stu);
    }

}

  步骤五:测试

@Test
    public void insert(){
        IStudentservice stu = (IStudentservice)atc.getBean("iStudentservice");
        //添加
        Student ss=new Student();
        ss.setStuname("阿斯顿");
        ss.setAge(123);
        int addstu = stu.addstu(ss);

 }

  改

  步骤一:DAO层

public interface IStudentdao {
    //修改学生
    public int updatestu(Student stu);
}

  步骤二:DAOimpl层

public class IStudentdaoimpl extends JdbcDaoSupport implements IStudentdao {

    //修改学生
    @Override
    public int updatestu(Student stu) {
        //获取JDBC模板
        JdbcTemplate jdbcTemplate=getJdbcTemplate();
        Object [] obj={stu.getStuname(),stu.getAge(),stu.getStuid()};
        String sql="update student set stuname=?,age=? where stuid=?";
        int update = jdbcTemplate.update(sql, obj);
        System.out.println("返回值类型:"+update);
        return update;
    }

}

  步骤三:Service层

public interface IStudentservice {
    //修改学生
    public int updatestu(Student stu);
}

  步骤四:Serviceimpl

public class IStudentserviceimpl implements IStudentservice {

    private IStudentdao iStudentdao;

    public IStudentdao getiStudentdao() {
        return iStudentdao;
    }

    public void setiStudentdao(IStudentdao iStudentdao) {
        this.iStudentdao = iStudentdao;
    }

    @Override
    public int updatestu(Student stu) {
        return iStudentdao.updatestu(stu);
    }

}

  步骤五:测试

@Test
    public void update(){
        IStudentservice stu = (IStudentservice)atc.getBean("iStudentservice");
        //修改
        Student sss=new Student();
        sss.setStuname("冯老板");
        sss.setAge(99);
        sss.setStuid(6);
int updatestu = stu.updatestu(sss);
    }

  删:

  步骤一:DAO层

public interface IStudentdao {

    //删除学生
    public int delstu(Student stu);
}

  步骤二:DAOimpl层

public class IStudentdaoimpl extends JdbcDaoSupport implements IStudentdao {

    //删除
    @Override
    public int delstu(Student stu) {
        //获取JDBC模板
        JdbcTemplate jdbcTemplate=getJdbcTemplate();
        Object [] obj={stu.getStuid()};
        String sql="delete from Student where stuid=?";
        int update = jdbcTemplate.update(sql, obj);
        System.out.println("返回值类型:"+update);
        return update;
    }

}

  步骤三:Service层

public interface IStudentservice {
    //删除学生
    public int delstu(Student stu);
}

  步骤四:Serviceimpl层

public class IStudentserviceimpl implements IStudentservice {

    private IStudentdao iStudentdao;

    public IStudentdao getiStudentdao() {
        return iStudentdao;
    }

    public void setiStudentdao(IStudentdao iStudentdao) {
        this.iStudentdao = iStudentdao;
    }

    @Override
    public int delstu(Student stu) {
        return iStudentdao.delstu(stu);
    }
}

  步骤五:测试

@Test
    public void del(){
        IStudentservice stu = (IStudentservice)atc.getBean("iStudentservice");
        //删除
        Student sss=new Student();
        sss.setStuid(6);
        int delstu = stu.delstu(sss);
    }

使用注释实现增删改(在这里只列举查询)

  步骤一:大配置文件

<?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"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
        <!--扫描注解-->
        <context:component-scan base-package="com.JdbcTemplate"/>

        <!--记载配置文件-->
        <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>

        <!--DateSource模板
        DriverManagerDataSource:Spring默认的数据源
        数据源还有:c3p0   dbcp
        -->
        <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
            <property name="driverClassName" value="${jdbc.driver}"></property>
            <property name="url" value="${jdbc.url}"></property>
            <property name="username" value="${jdbc.username}"></property>
            <property name="password" value="${jdbc.password}"></property>
        </bean>

        <!--植入JdbcTemplate-->
        <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
            <property name="dataSource" ref="dataSource"></property>
        </bean>

<!--
        &lt;!&ndash;植入DAO层&ndash;&gt;
        <bean id="iStudentdao" class="com.JdbcTemplate.dao.impl.IStudentdaoimpl">
            &lt;!&ndash;<property name="jdbcTemplate" ref="jdbcTemplate"></property>&ndash;&gt;
            <property name="dataSource" ref="dataSource"></property>
        </bean>

        &lt;!&ndash;植入Service&ndash;&gt;
        <bean id="iStudentservice" class="com.JdbcTemplate.service.impl.IStudentserviceimpl">
            <property name="iStudentdao" ref="iStudentdao"></property>
        </bean>

    -->
</beans>

  步骤二:DAOimpl层

@Repository
public class IStudentdaoimpl implements IStudentdao {

    @Resource
    private JdbcTemplate jdbcTemplate;

    //查询
    @Override
    public List<Student> allstu() {
        //获取JDBC模板
        /*JdbcTemplate jdbcTemplate=getJdbcTemplate();*/
        String sql="select * from student";
        //查询
        /*List<Student> query = jdbcTemplate.query(sql, new RowMapper<Student>() {
            *//**
             *
             * @param rs     返回的结果集
             * @param i             记录行
             * @return 方法返回值
             * @throws SQLException
             *//*
            @Override
            public Student mapRow(ResultSet rs, int i) throws SQLException {
                Student stu = new Student();
                stu.setStuid(rs.getInt("stuid"));
                stu.setStuname(rs.getString("stuname"));
                stu.setAge(rs.getInt("age"));
                return stu;
            }
        });*/

        //自动映射
        RowMapper<Student> rowMapper= new BeanPropertyRowMapper<>(Student.class);
        List<Student> query = jdbcTemplate.query(sql, rowMapper);

        return query;
    }

}

  步骤三:Serviceimpl层

@Service("iStudentservice")
public class IStudentserviceimpl implements IStudentservice {

    @Resource
    private IStudentdao iStudentdao;

    public IStudentdao getiStudentdao() {
        return iStudentdao;
    }

    public void setiStudentdao(IStudentdao iStudentdao) {
        this.iStudentdao = iStudentdao;
    }

    @Override
    public List<Student> allstu() {
        return iStudentdao.allstu();
    }
}

  步骤四:测试

@Test
    public void Demo01(){
ApplicationContext atc=new ClassPathXmlApplicationContext("applicationContext.xml");
        IStudentservice stu = (IStudentservice)atc.getBean("iStudentservice");
        //查询stu
        List<Student> allstu = stu.allstu();
        for (Student atu:allstu){
            System.out.println("名称:"+atu.getStuname()+"\t年龄:"+atu.getAge());
        }
    }

原文地址:https://www.cnblogs.com/whtt/p/11782457.html

时间: 2024-10-06 11:59:56

JdbcTemplate(增删改查以及以注释实现增删改查)的相关文章

基于Form组件实现的增删改和基于ModelForm实现的增删改

基于Form组件实现的增删改和基于ModelForm实现的增删改 一.ModelForm的介绍 ModelForm a. class Meta: model, # 对应Model的 fields=None, # 字段 exclude=None, # 排除字段 labels=None, # 提示信息 help_texts=None, # 帮助提示信息 widgets=None, # 自定义插件 error_messages=None, # 自定义错误信息(整体错误信息from django.cor

关于最短增广路算法和连续最短增广路算法的操作步骤

最短增广路算法(SAP): 1.初始化容量网络和网络流: 2.构造残留网络和层次网络,如果汇点不在层次网络中,则算法结束: 3.在层次网络中不断用BFS增广,直到层次网络中没有增广路为止:每次增广完毕,在层次网络中要去掉因改进流量而导致饱和的弧: 4.转到步骤(2). 连续最短增广路算法(Dinic): 1.初始化容量网络和网络流: 2.构造残留网络和层次网络,如果汇点不在层次网络中,则算法结束: 3.在层次网络中用一次DFS过程进行增广,DFS执行完毕,该阶段的增广也执行完毕: 4.转到步骤(

Ado.Net学习之【DataSet】和【SqlDataAdapter】结合实现数据的【增】【删】【改】【查】

准备:再数据库中建立一张表:表名:PicInfos 表结构: 表数据: 关于数据库的链接就不多说了.直接进入今天的主题:利用DataSet和SqlDataAdapter对数据库中的数据进行操作: 一.查看数据: public void DoSqlData() { using (SqlConnection sqlconn = new SqlConnection(sqlStr)) { string str = "select * from PicInfos"; //sql查询语句 SqlD

【BZOJ-3673&amp;3674】可持久化并查集 可持久化线段树 + 并查集

3673: 可持久化并查集 by zky Time Limit: 5 Sec  Memory Limit: 128 MBSubmit: 1878  Solved: 846[Submit][Status][Discuss] Description n个集合 m个操作操作:1 a b 合并a,b所在集合2 k 回到第k次操作之后的状态(查询算作操作)3 a b 询问a,b是否属于同一集合,是则输出1否则输出0 0<n,m<=2*10^4 Input Output Sample Input 5 6

Restructuring Company和Almost Union-Find 并查集的区间合并与并查集的删除

Restructuring Company Even the most successful company can go through a crisis period when you have to make a hard decision - to restructure, discard and merge departments, fire employees and do other unpleasant stuff. Let's consider the following mo

并查集——poj2236(带权并查集)

题目:Wireless Network 题意:给定n台已损坏计算机的位置和计算机最远通信距离d,然后分别根据命令执行以下两种操作: "O p" (1 <= p <= N) :表示修理计算机p: "S p q" (1 <= p, q <= N) :表示检测计算机p和计算机q能否通信. 输出:能通信则输出"SUCCESS",否则输出"FAIL" 题解: 带权并查集还是那个重要的知识点--关系. 此题,我们使

[BZOJ3674]可持久化并查集加强版&amp;[BZOJ3673]可持久化并查集 by zky

思路: 用主席树维护并查集森林,每次连接时新增结点. 似乎并不需要启发式合并,我随随便便写了一个就跑到了3674第一页?3673是这题的弱化版,本来写个暴力就能过,现在借用加强版的代码(去掉异或),直接吊打暴力程序. 1 #include<cstdio> 2 #include<cctype> 3 inline int getint() { 4 register char ch; 5 while(!isdigit(ch=getchar())); 6 register int x=ch

BZOJ 3673 可持久化并查集 by zky 可持久化并查集

题目大意:给定n个集合,提供三种操作: 1.合并a,b所在集合 2.回到第k次操作之后的状态 3.询问a,b是否在同一集合 可持久化并查集0.0 实现方式是用可持久化线段树实现可持久化数组维护可持久化并查集... 至于可持久化数组,每条路径上只有叶节点的位置的num域是有意义的,感觉无比浪费0.0 可是不这样还真没法维护0.0 合并时本来应该按照每个节点的深度之和维护,结果手残懒得写,只用siz维护了0.0 至于路径压缩,写了比不写慢0.0 还是不写了吧 #include<cstdio> #i

hdu 3081 【二分匹配+并查集+删边||最大路+并查集+二分枚举】

Marriage Match II Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others) Total Submission(s): 2307    Accepted Submission(s): 792 Problem Description Presumably, you all have known the question of stable marriage match. A