Spring入门(三)

news/2024/5/18 23:27:12 标签: spring, jdbc

spring-的jdbc模板">Spring 的JDBC模板

(一)Spring 其实提供了很多的持久化技术的模板类简化编程。
包括:
– JDBC
– Hibernate3.0
– IBatis(MyBatis)
– JPA

今天主要讲一下JDBC模板

(二)实战

  1. 在mysql中创建student表

             包括id  name   age属性
    

    2.Maven依赖的引入

       所需maven依赖如下
    
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>groupId</groupId>
    <artifactId>hello</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.3.18.RELEASE</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.46</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.3.18.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-tx -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-tx</artifactId>
            <version>4.3.18.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/commons-dbcp/commons-dbcp -->
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.4</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/commons-pool/commons-pool -->
        <dependency>
            <groupId>commons-pool</groupId>
            <artifactId>commons-pool</artifactId>
            <version>1.6</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.mchange/c3p0 -->
        <dependency>
            <groupId>com.mchange</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.5.2</version>
        </dependency>

    </dependencies>
</project>

3.

Student.java文件

public class Student {
    private Integer age;
    private String name;
    private Integer id;
    ......
  }

StudentMapper.java

public class StudentMapper  implements RowMapper<Student> {
    public Student mapRow(ResultSet resultSet, int i) throws SQLException {
        Student st=new Student();
        st.setId(resultSet.getInt("Id"));
        st.setName(resultSet.getString("name"));
        st.setAge(resultSet.getInt("age"));
        return st;
    }
}

StudentService.java

public interface StudentService {
    public void setDataSource(DataSource ds);

    public void create(String name, Integer age);

    public Student getStudent(Integer id);

    public List<Student> listStudents();

    public void delete(Integer id);

    public void update(Integer id, Integer age);
}

StudentJDBCTemplate.java

public class StudentJDBCTemplate implements StudentService {
    private DataSource dataSource;
    private JdbcTemplate jdbcTemplateObject;

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
        this.jdbcTemplateObject = new JdbcTemplate(dataSource);
    }

    public void create(String name, Integer age) {
        String SQL = "insert into Student (name, age) values (?, ?)";

        jdbcTemplateObject.update( SQL, name, age);
        System.out.println("Created Record Name = " + name + " Age = " + age);
        return;
    }

    public Student getStudent(Integer id) {
        String SQL = "select * from Student where id = ?";
        Student student = jdbcTemplateObject.queryForObject(SQL,
                new Object[]{id}, new StudentMapper());
        return student;
    }

    public List<Student> listStudents() {
        String SQL = "select * from Student";
        List <Student> students = jdbcTemplateObject.query(SQL,
                new StudentMapper());
        return students;
    }

    public void delete(Integer id) {
        String SQL = "delete from Student where id = ?";
        jdbcTemplateObject.update(SQL, id);
        System.out.println("Deleted Record with ID = " + id );
        return;
    }

    public void update(Integer id, Integer age) {
        String SQL = "update Student set age = ? where id = ?";
        jdbcTemplateObject.update(SQL, age, id);
        System.out.println("Updated Record with ID = " + id );
        return;
    }
}

MainApp.java测试文件

public class MainApp {
    public static void main(String[] args) {
        ApplicationContext context =
                new ClassPathXmlApplicationContext("beans.xml");

        StudentJDBCTemplate studentJDBCTemplate =
                (StudentJDBCTemplate)context.getBean("studentJDBCTemplate");

        System.out.println("------Records Creation--------" );
        studentJDBCTemplate.create("Zara", 11);
        studentJDBCTemplate.create("Nuha", 2);
        studentJDBCTemplate.create("Ayan", 15);

        System.out.println("------Listing Multiple Records--------" );
        List<Student> students = studentJDBCTemplate.listStudents();
        for (Student record : students) {
            System.out.print("ID : " + record.getId() );
            System.out.print(", Name : " + record.getName() );
            System.out.println(", Age : " + record.getAge());
        }

        System.out.println("----Updating Record with ID = 2 -----" );
        studentJDBCTemplate.update(2, 20);

        System.out.println("----Listing Record with ID = 2 -----" );
        Student student = studentJDBCTemplate.getStudent(2);
        System.out.print("ID : " + student.getId() );
        System.out.print(", Name : " + student.getName() );
        System.out.println(", Age : " + student.getAge());

    }
}

