(D) Spring ultra-comprehensive Quick Start -Spring JDBC Template

Foreword

Under the premise of the so-called JDBC Template that is, try to keep the code flexibility, reduce writing code, time before we learn JDBC, you need to connect the drive to create a statement, query, access lookup returns a value, set value, and so ... inconvenient.
Here Insert Picture Description
In fact, the two can achieve, certainly using less code way to die.

Additions and changes

In fact, however, is the JDBC CRUD, we look JDBC Template to help us simplify what operations:
you can add a sql statement, you can increase the number of sql statement:
increase or create, there are two methods, called execute, but it is generally it is used to create the table, but you want him to execute insert statement can be, but it is the underlying statement achieve, so do not set the placeholder, but really suitable for insertion statements should use the update method, which is the underlying PreparedStatement implementation, it is possible to achieve a placeholder is inserted, ideal for EE development, we briefly explain Usage:
the first step:
configure applicationContext.xml:


    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/selection_course?serverTimezone=GMT%2B8"/>
        <property name="username" value="root"/>
        <property name="password" value="12345678"/>
    </bean>

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

Very simple, so I put jdbcTemplate registered to bean them, and then we call it notes:
I would first obtain Bean object:

ApplicationContext applicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
JdbcTemplate jt = (JdbcTemplate)applicationContext.getBean("jdbcTemplate");

This object is obtained JdbcTemplate
if we want to have to use the execute method:

    public void testInsert() {
        jt.execute("insert into course values (1004,'高等数学',5)");
    }

There modify operation:

    public void testUpdate2() {
        String sql = "update course set score=? where id = ?";
        jt.update(sql,new Object[]{2,1005});
    }

This can be a way if you want to set placeholder:
JdbcTemplate.update (SQL String, Object [] obj)

    public void testUpdate() {
        String sql  = "insert into course values (?,?,?)";
        jt.update(sql,new Object[]{1005, "线性代数",3});
    }

The current way in front of such a development is better following this way, but their effect is the same:
public int Update (String SQL, Object ... args)
can add any item placeholders:

    public void testUpdate3() {
        String sql = "update course set score = ? where id = ?";
        jt.update(sql,3,1005);
    }

This is more convenient, if you want to execute multiple statements:
public int [] batchUpdate (Final String ... SQL)

    public void testBatchUpdate() {
        String[] sqls = {
                "insert into student values(1003, '星彩', '女', '1995-06-01')",
                "insert into student values(1004,'貂蝉','女','1996-05-04')",
                "update student set born = '1997-01-12' where id = 1002"
        };
        jt.batchUpdate(sqls);
    }

This is for the above plurality of different insert statements, and not disposed placeholder placeholder want to set up and perform a batch operation, can not perform multiple statements:
public int [] batchUpdate (SQL String, List <Object []> batchArgs)

    public void testBatchUpdate2() {
        String sql = "insert into selection(student, course) values(?,?)";
        List<Object[]> list = new LinkedList<>();
        list.add(new Object[]{1001,1003});
        list.add(new Object[]{1002,1001});
        jt.batchUpdate(sql,list);
    }

The first is to represent only bulk operations sql this one sql statement, while the latter represents the number of List array of sets of data to be updated

Delete search

To find out how to do?
public T queryForObject (String sql, Class
requiredType) look at the most simple query:

    public void testQuery() {
        String sql = "select count(*) from course";
        Integer i = jt.queryForObject(sql, Integer.class);
        System.out.println(i);
    }

The first parameter is the sql statement you want to query, and the second parameter is the result of a query after you return value is what type of
query results to a number of country?
public List queryForList (String sql, Class elementType)

    public void testQueryList() {
        String sql = "select name from course where score = 5";
        List<String> list = jt.queryForList(sql, String.class);
        System.out.println(list);
    }

To use queryForList method, save the results to a List list

How can you like a traditional jdbc as to save the query results to the entity classes it?
public T queryForObject (String sql, RowMapper rowMapper, @Nullable Object ... args)
The first argument is that you want to execute sql statement to query the
second parameter is an interface that has a method that mapRow, perform operations with its Like traditional JDBC, see the following example
the third parameter is a variable parameter, which is the sql statement placeholder

    public void testQueryEntity() {
        String sql = "select * from student where id = ?";
        Student o = jt.queryForObject(sql, new StudentRowMapper(), 1001);
        System.out.println(o);
    }
    private class StudentRowMapper implements RowMapper<Student> {

        @Override
        public Student mapRow(ResultSet rs, int rowNum) throws SQLException {
            Student student = new Student();
            student.setId(rs.getInt("id"));
            student.setName(rs.getString("name"));
            student.setSex(rs.getString("sex"));
            student.setBorn(rs.getString("born"));
            return student;
        }
    }

If you want to query multiple result? * From xxx such as the SELECT;
public List Query (SQL String, the RowMapper for rowMapper)

    public void testQueryEntity2() {
        String sql = "select * from student";
        List<Student> list = jt.query(sql,new StudentRowMapper());
        System.out.println(list);
    }

Simple operation than traditional bar jdbc

JDBC Example:

Like traditional development, we come to engage in an interface:

package com.bean.dao;

import com.bean.pojo.Course;

import java.util.List;

public interface CourseDao {
    void insert(Course course);
    void update(Course course);
    void delete(int id);
    Course search(int id);
    List<Course> selectAll();
}

Then an implementation class:

package com.bean.dao.impl;

import com.bean.dao.CourseDao;
import com.bean.pojo.Course;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Repository
public class CourseDaoImpl implements CourseDao {

    @Resource(name = "jdbcTemplate")
    private JdbcTemplate jdbcTemplate;

    @Override
    public void insert(Course course) {
        String sql = "insert into course(id,name,score) values (?,?,?)";
        jdbcTemplate.update(sql,course.getId(),course.getName(),course.getScore());
    }

    @Override
    public void update(Course course) {
        String sql = "update course set name = ?, score = ? where id = ?";
        jdbcTemplate.update(sql,course.getName(), course.getScore(),course.getId());
    }

    @Override
    public void delete(int id) {
        String sql = "delete from course where id = ?";
        jdbcTemplate.update(sql,id);
    }

    @Override
    public Course search(int id) {
        String sql = "select * from course where id = ?";
        Course course = jdbcTemplate.queryForObject(sql, new StudentRowMapper(), id);
        return course;
    }

    @Override
    public List<Course> selectAll() {
        String sql = "select * from course";
        List<Course> query = jdbcTemplate.query(sql, new StudentRowMapper());
        return query;
    }

    private class StudentRowMapper implements RowMapper<Course> {

        @Override
        public Course mapRow(ResultSet rs, int rowNum) throws SQLException {
            Course course = new Course();
            course.setId(rs.getInt("id"));
            course.setName(rs.getString("name"));
            course.setScore(rs.getInt("score"));
            return course;
        }
    }
}

Such Dao layer to engage over, how, is not it simple?

Published 54 original articles · won praise 82 · views 90000 +

Guess you like

Origin blog.csdn.net/u011679785/article/details/99405149