1. 程式人生 > 實用技巧 >SpringBoot - 08整合JDBC

SpringBoot - 08整合JDBC

SpringBoot - 08整合JDBC

(1)搭建專案環境

(1.1)修改POM檔案

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.43</version>
        </dependency>
        <dependency>
            <
groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.1.19</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</
artifactId> </dependency>

(2)配置資料來源

(2.1)通過自定義配置檔案方式配置資料來源資訊

  • 通過@PropertySource註解讀取配置檔案,使用Druid連線池
@Configuration     // 資料來源的JDBC配置類
@PropertySource("classpath:/jdbc.properties") // 載入指定的Properties配置檔案
public class JdbcConfiguration {
@Value(
"${jdbc.driverClassName}") private
String driverClassName; @Value("${jdbc.url}") private String url; @Value("${jdbc.username}") private String username; @Value("${jdbc.password}") private String password; // 例項化Druid @Bean public DataSource getDataSource(){ DruidDataSource source = new DruidDataSource(); source.setDriverClassName(this.driverClassName); source.setUrl(this.url); source.setUsername(this.username); source.setPassword(this.password); return source; } }

測試

    @Autowired
    private DataSource dataSource;

    @RequestMapping("/showInfo")
    public String showInfo(){
        System.out.println(this.dataSource.getClass().getPackage());
        return "ok";
    }
package com.alibaba.druid.pool

(2.2)通過@ConfigurationProperties註解讀取配置資訊

// 是SpringBoot的註解不能讀取其他配置,只能讀取SpringBoot配置application.properties
@ConfigurationProperties(prefix = "jdbc")
public class JdbcProperties {

    private String driverClassName;
    private String url;
    private String username;
    private String password;
    // 省略其他程式碼
}
@Configuration
//@PropertySource("classpath:/jdbc.properties")
@EnableConfigurationProperties(JdbcProperties.class) // 指定載入哪個配置資訊屬性類
public class JdbcConfiguration {

    @Autowired
    private JdbcProperties jdbcProperties;
    
    @Bean
    public DataSource getDataSource(){
        DruidDataSource source = new DruidDataSource();
        source.setDriverClassName(this.jdbcProperties.getDriverClassName());
        source.setUrl(this.jdbcProperties.getUrl());
        source.setUsername(this.jdbcProperties.getUrl());
        source.setPassword(this.jdbcProperties.getPassword());
        return source;
    }
}
//    @Autowired
    private JdbcProperties jdbcProperties;
    
    public JdbcConfiguration(JdbcProperties jdbcProperties){
        this.jdbcProperties = jdbcProperties;
    }

(2.3)使用@ConfigurationProperties註解的優雅使用方式

@Configuration  
public class JdbcConfiguration {

    @Bean
    @ConfigurationProperties(prefix = "jdbc")  //不需要其他類
    public DataSource getDataSource(){
        DruidDataSource source = new DruidDataSource();
        return source;
    }
}

(2.4)使用SpringBoot配置檔案配置資料來源

在SpringBoot 1.x版本中spring-boot-starter-jdbc啟動器中預設使用的資料來源是org.apache.tomcat.jdbc.pool.DataSource 在SpringBoot 2.x版本中spring-boot-starter-jdbc啟動器中預設使用的資料來源是com.zaxxer.hikariDataSource
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/dev?useUnicode=true
spring.datasource.username=root
spring.datasource.password=root
#spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
package com.zaxxer.hikari

(3)使用者功能測試

(3.1)編寫UserDao實現類

@Component
public class UsersDaoImpl implements UsersDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    @Transactional
    public void insertUsers(Users users) {
        String sql = "insert into users(username, usersex) values(?,?)";
        this.jdbcTemplate.update(sql,users.getUsername(),users.getUsersex());
    }

    @Override
    public List<Users> selectUsersAll() {
        String sql = "select * from users";
        return this.jdbcTemplate.query(sql, new RowMapper<Users>() {
            @Override
            public Users mapRow(ResultSet resultSet, int i) throws SQLException{
                Users users = new Users();
                users.setUserid(resultSet.getInt("userid"));
                users.setUsername(resultSet.getString("username"));
                users.setUsersex(resultSet.getString("usersex"));
                return users;
            }
        });
    }

    @Override
    public Users selectUserById(Integer id) {
        String sql = "select * from users where userid = ?";
        Object[] agr = new Object[]{id};
        Users users = new Users();
        this.jdbcTemplate.query(sql, agr, new RowCallbackHandler() {
            @Override
            public void processRow(ResultSet resultSet) throws SQLException {
                users.setUserid(resultSet.getInt("userid"));
                users.setUsername(resultSet.getString("username"));
                users.setUsersex(resultSet.getString("usersex"));
            }
        });
        return users;
    }

