1. 程式人生 > >spring JdbcTemplate使用 (資料庫持久化一)

spring JdbcTemplate使用 (資料庫持久化一)

目錄

JdbcTemplate是spring中的jdbc操作,有必要了解一下,不一定要使用

配置檔案

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-4.3.xsd">

	<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
		<property name="driverClassName" value="com.mysql.cj.jdbc.Driver" />
		<property name="url" value="jdbc:mysql://127.0.0.1:3306/test" />
		<property name="username" value="root" />
		<property name="password" value="root" />
	</bean>
	<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
		<property name="dataSource" ref="dataSource"/>
	</bean>
</beans>

demo

public class DemoJdbcTemplate {
	private static final Logger logger = LoggerFactory.getLogger(RunMainDbcp.class);

	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext("day5/spring-config.xml");
		JdbcTemplate jdbcTemplate = (JdbcTemplate) context.getBean("jdbcTemplate");
		logger.debug(jdbcTemplate.toString());
		logger.debug("增");
		// insertRole(jdbcTemplate);
		logger.debug("刪");
		// deleteRole(jdbcTemplate);
		logger.debug("改");
		// updateRole(jdbcTemplate);
		logger.debug("查");
		List<Role> role = getRole(jdbcTemplate);
		logger.debug("{}", role);
	}

	private static List<Role> getRole(JdbcTemplate jdbcTemplate) {
		String sql = "sELECT * from role where name like concat('%', ?, '%')";
		Object[] args = {"wawa"};
		List<Role> resultList = jdbcTemplate.query(sql, args, (rs, rownum) -> {
			Role role = new Role();
			role.setId(rs.getInt("id"));
			role.setName(rs.getString("name"));
			role.setDesc(rs.getString("desc"));
			return role;
		});
		return resultList;
	}

	private static void updateRole(JdbcTemplate jdbcTemplate) {
		String sql = "update role set name = ?, `desc` = ? where id = ?";
		Object[] args = {"wawa", "雞介面", -1};
		jdbcTemplate.update(sql, args);
	}

	private static void deleteRole(JdbcTemplate jdbcTemplate) {
		String sql = "delete from role where id = ?";
		Object[] args = {-1};
		jdbcTemplate.update(sql, args);
	}

	private static void insertRole(JdbcTemplate jdbcTemplate) {
		String sql = "insert into role(id, name, `desc`) values(?, ?, ?)";
		Object[] args = {-1, "hehe", "掌門"};
		jdbcTemplate.update(sql, args);
	}
}