1.工程的坐标依赖
junit
junit
4.12
test
org.springframework
spring-test 4.3.2.RELEASE
test
org.springframework
spring-context 4.3.2.RELEASE
org.aspectj aspectjweaver 1.8.9
mysql
mysql-connector-java 5.1.39
c3p0
c3p0
0.9.1.2
org.springframework
spring-jdbc 4.3.2.RELEASE
org.springframework spring-tx 4.3.2.RELEASE
创建db.propertie
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring_jdbc?useUnicode=true&characterEncoding=utf8
jdbc.user=root jdbc.password=root
可选配置
initialPoolSize=20
maxPoolSize=100
minPoolSize=10
maxIdleTime=600
acquireIncrement=5
maxStatements=5
idleConnectionTestPeriod=60
创建spring—db.xml
配置数据源,选择c3p0
C3P0 其他额外配置(对应的值在 db.properties 文件中指定)
dbcp 数据源配置
Spring把JDBC中重复的操作建立成了一个模板类,org.springframework.jdbc.core.JdbcTemplate ,配置文件中加入
创建数据库
具体实现
spring-jdbc.xml
编写po层,和数据库形成映射
package com.sxt.po;
import java.math.BigDecimal;
import java.util.Date;
public class Account {
private Integer id;
private String name;
private BigDecimal money;
private Integer userId;
private Date createTime;
private Date updateTime;
private String remark;
private String type;
public Account() {
}
public Account(String name, BigDecimal money, Integer userId, Date createTime, Date updateTime, String remark, String type) {
this.name = name;
this.money = money;
this.userId = userId;
this.createTime = createTime;
this.updateTime = updateTime;
this.remark = remark;
this.type = type;
}
@Override
public String toString() {
return "Account{" +
"id=" + id +
", name='" + name + '\'' +
", money=" + money +
", userId=" + userId +
", createTime=" + createTime +
", updateTime=" + updateTime +
", remark='" + remark + '\'' +
", type='" + type + '\'' +
'}';
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public BigDecimal getMoney() {
return money;
}
public void setMoney(BigDecimal money) {
this.money = money;
}
public Integer getUserId() {
return userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
编写dao层,接口
package com.sxt.dao;
import com.sxt.po.Account;
import java.util.List;
public interface AccountDao {
/**
* 添加记录,返回影响的行数
* @param account
* @return
*/
public Integer saveAccount(Account account);
/**
* 添加记录,返回主键
* @param account
* @return
*/
public Integer saveAccountHasPrimaryKey(Account account);
/**
* 批量添加账户记录,返回受影响的行数
* @param accounts
* @return
*/
public Integer saveAccountsBatch(List accounts);
/**
* 统计账户记录-聚合查询
* @param userId
* @return
*/
public Integer countAccountsByUserId(Integer userId);
/**
* 根据Id,查询记录详情
* @param userId
* @return
*/
public Account queryAccountById(Integer userId);
/**
* 多条件查询
* @param userId
* @param type
* @param createTime
* @param aname
* @return
*/
public List queryAccountsByParams(Integer userId,String type,String createTime,String aname);
/**
* 更新账户记录
* @param account
* @return
*/
public Integer updateAccount(Account account);
/**
* 批量更新
* @param accounts
* @return
*/
public Integer updateAccountsBatch(List accounts);
/**
* 根据id 删除记录
* @param id
* @return
*/
public Integer deleteAccountById(Integer id);
/**
* 批量删除,删除的id为一个数组
* @param ids
* @return
*/
public Integer deleteAccountsBatch(Integer[] ids);
}
编写impl层的daoImpl,继承接口,实现方法
package com.sxt.dao.impl;
import com.sxt.dao.AccountDao;
import com.sxt.po.Account;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;
import org.springframework.stereotype.Repository;
import javax.annotation.Resource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
@Repository
public class AccountDaoImpl implements AccountDao {
@Resource
private JdbcTemplate jdbcTemplate;
//添加记录,返回影响的行数
@Override
public Integer saveAccount(Account account) {
String sql="insert into account(aname,type,money,user_id,create_time,update_time,remark) " +
" values(?,?,?,?,?,?,?)";
return jdbcTemplate.update(sql,account.getName(),account.getType(),account.getMoney(),account.getUserId(),account.getCreateTime(),account.getUpdateTime(),account.getRemark());
}
//添加记录,返回主键
@Override
public Integer saveAccountHasPrimaryKey(Account account) {
String sql="insert into account(aname,type,money,user_id,create_time,update_time,remark) " +
" values(?,?,?,?,?,?,?)";
KeyHolder keyHolder=new GeneratedKeyHolder();
jdbcTemplate.update(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
PreparedStatement ps= con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
ps.setString(1,account.getName());
ps.setString(2,account.getType());
ps.setBigDecimal(3,account.getMoney());
ps.setInt(4,account.getUserId());
ps.setObject(5,account.getCreateTime());
ps.setObject(6,account.getUpdateTime());
ps.setString(7,account.getRemark());
return ps;
}
}, keyHolder);
// 返回主键
return keyHolder.getKey().intValue();
}
//批量添加账户记录,返回受影响的行数
@Override
public Integer saveAccountsBatch(List accounts) {
String sql="insert into account(aname,type,money,user_id,create_time,update_time,remark) " +
" values(?,?,?,?,?,?,?)";
return jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
@Override
public void setValues(PreparedStatement ps, int i) throws SQLException {
Account account= accounts.get(i);
ps.setString(1,account.getName());
ps.setString(2,account.getType());
ps.setBigDecimal(3,account.getMoney());
ps.setInt(4,account.getUserId());
ps.setObject(5,account.getCreateTime());
ps.setObject(6,account.getUpdateTime());
ps.setString(7,account.getRemark());
}
@Override
public int getBatchSize() {
// 批量添加记录的总条数
return accounts.size();
}
}).length;
}
@Override
public Integer countAccountsByUserId(Integer userId) {
return null;
}
@Override
public Account queryAccountById(Integer userId) {
return null;
}
@Override
public List queryAccountsByParams(Integer userId, String type, String createTime, String aname) {
return null;
}
@Override
public Integer updateAccount(Account account) {
return null;
}
@Override
public Integer updateAccountsBatch(List accounts) {
return null;
}
@Override
public Integer deleteAccountById(Integer id) {
return null;
}
@Override
public Integer deleteAccountsBatch(Integer[] ids) {
return null;
}
}
借助spring框架的测试类注解,达到简便扫描方法
package com.sxt;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring-jdbc.xml"})
public class TestBase {
}
继承TestBase
package com.sxt;
import com.sxt.dao.AccountDao;
import com.sxt.po.Account;
import org.junit.Test;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
public class TestAccountDao extends TestBase {
@Resource
private AccountDao accountDao;
@Test
public void test01(){
//BigDecimal.valueOf(8000) int无法转换
System.out.println(accountDao.saveAccount(new Account("中国好男人", BigDecimal.valueOf(8000),1,new Date(),new Date(),"男儿志","1")));
}
}
查询总记录
package com.sxt;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import javax.annotation.Resource;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring-jdbc.xml"})
public class TestJdbcTemplate {
@Resource
private JdbcTemplate jdbcTemplate;
@Test
public void test01(){
String sql = "select count(1) from account";
Integer total = jdbcTemplate.queryForObject(sql,Integer.class);
System.out.println("总记录"+total);
}
}