这里使用springboot自带的jdbcTemplate连接mysql数据库
1. 添加依赖包
<!-- jdbc --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.45</version> </dependency>
2. 在配置文件application.properties中添加jdbc的连接配置
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
3. 在service层的实现类中使用如下方式查询
//装配jdbcTemplate @Autowired private JdbcTemplate jdbcTemplate; //调用查询方法 @Override public List<User> getUserList() { String sql = "select id,user_code as code,user_name as username,user_pwd as password,update_tmsp as updateTime from m_user"; List<User> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<User>(User.class)); return list; }
4. 在启动类中加入包的扫描
@ComponentScan(basePackages={"com.king.controller","com.king.service"}) @EnableAutoConfiguration public class App { public static void main(String[] args) { SpringApplication.run(App.class, args); } }