4.配置文件的编写

    提供几种方式,具体如下:
<?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-4.3.xsd
">


    <context:component-scan base-package="com.txp.dao"/>

    <!--配置Spring的内接连接池-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql:///mybatis"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </bean>

    <!--配置DBCP连接池-->
    <bean id="dataSource1" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql:///mybatis"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </bean>

    <!--配置DBCP连接池-->
    <bean id="dataSource2" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"/>
        <property name="jdbcUrl" value="jdbc:mysql:///mybatis"/>
        <property name="user" value="root"/>
        <property name="password" value="root"/>
    </bean>
    <!--引入外部文件的方式:一-->
    <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:jdbc.properties"/>
    </bean>
    <!--引入外部文件的方式:二-->
    <context:property-placeholder location="classpath:jdbc.properties"/>
    <!--配置JDBC模板-->
    <bean id="studentJDBCTemplate" class="com.txp.dao.StudentJDBCTemplate">
        <property name="dataSource" ref="dataSource"/>
    </bean>
</beans> 

jdbc.properties文件内容

jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///mybatis
jdbc.username=root
jdbc.password=root

最后的结果
这里写图片描述


http://www.niftyadmin.cn/n/1394379.html

相关文章

Python的Web开发利器——Django安装使用经验谈

几天来&#xff0c;为了把这个可爱又可恨的尖钩用起来&#xff0c;真是煞费苦心。刚开始学习django就立马被它迷住了——这不就是我一直在找的东东吗&#xff1f;一下子看完了教程中的视图、模型、模板等各基础章节&#xff0c;哇&#xff0c;上帝&#xff0c;这么简单&#xf…

有关图像入理的问题

位图文件中应该保存的是每个像素的色彩等信息如果取得这些信息存入一个二维数组中。。。&#xff1f;&#xff1f;&#xff1f;请教些方面的高手&#xff01;最好有VB方面的&#xff01;

SQL Server 复制系列(文章索引)

一.本文所涉及的内容&#xff08;Contents&#xff09; 本文所涉及的内容&#xff08;Contents&#xff09;前言&#xff08;Introduction&#xff09;复制逻辑结构图&#xff08;Construction&#xff09;系列文章索引&#xff08;Catalog&#xff09;总结&待续...&#…

开始新生活!

今天搬到另一个房间住了。打扫的整整齐齐&#xff0c;心情也舒畅了很多&#xff01;而且这个房间有书架了&#xff0c;我的计算机和围棋藏书摆放整齐&#xff0c;十分舒服。希望今年在这个环境下能够潜心学习&#xff0c; 有所突破&#xff01;

Web应用程序开发方法研究

Web应用程序开发方法研究 摘要&#xff1a;如今已进入了web2.0高速发展的网络时代&#xff0c;各种基于互联网的Web应用程序如雨后春笋般出现。近几年&#xff0c;Web开发技术层出不穷&#xff0c;日趋成熟。本文介绍了Web技术的前世今生&#xff0c;对计算机科学前辈们孕育的软…

记得打补丁

之前遇到个很怪的问题&#xff1a; 买了个新硬盘&#xff0c;160G&#xff0c;重新装了VS.NET 2003,谁知道安装后&#xff08;安装过程完全顺利), 在新建WEB项目时&#xff0c;出现如下信息提示框&#xff0c;为什么呢&#xff1f; 无法在C&#xff1a;\DOCUMENTS AND SETTINGS…

Windows2012R2之虚拟机自动激活

Windows2012R2之虚拟机自动激活功能介绍&#xff1a;Windows2012R2系统推出虚拟机自动激活&#xff08;AVMA&#xff09;功能&#xff0c;此功能可以激活的Windows服务器上安装虚拟机&#xff0c;而无需为每个虚拟机管理产品密钥&#xff0c;即使在断开网络的环境。系统要求&am…

Mybatis相关知识点(一)

MyBatis入门 &#xff08;一&#xff09;介绍 MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code&#xff0c;并且改名为MyBatis 。2013年11月迁移到Github。 MyBatis是一个优秀的持久层框架&#xff0c;它对jdbc的…