Spring Road (31) - use NamedParameterJdbcTemplate to complete database operation (JavaConfig configuration)

background

In the previous article, we completed the instance of database add, delete, modify and query under the JdbcTemplate, in which the configuration of related bean s is realized through xml and annotation.

JdbcTemplate transfers parameters according to the placeholder location. In this article, we show the use of NamedParameterJdbcTemplate. This class uses the name to transfer parameters, which is more elegant than JdbcTemplate. Then in this article, we use JavaConfig to configure related bean s. We can experience the simplicity and power of JavaConfig.

Configure the data source and namedParameterJdbcTemplate in the configuration class

In BeanConfig, we configure the data source and namedParameterJdbcTemplate components through JavaConfig. The code is as follows:

package org.maoge.nameddemo;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import com.alibaba.druid.pool.DruidDataSource;
@Configuration // Configuration class
public class BeanConfig {
	// Configure data sources
	@Bean
	public DataSource dataSource() {
		DruidDataSource dataSource = new DruidDataSource();
		dataSource.setDriverClassName("com.mysql.jdbc.Driver");
		dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/myblog?useUnicode=true&characterEncoding=utf-8");
		dataSource.setUsername("root");
		dataSource.setPassword("XXX");
		return dataSource;
	}
	// Configure the namedParameterJdbcTemplate component
	@Bean
	public NamedParameterJdbcTemplate namedParameterJdbcTemplate() {
		NamedParameterJdbcTemplate template=new NamedParameterJdbcTemplate(dataSource());//Inject dataSource
		return template;
	}
}

Implement the database operation component BlogDao

The data object does not need to be changed:

package org.maoge.nameddemo;
/**
 * @theme Data object blog
 * @author maoge
 * @date 2020-01-27
 */
public class BlogDo {
	private Long id;
	private String title;
	private String author;
	private String content;
	// Omit get
}

Compared with the JdbcTemplate, the data operation component has some changes, mainly from parameter passing by location to parameter passing by name. The details are as follows. It can be seen that there is no change except for parameter passing. Also note that we do not use annotations in this class, because we will configure it as a bean directly through JavaConfig in the future.

package org.maoge.nameddemo;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.jdbc.core.RowMapper;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;

/**
 * @theme DAO--Blog
 * @author maoge
 * @date 2020-01-29
 */
public class BlogDao {
	public NamedParameterJdbcTemplate getNamedTemplate() {
		return namedTemplate;
	}

	public void setNamedTemplate(NamedParameterJdbcTemplate namedTemplate) {
		this.namedTemplate = namedTemplate;
	}

	private NamedParameterJdbcTemplate namedTemplate;


	/**
	 * Newly added
	 */
	public void insert(BlogDo blog) {
		Map<String, Object> map = new HashMap<>();
		map.put("author", blog.getAuthor());
		map.put("content", blog.getContent());
		map.put("title", blog.getTitle());
		// Attention to use: xxx space
		namedTemplate.update("insert into blog(author,content,title)values(:author,:content,:title)", map);
	}

	/**
	 * delete
	 */
	public void delete(Long id) {
		Map<String, Object> map = new HashMap<>();
		map.put("id", id);
		namedTemplate.update("delete from blog where id =:id", map);
	}

	/**
	 * To update
	 */
	public void update(BlogDo blog) {
		Map<String, Object> map = new HashMap<>();
		map.put("author", blog.getAuthor());
		map.put("content", blog.getContent());
		map.put("title", blog.getTitle());
		map.put("id", blog.getId());
		namedTemplate.update("update blog set author=:author,content=:content,title=:title where id=:id", map);
	}

	/**
	 * Press id to query
	 */
	public BlogDo getById(Long id) {
		Map<String, Object> map = new HashMap<>();
		map.put("id", id);
		return namedTemplate.queryForObject("select * from blog where id=:id", map, new RowMapper<BlogDo>() {
			@Override
			public BlogDo mapRow(ResultSet rs, int rowNum) throws SQLException {
				BlogDo blog = new BlogDo();
				blog.setAuthor(rs.getString("author"));
				blog.setContent(rs.getString("content"));
				blog.setId(rs.getLong("id"));
				blog.setTitle(rs.getString("title"));
				return blog;
			}
		});
	}

	/**
	 * Query list
	 */
	public List<BlogDo> getList() {
		return namedTemplate.query("select * from blog", new RowMapper<BlogDo>() {
			@Override
			public BlogDo mapRow(ResultSet rs, int rowNum) throws SQLException {
				BlogDo blog = new BlogDo();
				blog.setAuthor(rs.getString("author"));
				blog.setContent(rs.getString("content"));
				blog.setId(rs.getLong("id"));
				blog.setTitle(rs.getString("title"));
				return blog;
			}
		});
	}

}

Register BlogDao as a bean

Here, use JavaConfig to register BlogDao as a bean and inject namedParameterJdbcTemplate. The modified code is as follows:

package org.maoge.nameddemo;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import com.alibaba.druid.pool.DruidDataSource;
@Configuration // Configuration class
public class BeanConfig {
	// Configure data sources
	@Bean
	public DataSource dataSource() {
		DruidDataSource dataSource = new DruidDataSource();
		dataSource.setDriverClassName("com.mysql.jdbc.Driver");
		dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/myblog?useUnicode=true&characterEncoding=utf-8");
		dataSource.setUsername("root");
		dataSource.setPassword("Easy@0122");
		return dataSource;
	}
	// Configure the namedParameterJdbcTemplate component
	@Bean
	public NamedParameterJdbcTemplate namedParameterJdbcTemplate() {
		NamedParameterJdbcTemplate template=new NamedParameterJdbcTemplate(dataSource());//Inject dataSource
		return template;
	}
	//Register bean s for BlogDao
	@Bean
	public BlogDao blogDao() {
		BlogDao blogDao=new BlogDao();
		blogDao.setNamedTemplate(namedParameterJdbcTemplate());//Inject namedParameterJdbcTemplate
		return blogDao;
	}
}

test

Except for the different classes for building containers, the rest are the same:

package org.maoge.nameddemo;
import java.sql.SQLException;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Main {
	public static void main(String[] args) throws SQLException {
		// Get container
		AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(BeanConfig.class);
		// Get blogDao component
		BlogDao blogDao = context.getBean("blogDao", BlogDao.class);
		BlogDo blog = new BlogDo();
		blog.setAuthor("Cat elder brother");
		blog.setTitle("Test blog");
		blog.setContent("It's perfect");
		// Test insertion
		blogDao.insert(blog);
		// Get 1 test
		System.out.println(blogDao.getById(2L));
		// Test get list
		System.out.println(blogDao.getList().size());
		blog.setId(3L);
		blog.setContent("It's perfect XX");
		// modify
		blogDao.update(blog);
		// delete
		blogDao.delete(4L);
	}
}

summary

NamedParameterJdbcTemplate is a better way to operate the database than JdbcTemplate.

JavaConfig should be a better way to configure bean s than xml and annotations

345 original articles published, 240 praised, 530000 visitors+
His message board follow

Tags: JDBC Java SQL MySQL

Posted on Wed, 29 Jan 2020 01:07:13 -0800 by jh21236