封装JDBC
Spring对JDBC技术规范做了进一步的封装,又叫Spring jdbcTemplate(jabc模板技术)
public class Account implements Serializable{
public static final long serialVersionUID = 1L;
private int id;
private String name;
private double balance;
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 double getBalance() {
return balance;
}
public void setBalance(double balance) {
this.balance = balance;
}
public Account(){}
public Account(int id, String name, double balance) {
super();
this.id = id;
this.name = name;
this.balance = balance;
}
public Account(String name, double balance) {
super();
this.name = name;
this.balance = balance;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
long temp;
temp = Double.doubleToLongBits(balance);
result = prime * result + (int) (temp ^ (temp >>> 32));
result = prime * result + id;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Account other = (Account) obj;
if (Double.doubleToLongBits(balance) != Double.doubleToLongBits(other.balance))
return false;
if (id != other.id)
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
@Override
public String toString() {
return "Account [id=" + id + ", name=" + name + ", balance=" + balance + "]";
}
}
Jdbc的配置类
@Configuration
@PropertySource("classpath:jdbc.properties") //你的jdbc配置信息的位置
public class JdbcConfig {
//1.获取配置信息
@Value("${jdbc.driverClass}")
private String driver;
@Value("${jdbc.url}")
private String url;
@Value("${jdbc.username}")
private String username;
@Value("${jdbc.password}")
private String password;
@Value("${pool.maxActive}")
private int maxActive;
//--2.要有数据库连接池对象
@Bean(name="dataSource")
public DataSource createDataSource(){
DruidDataSource ds = new DruidDataSource();
ds.setDriverClassName(driver);
ds.setUrl(url);
ds.setUsername(username);
ds.setPassword(password);
ds.setMaxActive(maxActive); //设置最大连接数
return ds;
}
//3.配置JDBCTemplate
@Bean(name="jdbcTemplate")
public JdbcTemplate createJdbcTemplate(DataSource ds){
return new JdbcTemplate(ds); //利用数据源构造jdbcTemplate
}
}
Spring 配置类
@Configuration
@ComponentScan("day10_31") //包名
@Import(JdbcConfig.class) //-- 在主配置中导入子配置
public class SpringConfig {
}
AccountDao接口
public interface IAccountDao {
//查找数据
List<Account> findAll();
//实现数据库的增改
void saveOrUpdate(Account act); //act.getID
//实现数据的删除
void delete(Account act);
}
封装JDBC
@Repository("accountDaoTemplateImpl")
public class AccountDaoTemplateImpl implements IAccountDao{
@Autowired
private JdbcTemplate jdbcTemplate;
//查找数据
@Override
public List<Account> findAll() {
return jdbcTemplate.query
("select * from account",
new BeanPropertyRowMapper<Account>(Account.class));
}
//实现数据库的增加和更新
@Override
public void saveOrUpdate(Account act) {
if(act.getId() == 0){
jdbcTemplate.update(
"insert into account(name,balance) values(?,?)",
new Object[]{act.getName(),act.getBalance()});
}else{
jdbcTemplate.update(
"update account set name=?,balance=? where id=?",
new Object[]{act.getName(),act.getBalance(),act.getId()});
}
}
//删除数据
@Override
public void delete(Account act) {
jdbcTemplate.update("delete from account where id =?"
,new Object[]{act.getId()});
}
}
AccountDao测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={SpringConfig.class})
public class TestAccountDao {
@Autowired
@Qualifier("accountDaoTemplateImpl") //换accountDaoJdbcImpl
private IAccountDao actDao;
//查找数据
@Test
public void testFind(){
System.out.println("aaa");
List<Account> acts = actDao.findAll();
for (Account act: acts) {
System.out.println(act);
}
}
//插入数据
@Test
public void testSave(){
actDao.saveOrUpdate(new Account("xxx",22.0));
}
//更新数据
@Test
public void testUpdate(){
actDao.saveOrUpdate(new Account(12,"xxx",22.0));
}
//删除数据
@Test
public void testDelete(){
actDao.delete(new Account(12,"xxx",22.0));
}
}
jdbc.properties
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/db_chat
jdbc.username=root
jdbc.password=root
pool.maxActive=10
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<!-- 1. 项目的整体信息 -->
<modelVersion>4.0.0</modelVersion>
<groupId>com.uek.project</groupId>
<artifactId>spring-app</artifactId>
<version>0.1</version>
<packaging>war</packaging>
<!-- 2. 项目属性配置 -->
<properties>
<!-- 项目编码使用UTF-8 -->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<!-- 忽略掉web.xml文件 ,因为我们使用servlet3.0开发web项目 -->
<failOnMissingWebXml>false</failOnMissingWebXml>
<!-- 自定义版本标记 -->
<spring.version>5.1.7.RELEASE</spring.version>
</properties>
<!-- 3. 配置项目所需要的第三方jar 包 -->
<dependencies>
<!-- servlet api -->
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/javax.servlet.jsp.jstl/jstl -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!--Spring框架 IOC 第一天要引入的 -->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- Spring框架 AOP 第二天引入的 -->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.8.10</version>
</dependency>
<dependency>
<groupId>aopalliance</groupId>
<artifactId>aopalliance</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.10</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- Spring Test -->
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- Spring与JDBC的整合 -->
<!-- 整合JDBC需要用到的jar,当然再整合MyBatis框架也需要用到此处用到的jar -->
<!-- MySQL数据库驱动 -->
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.48</version>
</dependency>
<!-- druid数据库连接池 -->
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.20</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
</dependencies>
<!-- 配置构建插件 -->
<build>
<plugins>
<plugin>
<!-- 编译插件 -->
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
<!-- Tomcat 插件 -->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<port>8080</port>
<path>/airsys</path>
<!-- 实现热部署,不需要每次修改代码后都重新启动Tomcat -->
<contextReloadable>true</contextReloadable>
</configuration>
</plugin>
</plugins>
</build>
</project>