SpringBoot整合Jdbc
(1)、添加相关依赖
1 <dependency> 2 <groupId>org.springframework.boot</groupId> 3 <artifactId>spring-boot-starter-jdbc</artifactId> 4 </dependency> 5 6 <dependency> 7 <groupId>mysql</groupId> 8 <artifactId>mysql-connector-java</artifactId> 9 <version>8.0.14</version> 10 </dependency>
(2)、在配置文件中配置数据源相关信息
1 spring.datasource.username=root 2 spring.datasource.password=123456 3 spring.datasource.url=jdbc:mysql://localhost:3306/JdbcDemo?serverTimezone=UTC 4 spring.datasource.driver-class-name=com.mysql.jdbc.Driver
(3)、编写service、dao(为了方便我就写在一起了)
1 package cn.coreqi.service; 2 3 import cn.coreqi.entities.User; 4 import org.springframework.beans.factory.annotation.Autowired; 5 import org.springframework.jdbc.core.BeanPropertyRowMapper; 6 import org.springframework.jdbc.core.JdbcOperations; 7 import org.springframework.jdbc.core.RowMapper; 8 import org.springframework.stereotype.Service; 9 10 import java.util.ArrayList; 11 import java.util.List; 12 13 @Service 14 public class UserService { 15 @Autowired 16 private JdbcOperations jdbcOperations; 17 public void addUser(User user){ 18 jdbcOperations.update("insert into users(UserName,PassWord,Enabled) values (?,?,?)" 19 ,user.getUserName(),user.getPassWord(),user.getEnabled()); 20 } 21 public void addUserList(List<User> users){ 22 List<Object[]> datas = new ArrayList<>(); 23 for (User s : users){ 24 datas.add(new Object[]{s.getUserName(),s.getPassWord(),s.getEnabled()}); 25 } 26 jdbcOperations.batchUpdate("insert into users(UserName,PassWord,Enabled) values (?,?,?)" 27 ,datas); 28 } 29 public User getUserById(Integer id){ 30 RowMapper<User> rowMapper = new BeanPropertyRowMapper<>(User.class); 31 return jdbcOperations.queryForObject("select * from users where Id = ?",rowMapper,id); 32 } 33 public List<User> getUsers(){ 34 RowMapper<User> rowMapper = new BeanPropertyRowMapper<>(User.class); 35 return jdbcOperations.query("select * from users",rowMapper); 36 } 37 public Long getUsersSize(){ 38 return jdbcOperations.queryForObject("select count(Id) from users",Long.class); 39 } 40 }
(4)controller调用即可