微服務(wù) SpringBoot 2.0(七):使用JdbcTemplates訪問Mysql

一切沒有與數(shù)據(jù)庫交互的網(wǎng)站都是假網(wǎng)站 —— Java面試必修

引言

在web開發(fā)服務(wù)中,開發(fā)人員要做的事情就是將數(shù)據(jù)庫中的數(shù)據(jù)返回至前端頁面,在第五章我們已經(jīng)整合了頁面,今天我們再結(jié)合數(shù)據(jù)庫做一個完整的增刪改查功能,馬上要進入數(shù)據(jù)交互了,緊不緊張

在接下來的文章中,我在末尾處會公布源碼,源碼將托管在碼云上

JdbcTemplate

工具

SpringBoot版本:2.0.4
開發(fā)工具:IDEA 2018
Maven:3.3 9
DB:mysql
JDK:1.8

依賴

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

添加上面代碼后一定要刷新依賴噢

數(shù)據(jù)源配置

在src/main/resources/application.yml中配置數(shù)據(jù)源信息。

spring.datasource:
  url: jdbc:mysql://192.168.2.211:3306/springboot?useUnicode=true&characterEncoding=utf-8
  username: root
  password: 123456
  driver-class-name: com.mysql.jdbc.Driver

spring-boot-starter-jdbc 默認使用tomcat-jdbc數(shù)據(jù)源,如果你想使用其他的數(shù)據(jù)源,比如這里使用了阿里巴巴的數(shù)據(jù)池管理,你應(yīng)該額外添加以下依賴:

<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.5</version>
</dependency>

初始化mysql

-- create table `website_jdbc`
CREATE TABLE `website_jdbc` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) NOT NULL,
  `url` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;
INSERT INTO `website_jdbc` VALUES (1,'Java面試必修', 'www.itmsbx.com');
INSERT INTO `website_jdbc` VALUES (2,'對象無憂', 'www.51object.com');
INSERT INTO `website_jdbc` VALUES (3,'上海恒驪信息科技', 'www.henliy.com');
INSERT INTO `website_jdbc` VALUES (4 , '淘寶網(wǎng)', 'www.taobao.com');

編寫B(tài)ean,Service,Dao

bean
public class WebSiteBean {

    //省略 getter 和 setter
    private Long id;
    private String name;
    private String url;

}
service
public interface WebSiteService {

    int add(WebSiteBean webSiteBean);

    int update(WebSiteBean webSiteBean);

    int deleteByIds(String ids);

    List<WebSiteBean> queryWebSiteList(Map<String,Object> params);
}

@Service
public class WebSiteServiceImpl implements WebSiteService {

    @Autowired
    private WebSiteDao webSiteDao;

    @Override
    public int add(WebSiteBean webSiteBean) {
        return webSiteDao.add(webSiteBean);
    }

    @Override
    public int update(WebSiteBean webSiteBean) {
        return webSiteDao.update(webSiteBean);
    }

    @Override
    public int deleteByIds(String ids) {
        return webSiteDao.deleteByIds(ids);
    }

    @Override
    public List<WebSiteBean> queryWebSiteList(Map<String, Object> params) {
        return webSiteDao.queryWebSiteList(params);
    }
}
dao
public interface WebSiteDao {

    int add(WebSiteBean webSiteBean);

    int update(WebSiteBean webSiteBean);

    int deleteByIds(String ids);

    List<WebSiteBean> queryWebSiteList(Map<String,Object> params);
}


