SpringBoot(九)-- SpringBoot JDBC

时间:2024-09-27 19:02:50

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查询示例

 import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;
/**
* service层
*/
@Service
public class CommonServiceImpl implements CommonService { // 注入JdbcTemplate
@Autowired
private JdbcTemplate jdbcTemplate; public List<ConsultContent> queryContent(Map map) {
String sql = "select * from consult_content a where a.state = 0 and a.type = 1 order by a.itemindex";
return jdbcTemplate.query(sql, new RowMapper<ConsultContent>() { public ConsultContent mapRow(ResultSet rs, int rowNum)
throws SQLException {
ConsultContent cc = new ConsultContent();
cc.setContent(rs.getString("content"));
cc.setId(rs.getInt("id"));
cc.setItemIndex(rs.getInt("itemIndex"));
cc.setState(rs.getInt("state"));
cc.setType(rs.getString("type"));
return cc;
}
});
}
}