一切沒有與數(shù)據(jù)庫交互的網(wǎng)站都是假網(wǎng)站 —— Java面試必修
引言
在web開發(fā)服務(wù)中率触,開發(fā)人員要做的事情就是將數(shù)據(jù)庫中的數(shù)據(jù)返回至前端頁面,在第五章我們已經(jīng)整合了頁面汇竭,今天我們再結(jié)合數(shù)據(jù)庫做一個(gè)完整的增刪改查功能葱蝗,馬上要進(jìn)入數(shù)據(jù)交互了,緊不緊張
在接下來的文章中细燎,我在末尾處會(huì)公布源碼两曼,源碼將托管在碼云上
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 默認(rèn)使用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實(shí)現(xiàn)類,這里注入我們需要的JdbcTemplate户辫,然后通過JdbcTemplate提供的接口進(jìn)行增刪查該的操作,這里我就寫幾個(gè)簡單的嗤锉,更多可以自行查看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í)更多面試技巧和知識(shí)渔欢,請關(guān)注公眾號:Java面試必修(itmsbx)");
return mav;
}
}
更改Application
@SpringBootApplication
public class DemoJdbcApplication {
@Autowired
private Environment env;
//destroy-method="close"的作用是當(dāng)數(shù)據(jù)庫連接不使用的時(shí)候,就把該連接重新放到數(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í)建立物理連接的個(gè)數(shù)
dataSource.setMaxActive(20);//最大連接池?cái)?shù)量
dataSource.setMinIdle(0);//最小連接池?cái)?shù)量
dataSource.setMaxWait(60000);//獲取連接時(shí)最大等待時(shí)間,單位毫秒档冬。
dataSource.setValidationQuery("SELECT 1");//用來檢測連接是否有效的sql
dataSource.setTestOnBorrow(false);//申請連接時(shí)執(zhí)行validationQuery檢測連接是否有效
dataSource.setTestWhileIdle(true);//建議配置為true膘茎,不影響性能桃纯,并且保證安全性。
dataSource.setPoolPreparedStatements(false);//是否緩存preparedStatement披坏,也就是PSCache
return dataSource;
}
public static void main(String[] args) {
SpringApplication.run(DemoJdbcApplication.class, args);
}
}
到這里啟動(dòng)服務(wù)器态坦,瀏覽器輸入http://localhost:8080/jdbc/query 看看效果吧
總結(jié)
本章講解了使用JdbcTemplates訪問Mysql數(shù)據(jù)庫,實(shí)現(xiàn)了數(shù)據(jù)交互棒拂,看上去是不是還是很簡單呢伞梯?不過光是JdbcTemplates還是不夠的,畢竟咱們還是要深入企業(yè)主流框架帚屉,下一章我將帶大家整合Mybatis框架谜诫,后面的源代碼將整合一個(gè)開源的網(wǎng)站來進(jìn)行講解,學(xué)完這些框架之后攻旦,你也能收獲一個(gè)自己動(dòng)手的網(wǎng)站喻旷,一舉多得是不是很有動(dòng)力
源碼地址:
https://gitee.com/rjj1/SpringBootNote/tree/master/demo-jdbc
作者有話說:喜歡的話就請移步Java面試必修網(wǎng),請自備水牢屋,更多干且预、干、干貨等著你