    @Override
    public void updateUsers(Users users) {
        String sql = "update users set username=?,usersex=? where userid = ?";
        this.jdbcTemplate.update(sql, users.getUsername(), users.getUsersex(), users.getUserid());
    }

    @Override
    public void deleteUserById(Integer id) {
        String sql = "delete from users where userid = ?";
        this.jdbcTemplate.update(sql,id);
    }
}

(3.2)編寫UserService實現類

public class UserServiceImpl implements UserService {

    @Autowired
    private UsersDao usersDao;

    @Override
    public void addUser(Users users) {  usersDao.insertUsers(users); }

    @Override
    public List<Users> selectUsersAll() {  return usersDao.selectUsersAll(); }

    @Override
    public Users findUserById(Integer id) { return usersDao.selectUserById(id); }

    @Override
    @Transactional
    public void modifyUser(Users users) {  this.usersDao.updateUsers(users); }

    @Override
    @Transactional
    public void dropUser(Integer id){  this.usersDao.deleteUserById(id); }
}

(3.3)頁面跳轉

@Controller
public class PageController {

    @RequestMapping("/{page}")
    public String showPage(@PathVariable String page){
        System.out.println(page);
        return page;
    }
}

(3.4)新增使用者

templates/addUsers.html

<html xmlns:th="http://www.thymeleaf.org">
<head>
    <title>新增使用者</title>
</head>
<body>
    <form th:action="@{/user/addUser}" method="post">
        <input type="text" name="username"><br/>
        <input type="text" name="usersex"><br/>
        <input type="submit" value="OK">
    </form>
</body>
</html>
    @Autowired
    private UserService userService;

    @PostMapping("/addUser")
    public String addUsers(Users users){
        try{
            this.userService.addUser(users);
        }catch (Exception e){
            e.printStackTrace();
            return "error";
        }
        return "ok";  // return "redirect:/ok"
    }

redirect:/ok

(3.5)新增favicon.ico

在/static目錄下新增favicon.ico檔案

<link rel="shortcut icon" href="../resources/favicon.ico" th:href="@{/static/favicon.ico}">

(3.6)查詢使用者

templates/showUsers.html

<body>
    <table border="1px">
        <tr>
            <th>使用者ID</th>
            <th>使用者姓名</th>
            <th>使用者性別</th>
            <th>操作</th>
        </tr>
        <tr th:each="u: ${list}">
            <td th:text="${u.userid}"></td>
            <td th:text="${u.username}"></td>
            <td th:text="${u.usersex}"></td>
            <td>
                <a th:href="@{/user/preUpdateUser(id=${u.userid})}">修改</a>
                <a th:href="@{/user/deleteUser(id=${u.userid})}">刪除</a>
            </td>
        </tr>
    </table>
    <a href="/addUsers">新增使用者</a>

</body>
    @RequestMapping("/showUsers")
    public String findUserAll(Model model){
        List<Users> list = null;
        try{
            list = this.userService.selectUsersAll();
            model.addAttribute("list", list);
            System.out.println(list);
        }catch (Exception e){
            e.printStackTrace();
            return "error";
        }
        return "showUsers";
    }

(3.7)更新使用者

<body>
    <form th:action="@{/user/updateUser}" method="post">
        <input type="hidden" name="userid" th:value="${user.userid}">
        <input type="text" name="username" th:value="${user.username}"><br/>
        <input type="text" name="usersex" th:value="${user.usersex}"><br/>
        <input type="submit" value="OK">
    </form>
</body>
  @RequestMapping("/preUpdateUser")
    public String preUpdateUser(Integer id, Model model){
        try{
            Users users = this.userService.findUserById(id);
            model.addAttribute("user",users);
            System.out.println(users);
        }catch (Exception e){
            e.printStackTrace();
            return "error";
        }
        return "updateUsers";
    }

    @RequestMapping("/updateUser")
    public String updateUser(Users users){
        try{
            this.userService.modifyUser(users);
        }catch (Exception e){
            e.printStackTrace();
            return "error";
        }
        return "redirect:/ok";
    }

(3.8)刪除使用者

    @RequestMapping("/deleteUser")
    public String updateUser(Integer id){
        try{
            this.userService.dropUser(id);
        }catch (Exception e){
            e.printStackTrace();
            return "error";
        }
        return "redirect:/ok";
    }