SpringBoot整合JDBC
1、 在SpringBoot整合Jdbc只需要找到启动器即可,首先导入jdbc启动器配置及数据库驱动
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
2、代码: 下面是我的项目结构
3、先在resource下创建一个yml 存放数据库的连接配置。
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/test
username: root
password: 1234
4、实体类:
public class Goods {
private Integer id;
private String name;
private Double price;
private Integer num;
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 getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
public Integer getNum() {
return num;
}
public void setNum(Integer num) {
this.num = num;
}
}
GoodsDao.class
public interface GoodsDao {
List<Goods> findAll();
}
GoodsDaoImpl.class
@Repository
public class GoodsDaoImpl implements GoodsDao {
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
public List<Goods> findAll() {
String sql="SELECT * FROM GOODS";
List<Goods> list=
jdbcTemplate.query(sql,new Object[]{},new BeanPropertyRowMapper<>(Goods.class));
if(list.size()>0&&list!=null){
return list;
}
return null;
}
}
GoodsService.class
public interface GoodsService {
List<Goods> findAll();
}
GoodsServiceImpl
@Service
public class GoodsServiceImpl implements GoodsService {
@Autowired
private GoodsDao goodsDao;
@Override
public List<Goods> findAll() {
return goodsDao.findAll();
}
}
GoodsController.class
@RestController
public class GoodsController {
@Autowired
private GoodsService goodsService;
@GetMapping("findAll")
public List<Goods> findAll(){
return goodsService.findAll();
}
}
写完调试:
以上就是一个最简单SpringBoot整合JDBC了。