第一步:引入依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
mysql的连接类和连接池
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.29</version>
</dependency>
Spring Boot的相关依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
第二步:配置文件的数据库连接信息
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=root
第三步:具体代码编写
实体类
@Data
public class Account {
private int id ;
private String name ;
private double money;
}
dao层
public interface IAccountDAO {
int add(Account account);
int update(Account account);
int delete(int id);
Account findAccountById(int id);
List<Account> findAccountList();
}
dao实现类代码
@Repository
public class AccountDaoImpl implements IAccountDAO {
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public int add(Account account) {
return jdbcTemplate.update("insert into account(name, money) values(?, ?)",
account.getName(),account.getMoney());
}
@Override
public int update(Account account) {
return jdbcTemplate.update("UPDATE account SET NAME=? ,money=? WHERE id=?",
account.getName(),account.getMoney(),account.getId());
}
@Override
public int delete(int id) {
return jdbcTemplate.update("DELETE from TABLE account where id=?",id);
}
@Override
public Account findAccountById(int id) {
List<Account> list = jdbcTemplate.query("select * from account where id = ?", new Object[]{id}, new BeanPropertyRowMapper(Account.class));
if(list!=null && list.size()>0){
Account account = list.get(0);
return account;
}else{
return null;
}
}
@Override
public List<Account> findAccountList() {
List<Account> list = jdbcTemplate.query("select * from account", new Object[]{}, new BeanPropertyRowMapper(Account.class));
if(list!=null && list.size()>0){
return list;
}else{
return null;
}
}
}