Spring JdbcTemplate
01. 坐标导入
> spring-jdbc : jdbc模板的使用;
> spring-tx : 事务
> spring-context:
> mysql-connector-java : mysql驱动
> druid : 连接池
> spring-test : spring测试单元
> junit : 测试单元
02. 配置数据库连接配置 jdbc.properties
1 jdbc.driver=com.mysql.cj.jdbc.Driver 2 jdbc.url=jdbc:mysql://localhost:3306/travel 3 jdbc.username=root 4 jdbc.password=123456
03. applicationContext.xml 配置
1 <!--配置文件指定--> 2 <context:property-placeholder location="classpath:jdbc.properties"/> 3 4 <!--数据源--> 5 <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> 6 <property name="driverClassName" value="${jdbc.driver}"/> 7 <property name="url" value="${jdbc.url}"/> 8 <property name="username" value="${jdbc.username}"/> 9 <property name="password" value="${jdbc.password}"/> 10 </bean> 11 12 <!--jdbcTemplate--> 13 <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate"> 14 <property name="dataSource" ref="dataSource"/> 15 </bean>
04. 配置 pojo 对象
1 public class tab_category { 2 private Integer cid; 3 private String cname; 4 5 public Integer getCid() { 6 return cid; 7 } 8 9 public void setCid(Integer cid) { 10 this.cid = cid; 11 } 12 13 public String getCname() { 14 return cname; 15 } 16 17 public void setCname(String cname) { 18 this.cname = cname; 19 } 20 21 @Override 22 public String toString() { 23 return "tab_category{" + 24 "cid=" + cid + 25 ", cname='" + cname + '\'' + 26 '}'; 27 } 28 }
05. 配置测试
1 @RunWith(SpringJUnit4ClassRunner.class) 2 @ContextConfiguration("classpath:applicationContext.xml") 3 public class JDBCTest { 4 5 @Autowired 6 private JdbcTemplate jdbcTemplate; 7 8 @Test 9 /*添加*/ 10 public void test01(){ 11 int i = jdbcTemplate.update("insert into tab_category value (?,?)", 9, "测试组"); 12 System.out.println(i); 13 } 14 15 @Test 16 /*修改*/ 17 public void test02(){ 18 int i = jdbcTemplate.update("update tab_category set cname =? where cid=?", "测试组(new)",9); 19 System.out.println(i); 20 } 21 22 @Test 23 /*查询单个*/ 24 public void test03(){ 25 tab_category category = jdbcTemplate.queryForObject("select * from tab_category where cid=?", new BeanPropertyRowMapper<tab_category>(tab_category.class), 9); 26 System.out.println(category); 27 } 28 29 @Test 30 /*查询多个*/ 31 public void test04(){ 32 List<tab_category> categories = jdbcTemplate.query("select * from tab_category ", new BeanPropertyRowMapper<tab_category>(tab_category.class)); 33 System.out.println(categories); 34 } 35 36 @Test 37 /*删除*/ 38 public void test05(){ 39 int i = jdbcTemplate.update("delete from tab_category where cid=?", 9); 40 System.out.println(i); 41 } 42 }