目录
项目目录
com/qcby/
├── dao/ --数据访问层(Data Access Object)
│ ├── impl/ --接口实现类
│ │ └── AccountDaoImpl.java --AccountDao接口的实现
│ └── AccountDao.java --账户数据访问接口
├── model/ --实体模型层
│ └── Account.java --账户实体类
└── service/ --业务逻辑层
├── impl/ --接口实现类
│ └── AccountServiceImpl.java --AccountService接口的实现
└── AccountService.java --账户业务逻辑接口
main/resources/ - 资源配置
- applicationContext.xml - Spring 核心配置文件,用于 Bean 管理和依赖注入
test/java/com/qcby/ - 测试代码
- AccountTest.java - 账户相关的测试类
Spring框架开发方式
1. 创建数据库,创建表结构
sql
create database spring_db;
use spring_db;
create table account(
id int primary key auto_increment,
name varchar(40),
money double
)character set utf8 collate utf8_general_ci;
insert into account(name,money) values('aaa',1000);
insert into account(name,money) values('bbb',1000);
insert into account(name,money) values('ccc',1000);
2. 导入依赖:pom.xml
- 创建maven Java项目
- 导入开发jar包
- 持久层使用原始的JDBC程序,连接池使用Druid连接池。
XML
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.2.RELEASE</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.12</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- 连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
<!-- mysql驱动包 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
</dependencies>
3. 编写JavaBean的类: Account类
- 实现Serializable接口
- 设置私有属性:id、name、money
- 设置公共getter/setter
- 重新toString()方法
java
package com.qcby.model;
import java.io.Serializable;
public class Account implements Serializable {
private static final long serialVersionUID = 7355810572012650248L;
private Integer id;
private String name;
private Double money;
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 Double getMoney() {
return money;
}
public void setMoney(Double money) {
this.money = money;
}
@Override
public String toString() {
return "Account{" +
"id=" + id +
", name='" + name + '\'' +
", money=" + money +
'}';
}
}
4. 编写数据访问层的接口: AccountDao类
java
package com.qcby.dao;
import com.qcby.model.Account;
import java.util.List;
public interface AccountDao {
public List<Account> findAll();
}
5. 编写AccountDao的实现类: AccountDaoImpl类
- 注入连接池对象:通过**setter方法(DI依赖注入)**注入DataSource
java
// 注入连接池对象
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
-
实现findAll()方法
- 初始化
javaList<Account> list = new ArrayList<>(); Connection connection = null; PreparedStatement stmt = null; ResultSet rs = null;- 从连接池中获取数据库连接
java// 获取连接 connection = dataSource.getConnection();- 执行SQL
- 使用PreparedStatement防止SQL注入
- 执行查询获取结果集
java// 编写sql语句 String sql = "select * from account"; // 预编译 stmt = connection.prepareStatement(sql); // 查询 rs = stmt.executeQuery();- 结果集处理
java// 遍历,封装数据 while (rs.next()){ Account account = new Account(); account.setId(rs.getInt("id")); account.setName(rs.getString("name")); account.setMoney(rs.getDouble("money")); list.add(account); }- 关闭资源
javafinally { try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } }
完整代码:
java
package com.qcby.dao.impl;
import com.qcby.dao.AccountDao;
import com.qcby.model.Account;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class AccountDaoImpl implements AccountDao {
// 注入连接池对象
private DataSource dataSource;
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
/**
* 查询所有的数据
* @return
*/
@Override
public List<Account> findAll() {
/*
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql:///spring_db");
dataSource.setUsername("root");
dataSource.setPassword("root");
*/
List<Account> list = new ArrayList<>();
Connection connection = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
// 获取连接
connection = dataSource.getConnection();
// 编写sql语句
String sql = "select * from account";
// 预编译
stmt = connection.prepareStatement(sql);
// 查询
rs = stmt.executeQuery();
// 遍历,封装数据
while (rs.next()){
Account account = new Account();
account.setId(rs.getInt("id"));
account.setName(rs.getString("name"));
account.setMoney(rs.getDouble("money"));
list.add(account);
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
return list;
}
}
6. 编写业务层的接口: AccountService类
java
package com.qcby.service;
import com.qcby.model.Account;
import java.util.List;
public interface AccountService {
public List<Account> findAll();
}
7. 编写AccountService的实现类: AccountServiceImpl类
- 注入依赖:通过setter方法(DI依赖注入),通过AccountDao访问数据层
- 查询数据
java
package com.qcby.service.impl;
import com.qcby.dao.AccountDao;
import com.qcby.model.Account;
import com.qcby.service.AccountService;
import java.util.List;
public class AccountServiceImpl implements AccountService {
// 依赖注入
private AccountDao accountDao;
public void setAccountDao(AccountDao accountDao) {
this.accountDao = accountDao;
}
/**
* 查询所有的数据
* @return
*/
@Override
public List<Account> findAll() {
return accountDao.findAll();
}
}
8. 编写配置文件: applicationContext.xml
- 使用Bean配置连接池
- 使用Bean管理
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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<!--配置连接池-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
<property name="url" value="jdbc:mysql:///spring_db"></property>
<property name="username" value="root"></property>
<property name="password" value="root"></property>
</bean>
<!--管理bean-->
<bean id="accountService" class="com.qcby.service.impl.AccountServiceImpl">
<property name="accountDao" ref="accountDao" />
</bean>
<bean id="accountDao" class="com.qcby.dao.impl.AccountDaoImpl">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
9. 编写测试类: AccountTest类
java
package com.qcby;
import com.qcby.model.Account;
import com.qcby.service.AccountService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.util.List;
public class AccountTest {
@Test
public void run1(){
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
AccountService accountService = (AccountService) ac.getBean("accountService");
// 调用方法
List<Account> list = accountService.findAll();
for (Account account : list) {
System.out.println(account);
}
}
}