(1)、添加相关依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency> <dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.14</version>
</dependency>
(2)、在配置文件中配置数据源相关信息
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.url=jdbc:mysql://localhost:3306/JdbcDemo?serverTimezone=UTC
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
(3)、编写service、dao(为了方便我就写在一起了)
package cn.coreqi.service; import cn.coreqi.entities.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcOperations;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service; import java.util.ArrayList;
import java.util.List; @Service
public class UserService {
@Autowired
private JdbcOperations jdbcOperations;
public void addUser(User user){
jdbcOperations.update("insert into users(UserName,PassWord,Enabled) values (?,?,?)"
,user.getUserName(),user.getPassWord(),user.getEnabled());
}
public void addUserList(List<User> users){
List<Object[]> datas = new ArrayList<>();
for (User s : users){
datas.add(new Object[]{s.getUserName(),s.getPassWord(),s.getEnabled()});
}
jdbcOperations.batchUpdate("insert into users(UserName,PassWord,Enabled) values (?,?,?)"
,datas);
}
public User getUserById(Integer id){
RowMapper<User> rowMapper = new BeanPropertyRowMapper<>(User.class);
return jdbcOperations.queryForObject("select * from users where Id = ?",rowMapper,id);
}
public List<User> getUsers(){
RowMapper<User> rowMapper = new BeanPropertyRowMapper<>(User.class);
return jdbcOperations.query("select * from users",rowMapper);
}
public Long getUsersSize(){
return jdbcOperations.queryForObject("select count(Id) from users",Long.class);
}
}
(4)controller调用即可