JDBC Spring framework

Creative Commons License Copyright: Attribution, allow others to create paper-based, and must distribute paper (based on the original license agreement with the same license Creative Commons )

Outline

In the Spring JDBC module, all classes may be assigned to four separate packages:

  1. core
    or core package, which contains the JDBC core functions. There are many important class in this package, including: JdbcTemplate class, SimpleJdbcInsert class, SimpleJdbcCall class, and NamedParameterJdbcTemplate class.

  2. datasource
    i.e. utility class packet data source, accessing data sources. It has implemented a variety of data sources, can be tested outside the container JavaEE JDBC code.

  3. object
    that is the object package, object-oriented access to the database. It allows to execute the query and returns the results as business objects. Results It can be mapped properties between the column and the business object data table.

  4. support
    is to support the package, the package is the core package and the support object class. Providing SQLException anomalies in e.g. conversion function.

Add dependent

To use depend on spring and Spring JDBC dependence

<!-- spring IOC最小依赖,maven可以自动将其他依赖添加进来 -->
<dependency>
	<groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>5.1.5.RELEASE</version>
</dependency>
<!-- spring JDBC的依赖库 -->
<dependency>
    <groupId>org.springframework</groupId>
	<artifactId>spring-jdbc</artifactId>
    <version>5.1.5.RELEASE</version>
</dependency>

Configuration data source

First of all have about the property database connection configuration file

jdbc.url=jdbc:mysql://localhost:3306/books
jdbc.driver=com.mysql.jdbc.Driver
jdbc.user=root
jdbc.password=root
jdbc.characterEncoding=utf8

Entity class

@Setter
@Getter// 生成getter、setter的注解(需要Lombok插件)
public class BookType {
    private Integer id;// 图书类型id
    private String tname;// 图书类型
}

XML configuration

<!-- 配置数据源 -->
    <context:property-placeholder location="classpath:jdbc.properties"/>
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.user}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="connectionProperties">
            <props>
                <prop key="charsetEncoding">${jdbc.characterEncoding}</prop>
            </props>
        </property>
    </bean>

Annotation Configuration

/**
* @program: spring
*
* @description: 用注解的方式配置数据源
*
* @author: 吴蒙召
*
* @create: 2019-06-20 15:11
*
* @version: 1.0
**/

@PropertySource("classpath:jdbc.properties")
@Component
public class MyDataSource extends DriverManagerDataSource {

    public MyDataSource(@Value("${jdbc.driver}") String driver, @Value("${jdbc.url}") String url, @Value("${jdbc.user}")
            String username, @Value("${jdbc.password}") String password, @Value("${jdbc.characterEncoding}") String characterEncoding){
        super.setDriverClassName(driver);
        super.setUrl(url);
        super.setUsername(username);
        super.setPassword(password);
        Properties properties = new Properties();
        properties.setProperty("characterEncoding",characterEncoding);
        super.setConnectionProperties(properties);
    }
}

JdbcTemplate

JdbcTemplate is actually a database of operational tools, which provides a series of method of operation of the database, such as the commonly used CRUD and so on. Its use tools and libraries apache Dbutils provided similar, but the class name is different. Examples are given below

JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
// 查询方法
jdbcTemplate.query("select * from booktype",new BeanPropertyRowMapper<BookType>(BookType.class));
// 增加、删除、修改方法()
jdbcTemplate.update("insert into booktype (tname) values (?)",bookType.getTname());
/**
*此处只给出了增加的方法,删除、修改只需要换了SQL语句即可
*jdbcTemplate只是封装了PrepareStatement的方法,用的还是占位符配合参数的方式
**/

JdbcTemplate methods provided:

  • execute method: it can be used to execute any SQL statement, typically used to execute DDL statements;
  • update method and batchUpdate method: update methods for performing add, modify and delete statements; batchUpdate methods for performing batch related statements;
  • query methods and queryForXXX method: to perform a query related statements;
  • Method call: for executing stored procedures, functions related statements.

JdbcTemplate query methods

Query a single data

Generally used queryForObject (String sql, Object [] args, Class <T> requiredType) Method

String sql = "select tname from booktype where id = ?";
String tName = JdbcTemplate().queryForObject(sql, new Object[] { bookType.getId() }, String.class);

Query multiple rows of data

Use the query method, but to pass a BeanPropertyRowMapper object parameter. Automatic mapping of the way such a thing, but requires the field names correspond to your entity class and property names you build a table (you need not correspond to the column names from your query result attribute alias name of your entity class )

// 如果双方名字不对应,则String sql = "select tname as tName from booktype"
List<BookType> bookTypeList = jdbcTemplate.query("select * from booktype",new BeanPropertyRowMapper<BookType>(BookType.class));
// query方法中的第三个参数如果SQL语句没有条件判断就不需要了

NamedParameterJdbcTemplate

In classical JDBC usage, the SQL parameters placeholder is ?expressed, and the position is restricted. Location parameters problem is that once the order of the parameters is changed, it is necessary to change the parameter bindings.
Spring JDBC the frame, an alternative is to use the SQL parameters to bind named parameters (named parameter).

What is the named parameters

Named parameters: SQL by name (preceded by a colon) instead of the location specified by the named parameters easier to maintain, but also enhance the readability of named parameters with placeholders substituted by the frame classes at runtime.
Named parameters are only NamedParameterJdbcTemplate supported. NamedParameterJdbcTemplate can use all jdbcTemplate method.

Named parameters using the example

The availability of additional primary key:
NamedParameterJdbcTemplate also added KeyHolder class, which we can obtain the primary key, similar Mybatis in useGeneratedKeys.

@Test
public void testNamedParameter(){
    NamedParameterJdbcTemplate npjt = new NamedParameterJdbcTemplate(dataSource);
    String sql = "insert into booktype (id,tname) values (:id,:tname)";
    BookType bt = new BookType();
    bt.setId(66);
    bt.setTname("test");
    SqlParameterSource sqlParameterSource=new BeanPropertySqlParameterSource(bt);
    npjt.update(sql,sqlParameterSource);
    //KeyHolder keyHolder = new GeneratedKeyHolder();
    //npjt.update(sql, sqlParameterSource, keyHolder);
    // 插入成功后,返回该条信息的主键id
    //int resultId = keyHolder.getKey().intValue();
    //System.out.println(resultId);
}

Spring Jdbc also provides many types, such as calls SimpleJdbcCall such as stored procedures or stored functions, not repeat them here. Spring JDBC provides classes there is still only a single check for table use, query on the table relates to the combination still need Hibernate, Mybatis and other database framework to deal with the more perfect.

Guess you like

Origin blog.csdn.net/qq_38647878/article/details/93334369