● 根本介绍

  1. 经过 Spring 能够装备数据源,从而完成对数据表的操作
  2. JdbcTemplate 是 Spring 供给的访问数据库的技能。能够将 JDBC 的常用操作封装为模板办法。

运用API的技巧

  1. 先确认API的姓名
  2. 依据API供给的相应的参数
  3. 把自己的调用思路清晰

运用JdbcTemplate

查询 (SELECT

单行单列

第一种办法

这种写法是更推荐的办法,特别适用于查询单行单列并将成果映射到指定类型的状况。经过传递成果的预期类型作为requiredType参数,您能够保证查询成果将直接映射到该类型,而不需求手动编写RowMapper完成。

@Test
public void test11() {  
	ClassPathXmlApplicationContext ioc = new ClassPathXmlApplicationContext("bean.xml");  
	JdbcTemplate jdbcTemplate = ioc.getBean(JdbcTemplate.class);  
	// 确认API  
	// public <T> T queryForObject(String sql, Class<T> requiredType, @Nullable Object... args)
	String sql = "select name from monster where id = ?";  
	String name = jdbcTemplate.queryForObject(sql, String.class, 200);  
	System.out.println("name = " + name);  
}

第二种办法

@Test
public void test10() {  
	ClassPathXmlApplicationContext ioc = new ClassPathXmlApplicationContext("bean.xml");  
	JdbcTemplate jdbcTemplate = ioc.getBean(JdbcTemplate.class);  
	// 确认API  
	// <T> T queryForObject(String sql, RowMapper<T> rowMapper, @Nullable Object... args)  
	String sql = "select name from monster where id = ?";  
	String name = jdbcTemplate.queryForObject(sql,  
	(ResultSet rs, int rowNum) -> rs.getString("name"), 200);  
	System.out.println("name = " + name);  
}

单个方针

第一种办法

@Test
public void test6() {  
	ClassPathXmlApplicationContext ioc = new ClassPathXmlApplicationContext("bean.xml");  
	JdbcTemplate jdbcTemplate = ioc.getBean(JdbcTemplate.class);  
	// 确认API  
	// <T> T queryForObject(String sql, RowMapper<T> rowMapper, @Nullable Object... args)  
	String sql = "select id AS `monsterId`, name, skill from monster where id = ?";  
	//这里有一个细节就是称号需求一样, 即查询的表字需求和查询的字段保持一致  
	RowMapper<Monster> rowMapper = new RowMapper<Monster>() {  
	@Override  
	public Monster mapRow(ResultSet rs, int rowNum) throws SQLException {  
			Monster monster = new Monster();  
			monster.setSkill(rs.getString("skill"));  
			monster.setName(rs.getString("name"));  
			monster.setMonsterId(rs.getInt("monsterId"));  
			return monster;  
		}  
	};  
	// 能够运用lambda表达式简化  
	Monster monster = jdbcTemplate.queryForObject(sql, rowMapper, 100);  
	System.out.println("monster = " + monster);  
}

第二种办法

@Test
public void test7() {  
	ClassPathXmlApplicationContext ioc = new ClassPathXmlApplicationContext("bean.xml");  
	JdbcTemplate jdbcTemplate = ioc.getBean(JdbcTemplate.class);  
	// 确认API  
	// <T> T queryForObject(String sql, RowMapper<T> rowMapper, @Nullable Object... args)  
	String sql = "select id AS `monsterId`, name, skill from monster where id = ?";  
	// 运用子类完成方针的封装  
	RowMapper<Monster> rowMapper = new BeanPropertyRowMapper<>(Monster.class);  
	Monster monster = jdbcTemplate.queryForObject(sql, rowMapper, 100);  
	System.out.println("monster = " + monster);  
}
  • test6()办法运用了匿名内部类完成的RowMapper,在mapRow()办法中手动设置了查询成果的映射关系,将查询成果映射到Monster方针中。
  • test7()办法运用了BeanPropertyRowMapper,它是Spring供给的一种便利的RowMapper完成,能够依据成果集的列名和方针方针的特色名进行主动映射。

两种写法都是能够的,但有一些考虑要素能够帮助您挑选适合您的状况:

  • 如果您的查询成果需求进行自定义的映射逻辑,或许需求处理一些特别的转换操作,您能够挑选test6()的写法,并经过自定义的RowMapper完成进行映射。
  • 如果您的查询成果与方针方针的特色名和类型完全一致,或许您不需求进行额定的映射操作,您能够挑选test7()的写法,并运用BeanPropertyRowMapper进行主动映射。

整体而言,test7()的写法更加简练和便利,因为它利用了BeanPropertyRowMapper的主动映射功能,能够减少手动编写映射逻辑的工作量。然而,如果您需求更复杂的映射逻辑或转换操作,test6()的写法能够给您更大的灵活性

多个方针

办法一

@Test
public void test9() {  
	ClassPathXmlApplicationContext ioc = new ClassPathXmlApplicationContext("bean.xml");  
	JdbcTemplate jdbcTemplate = ioc.getBean(JdbcTemplate.class);  
	// 确认API  
	String sql = "select id AS `monsterId`, name, skill from monster where id > ?";  
	RowMapper<Monster> rowMapper = new BeanPropertyRowMapper<>(Monster.class);  
	List<Monster> query = jdbcTemplate.query(sql, rowMapper, 100);  
	for (Monster monster : query) {  
		System.out.println("monster = " + monster);  
	}  
}

办法二

@Test
public void test8() {  
	ClassPathXmlApplicationContext ioc = new ClassPathXmlApplicationContext("bean.xml");  
	JdbcTemplate jdbcTemplate = ioc.getBean(JdbcTemplate.class);  
	// 确认API  
	// <T> T queryForObject(String sql, RowMapper<T> rowMapper, @Nullable Object... args)  
	String sql = "select id AS `monsterId`, name, skill from monster where id > ?";  
	// 运用lambda表达式简化
	List<Monster> monsterList = jdbcTemplate.query(sql, 
	(ResultSet rs, int rowNum) -> {  
		Monster monsters = new Monster(rs.getInt("monsterId"), rs.getString("name"), rs.getString("skill"));  
		return monsters;  
	}, 100);  
	for (Monster monster : monsterList) {  
		System.out.println("monster = " + monster);  
	}  
}

更新(INSERTUPDATEDELETE

你能够运用update(..)办法来履行刺进、更新和删去操作。参数值通常作为变量参数供给,或许作为一个方针数组供给

INSERT

this.jdbcTemplate.update( "insert into t_actor (first_name, last_name) values (?, ?)", "Leonor", "Watling");

怎么完成刺进多条数据 ?

@Test
public void test5() {  
	ClassPathXmlApplicationContext ioc = new ClassPathXmlApplicationContext("bean.xml");  
	JdbcTemplate jdbcTemplate = ioc.getBean(JdbcTemplate.class);  
	// 1. 批量刺进 猜想update => 依据参数修改称号是 batchUpdate// 2. 依据参数供给数据  
	String sql = "insert into monster values (?, ?, ?)";  
	List<Object[]> list = new ArrayList<>();  
	list.add(new Object[]{700, "老鼠精", "偷吃粮食"});  
	list.add(new Object[]{800, "老猫精", "抓老鼠"});  
	// 3. 调试  
	// 阐明:  
	// 返回成果是一个数组, 每一个元素对应的上面的sql句子影响的行数  
	int[] ints = jdbcTemplate.batchUpdate(sql, list);  
	// 4. 输出  
	for (int anInt : ints) {  
	System.out.println("anInt: " + anInt);  
	}  
	System.out.println("add ok ~");  
}

UPDATE

this.jdbcTemplate.update(
        "update t_actor set last_name = ? where id = ?",
        "Banjo", 5276L);

DELETE

this.jdbcTemplate.update(
        "delete from t_actor where id = ?",
        Long.valueOf(actorId));

运用NamedParameterJdbcTemplate

签字参数

签字参数的写法具有以下特色:

  • 运用冒号(:)作为参数的前缀,例如:id:name:skill
  • 冒号后面的字符串是参数的称号,用于在Map方针中进行参数值的映射。
  • SQL句子中的签字参数和实际的参数值将在履行时进行匹配和替换。
@Test
public void test12() {  
	ClassPathXmlApplicationContext ioc = new ClassPathXmlApplicationContext("bean.xml");  
	NamedParameterJdbcTemplate namedParameterJdbcTemplate = ioc.getBean(NamedParameterJdbcTemplate.class);  
	// 签字参数  
	// :id, :name, :skill 不需求知道表的结构  
	String sql = "insert into monster values (:id, :name, :skill)";  
	Map<String, Object> map = new HashMap<>();  
	map.put("id", 900);  
	map.put("name", "蚂蚁精");  
	map.put("skill", "喜爱打洞");  
	int affected = namedParameterJdbcTemplate.update(sql, map);  
	System.out.println("affected = " + affected);  
}

xml文件

<?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">  
	<!-- 装备数据源方针-DataSource-->  
	<bean class="com.mchange.v2.c3p0.ComboPooledDataSource" id="dataSource">  
	<property name="user" value="root"/>  
	<property name="password" value="hsp"/>  
	<property name="driverClass" value="com.mysql.jdbc.Driver"/>  
	<property name="jdbcUrl" value="jdbc:mysql://localhost:3306/spring"/>  
	</bean>  
	<bean class="org.springframework.jdbc.core.JdbcTemplate" id="jdbcTemplate">  
	<property name="dataSource" ref="dataSource"/>  
	</bean>  
	<!-- 装备 NamedParameterJdbcTemplate--><bean class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate" id="parameterJdbcTemplate">  
	<!-- 经过结构器, 设置特色-->  
	<constructor-arg name="dataSource" ref="dataSource" />  
	</bean>  
</beans>

中文文档地址: springdoc.cn/