Spring之路(30)–使用JdbcTemplate完成数据库操作(xml+注解配置)

背景

上一篇讲述了数据源DataSource,本篇使用的JdbcTemplate完成对数据库增删改查操作,话不多少,开整…

创建spring.xml

创建spring.xml,这个没啥好说的,注意开启对包的扫描,以便于后续自动注册包内定义的bean:

<?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"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
         http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
         http://www.springframework.org/schema/context 
         http://www.springframework.org/schema/context/spring-context-4.0.xsd
         http://www.springframework.org/schema/mvc
         http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
	<context:component-scan
		base-package="org.maoge.jdbctemplatedemo" />
</beans>

配置数据源

在xml配置数据源,上一篇我们使用JavaConfig配置了数据源,使用xml就是形式不一样,直接翻译过来就行。

    <!-- 数据源 -->
	<bean id="dataSource"
		class="com.alibaba.druid.pool.DruidDataSource">
		<property name="driverClassName"
			value="com.mysql.jdbc.Driver"></property>
		<!-- 注意xml中使用&amp;替代& -->
		<property name="url"
			value="jdbc:mysql://127.0.0.1:3306/myblog?useUnicode=true&amp;characterEncoding=utf-8"></property>
		<property name="username" value="root"></property>
		<property name="password" value="XXX"></property>
	</bean>

配置jdbcTemplate组件,并注入dataSource

同样使用xml配置jdbcTemplate,显示指定注入dataSource。

	<!--注册jdbcTemplate组件 -->
	<bean id="jdbcTemplate"
		class="org.springframework.jdbc.core.JdbcTemplate">
		<property name="dataSource" ref="dataSource"></property>
	</bean>

定义数据对象

此处我们还是对博客blog表进行操作,所以定义BlogDo数据对象。

package org.maoge.jdbctemplatedemo;
/**
 * @theme 数据对象--博客
 * @author maoge
 * @date 2020-01-27
 */
public class BlogDo {
	private Long id;
	private String title;
	private String author;
	private String content;
	// 省略get get
}

实现数据库操作组件

此处常规操作是先定义一个接口,然后将实现接口的类注册为bean,我个人是感觉没啥意义,咱们直接实现数据库操作组件。

一般对数据库进行操作对象称为DAO,此处我们也按这个命名来实现:

package org.maoge.jdbctemplatedemo;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;

/**
 * @theme DAO--博客
 * @author maoge
 * @date 2020-01-29
 */
@Repository // 注册为组件(此处也可以使用@Component)
public class BlogDao {
	@Autowired // 自动注入xml中定义的jdbcTemplate
	private JdbcTemplate jdbcTemplate;

	/**
	 * 新增
	 */
	public void insert(BlogDo blog) {
		jdbcTemplate.update("insert into blog(author,content,title)values(?,?,?)", blog.getAuthor(), blog.getContent(),
				blog.getTitle());
	}

	/**
	 * 删除
	 */
	public void delete(Long id) {
		jdbcTemplate.update("delete from blog where id =?", id);
	}

	/**
	 * 更新
	 */
	public void update(BlogDo blog) {
		jdbcTemplate.update("update blog set author=?,content=?,title=? where id=?", blog.getAuthor(),
				blog.getContent(), blog.getTitle(), blog.getId());
	}

	/**
	 * 按id查询
	 */
	public BlogDo getById(Long id) {
		return jdbcTemplate.queryForObject("select * from blog where id=?", 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;
			}

		}, id);
	}

	/**
	 * 查询列表
	 */
	public List<BlogDo> getList() {
		return jdbcTemplate.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;
			}
		});
	}
}

可以看到,除了最后两个查询方法稍微有点不好理解,其他的都简单了。最后两个用到了匿名类相关知识,可以去了解下,当然就算不了解直接写类似的代码也是可以的,已经足够简单了。

bean分析

注意本文其实我们使用xml定义了dataSource、jdbcTemplate两个bean,而BlogDao是使用注解定义的。为何不都使用注解或都使用注解呢?

因为dataSource和jdbcTemplate是Spring定义好的类,我们没法在上面添加注解了。所以可以使用xml注册它或者使用JavaConfig。

而BlogDao我们既可以使用注解,也可以使用xml注册它,由于直接代码量更少,所以此处为了简单就使用了注解。

测试

我们获取容器中的BlogDao组件,然后调用其方法进行测试即可,测试代码如下:

package org.maoge.jdbctemplatedemo;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Main {
	public static void main(String[] args) {
		// 获取容器
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
				"/org/maoge/jdbctemplatedemo/spring.xml");
		// 获取blogDao组件
		BlogDao blogDao = context.getBean("blogDao", BlogDao.class);
		BlogDo blog = new BlogDo();
		blog.setAuthor("猫哥");
		blog.setTitle("测试博客");
		blog.setContent("非常完美吭");
		// 测试插入
		blogDao.insert(blog);
		// 测试获取1个
		System.out.println(blogDao.getById(2L));
		// 测试获取列表
		System.out.println(blogDao.getList().size());
		blog.setId(3L);
		blog.setContent("非常完美吭XX");
		// 修改
		blogDao.update(blog);
		// 删除
		blogDao.delete(4L);
	}
}

总结

使用JdbcTemplate之后,确实将重复的模板代码基本都消灭了,我们可以关心真正的业务逻辑。

发布了345 篇原创文章 · 获赞 240 · 访问量 53万+

猜你喜欢

转载自blog.csdn.net/woshisangsang/article/details/104106054