@Repository
public class WebSiteDaoImpl implements WebSiteDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public int add(WebSiteBean webSiteBean) {
        return jdbcTemplate.update("insert into website_jdbc(name,url) values(?, ?)"
                ,webSiteBean.getName(),webSiteBean.getUrl());
    }

    @Override
    public int update(WebSiteBean webSiteBean) {
        return jdbcTemplate.update("update website_jdbc set name=?,url where id = ?",
                new Object[]{webSiteBean.getName(),webSiteBean.getUrl(),webSiteBean.getId()});
    }

    @Override
    public int deleteByIds(String ids) {
        return jdbcTemplate.update("delete from website_jdbc  where id in(" + ids + ")");
    }

    @Override
    public List<WebSiteBean> queryWebSiteList(Map<String, Object> params) {
        StringBuffer sql =new StringBuffer();
        sql.append("select * from website_jdbc where 1=1");
        if(params.containsKey("name")){
            sql.append(" and name like '%").append(String.valueOf(params.get("name"))).append("%'");
        }
        if(params.containsKey("url")){
            sql.append(" and url like '%").append((String)params.get("url")).append("%'");
        }
        List<WebSiteBean> list = jdbcTemplate.query(sql.toString() , new BeanPropertyRowMapper(WebSiteBean.class));
        return list;
    }
}

Dao實現(xiàn)類,這里注入我們需要的JdbcTemplate,然后通過JdbcTemplate提供的接口進行增刪查該的操作,這里我就寫幾個簡單的,更多可以自行查看JdbcTemplate提供的api

編寫Controller

@Controller
@RequestMapping("/jdbc")
public class WebSiteController {

    @Autowired
    private WebSiteService websiteService;

    @RequestMapping("query")
    public ModelAndView query(){
        Map<String,Object> params = new HashMap<>();
        params.put("name","Java面試必修");
        List<WebSiteBean> webSiteBeans = websiteService.queryWebSiteList(params);
        ModelAndView mav = new ModelAndView("/list");
        mav.addObject("webSiteBeans",webSiteBeans);
        mav.addObject("hint","想學(xué)習(xí)更多面試技巧和知識,請關(guān)注公眾號:Java面試必修(itmsbx)");
        return mav;
    }
}

更改Application

@SpringBootApplication
public class DemoJdbcApplication {

    @Autowired
    private Environment env;

    //destroy-method="close"的作用是當數(shù)據(jù)庫連接不使用的時候,就把該連接重新放到數(shù)據(jù)池中,方便下次使用調(diào)用.
    @Bean(destroyMethod =  "close")
    public DataSource dataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(env.getProperty("spring.datasource.url"));
        dataSource.setUsername(env.getProperty("spring.datasource.username"));//用戶名
        dataSource.setPassword(env.getProperty("spring.datasource.password"));//密碼
        dataSource.setDriverClassName(env.getProperty("spring.datasource.driver-class-name"));
        dataSource.setInitialSize(2);//初始化時建立物理連接的個數(shù)
        dataSource.setMaxActive(20);//最大連接池數(shù)量
        dataSource.setMinIdle(0);//最小連接池數(shù)量
        dataSource.setMaxWait(60000);//獲取連接時最大等待時間,單位毫秒。
        dataSource.setValidationQuery("SELECT 1");//用來檢測連接是否有效的sql
        dataSource.setTestOnBorrow(false);//申請連接時執(zhí)行validationQuery檢測連接是否有效
        dataSource.setTestWhileIdle(true);//建議配置為true,不影響性能,并且保證安全性。
        dataSource.setPoolPreparedStatements(false);//是否緩存preparedStatement,也就是PSCache
        return dataSource;
    }

    public static void main(String[] args) {
        SpringApplication.run(DemoJdbcApplication.class, args);
    }
}

到這里啟動服務(wù)器,瀏覽器輸入http://localhost:8080/jdbc/query 看看效果吧

總結(jié)

本章講解了使用JdbcTemplates訪問Mysql數(shù)據(jù)庫,實現(xiàn)了數(shù)據(jù)交互,看上去是不是還是很簡單呢?不過光是JdbcTemplates還是不夠的,畢竟咱們還是要深入企業(yè)主流框架,下一章我將帶大家整合Mybatis框架,后面的源代碼將整合一個開源的網(wǎng)站來進行講解,學(xué)完這些框架之后,你也能收獲一個自己動手的網(wǎng)站,一舉多得是不是很有動力

源碼地址:

https://gitee.com/rjj1/SpringBootNote/tree/master/demo-jdbc


作者有話說:喜歡的話就請移步Java面試必修網(wǎng),請自備水,更多干、干、干貨等著你

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容