幾句簡單代碼解決springboot整合JdbcTemplate訪問數據庫進行操作

這篇文章我們看一下springboot整合jdbc,做一個小例子來講解。

數據源配置

pom.xml文件中導入

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring‐boot‐starter‐jdbc</artifactId>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql‐connector‐java</artifactId>
    <scope>runtime</scope>
</dependency>

然後在application.properties中配置數據庫信息:

spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=0911SIHAI
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

使用JdbcTemplate操作數據庫

這裏我們以user進行對數據庫的操作,做一個小例子

user代碼:

/**
 * @author 
 * @date 2018/7/26 16:09
 */
public class User {


    private String username;

    private String password;

    //getter setter
}
  • 定義包含有插入、刪除、查詢的抽象接口UserService
/**
 * @author 
 * @date 2018/7/26 16:07
 */
public interface UserService {

    /**
     * 新增用戶
     * @param username
     * @param password
     */
    void add(String username, String password);

    /**
     * 根據name刪除一個用戶高
     * @param userName
     */
    void deleteByName(String userName);

    /**
     * 獲取所有用戶
     */
    List<User> getAllUsers();


}
  • 通過JdbcTemplate實現UserService中定義的數據訪問操作
/**
 * @author 
 * @date 2018/7/26 16:11
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public void add(String username, String password) {
        jdbcTemplate.update("insert into user values (?,?)",username,password);
    }

    @Override
    public void deleteByName(String userName) {
        jdbcTemplate.update("delete from user where username = ?",userName);
    }

    @Override
    public List<User> getAllUsers() {
        return jdbcTemplate.query("select * from user",
                new RowMapper(){
                    @Override
                    public Object mapRow(ResultSet rs, int rowNum) throws SQLException {
                        User user  = new User();
                        user.setUsername(rs.getString("username"));
                        user.setPassword(rs.getString("password"));
                        return user;
                    }
        } );
    }
}
  • 對用戶操作進行測試
/**
 * @author 
 * @date 2018/7/26 16:22
 */
@RunWith(SpringRunner.class)
@SpringBootTest
public class UserTest {

    @Autowired
    private UserService userService;

    @Test
    public void testAdd(){

        userService.add("sihai","abc");
        userService.add("yan","abc");
    }

    @Test
    public void testQuery(){

        List<User> users = userService.getAllUsers();

        Assert.assertEquals(2, users.size());
    }
}

這裏只是一個簡單的例子,但是基本的jdbc的操作是有了,具體的jdbcTemplate的使用可以查看

https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/jdbc/core/JdbcTemplate.html

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章