pom依赖:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.10</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> <version>8.0.17</version> </dependency> 复制代码
链接配置:
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource spring.datasource.username=root spring.datasource.password=12345678 spring.datasource.url=jdbc:mysql://localhost:3306/spoon 复制代码
Service操作:
@Service public class UserService { @Autowired JdbcTemplate jdbcTemplate; public Integer addUser(User user) { System.out.println("addUser"); return jdbcTemplate.update("insert into user (name , address) values (?, ?)", user.getName(), user.getAddress()); } public Integer updateUsernameById(User user){ System.out.println("updateUsernameById"); return jdbcTemplate.update("update user set name = ? where id = ?", user.getName(), user.getId()); } public Integer deleteUserById(Integer id){ System.out.println("deleteUserById"); return jdbcTemplate.update("delete from user where id = ?", id); } public List<User> getAllUsers(){ return jdbcTemplate.query("select * from user", new RowMapper<User>() { @Override public User mapRow(ResultSet resultSet, int i) throws SQLException { User user = new User(); user.setId(resultSet.getInt("id")); user.setName(resultSet.getString("name")); user.setAddress(resultSet.getString("address")); return user; } }); } public List<User> getAllUsers2(){ return jdbcTemplate.query("select * from user", new BeanPropertyRowMapper<>(User.class)); } } 复制代码
Test:
@SpringBootTest class DemoApplicationTests { @Autowired UserService userService; @Test void contextLoads() { User user = new User(); user.setName("zhangxin"); user.setAddress("www.n22.online"); userService.addUser(user); } @Test void test1(){ User user = new User(); user.setId(1); user.setName("zhangsanjin"); userService.updateUsernameById(user); } @Test void test2(){ userService.deleteUserById(1); } @Test void test3(){ System.out.println(userService.getAllUsers()); } @Test void test4(){ System.out.println(userService.getAllUsers2()); } }