SpringBoot(九)-- SpringBoot JDBC
1.属性配置文件(application.properties)
# type 可以修改连接池类型,默认采用Tomcat的连接池
# spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.url=jdbc:mysql://localhost:3306/consult
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=org.gjt.mm.mysql.Driver
2.pom.xml 配置maven依赖
<!-- MYSQL --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <!-- Spring Boot JDBC --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency>
3.Java查询示例
1 import java.sql.ResultSet; 2 import java.sql.SQLException; 3 import java.util.List; 4 import java.util.Map; 5 import org.springframework.beans.factory.annotation.Autowired; 6 import org.springframework.jdbc.core.JdbcTemplate; 7 import org.springframework.jdbc.core.RowMapper; 8 import org.springframework.stereotype.Service; 9 /** 10 * service层 11 */ 12 @Service 13 public class CommonServiceImpl implements CommonService { 14 15 // 注入JdbcTemplate 16 @Autowired 17 private JdbcTemplate jdbcTemplate; 18 19 public List<ConsultContent> queryContent(Map map) { 20 String sql = "select * from consult_content a where a.state = 0 and a.type = 1 order by a.itemindex"; 21 return jdbcTemplate.query(sql, new RowMapper<ConsultContent>() { 22 23 public ConsultContent mapRow(ResultSet rs, int rowNum) 24 throws SQLException { 25 ConsultContent cc = new ConsultContent(); 26 cc.setContent(rs.getString("content")); 27 cc.setId(rs.getInt("id")); 28 cc.setItemIndex(rs.getInt("itemIndex")); 29 cc.setState(rs.getInt("state")); 30 cc.setType(rs.getString("type")); 31 return cc; 32 } 33 }); 34 } 35 }