首先
jdbc.properties
jdbc.driverClass=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1/work?useSSL=false&serverTimezone=UTC
jdbc.user=root
jdbc.password=123456
jdbc.initialPoolSize = 5
jdbc.maxPoolSize = 10
applicaitoncontext.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"
xmlns:conttext="http://www.springframework.org/schema/tool"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tool http://www.springframework.org/schema/tool/spring-tool.xsd">
<context:component-scan base-package="SpringTemplate"/>
<!-- 1导入资源文件-->
<context:property-placeholder location="classpath:JDBCTEM/jdbctem.properties"/>
<!-- 2配置C3P0数据源-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="${jdbc.user}"/>
<property name="jdbcUrl" value="${jdbc.url}"/>
<property name="password" value="${jdbc.password}"/>
<property name="driverClass" value="${jdbc.driverClass}"/>
<property name="initialPoolSize" value="${jdbc.initialPoolSize}"/>
<property name="maxPoolSize" value="${jdbc.maxPoolSize}"/>
</bean>
<!--3配置Spring 的JDBCTemplate-->
<bean id="JdbcTemplate"
class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
</beans>
1.存在一个已有的数据库
2.创建对应的Three
@Repository
public class Three {
private int id;
private String name;
private int value;
@Override
public String toString() {
return "Three{" +
"id=" + id +
", name='" + name + '\'' +
", value=" + value +
'}';
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
3.创建ThreeDao
@Component("ThreeDao")
public class ThreeDao {
@Autowired
private JdbcTemplate jdbcTemplate;
public Three get(Integer id){
String sql = "select * from three where id =?";
RowMapper<Three> rowMapper = new BeanPropertyRowMapper<Three>(Three.class);
Three three = jdbcTemplate.queryForObject(sql,rowMapper,id);
return three;
}
}
4.Test
public class TemplatedUseTest {
ApplicationContext context;
private JdbcTemplate jdbcTemplate;
private ThreeDao threeDao;
{
context=new ClassPathXmlApplicationContext(
"classpath:JDBCTEM/JDBCTEMcontext.xml"
);
jdbcTemplate=(JdbcTemplate) context.getBean("JdbcTemplate");
threeDao =(ThreeDao) context.getBean("ThreeDao");
}
@Test
public void TemplatedUseTEST(){
System.out.println(threeDao.get(1));
}
}