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());
        }
    }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM