首页 > 编程 > Java > 正文

springboot使用JdbcTemplate完成对数据库的增删改查功能

2019-11-26 10:45:58
字体:
来源:转载
供稿:网友

首先新建一个简单的数据表,通过操作这个数据表来进行演示

DROP TABLE IF EXISTS `items`; CREATE TABLE `items` (  `id` int(11) NOT NULL AUTO_INCREMENT,  `title` varchar(255) DEFAULT NULL,  `name` varchar(10) DEFAULT NULL,  `detail` varchar(255) DEFAULT NULL,  PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8; 

引入JdbcTemplate的maven依赖及连接类

<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文件配置mysql的驱动类,数据库地址,数据库账号、密码信息,application.properties新建在src/main/resource文件夹下

spring.datasource.url=jdbc:mysql://127.0.0.1:3306/spring?useSSL=false spring.datasource.username=root spring.datasource.password=123456 spring.datasource.driver-class-name=com.mysql.jdbc.Driver spring.datasource.max-idle=10 spring.datasource.max-wait=10000 spring.datasource.min-idle=5 spring.datasource.initial-size=5 server.port=8080 server.session.timeout=10 server.tomcat.uri-encoding=UTF-8 

新建一个实体类,属性对应sql字段

package org.amuxia.start; public class Items {  private Integer id;  private String title;  private String name;  private String detail;  public Integer getId() {   return id;  }  public void setId(Integer id) {   this.id = id;  }  public String getTitle() {   return title;  }  public void setTitle(String title) {   this.title = title;  }  public String getName() {   return name;  }  public void setName(String name) {   this.name = name;  }  public String getDetail() {   return detail;  }  public void setDetail(String detail) {   this.detail = detail;  }  public Items() {   super();   // TODO Auto-generated constructor stub  }  public Items(Integer id, String title, String name, String detail) {   super();   this.id = id;   this.title = title;   this.name = name;   this.detail = detail;  }  @Override  public String toString() {   return "Items [id=" + id + ", title=" + title + ", name=" + name + ", detail=" + detail + "]";  } } 

新增操作

/**   * 新增数据   * @param items   * @return   */  @RequestMapping("/add")  public @ResponseBody String addItems(Items items) {   String sql = "insert into items (id,title,name,detail) value (?,?,?,?)";   Object args[] = {items.getId(),items.getTitle(),items.getName(),items.getDetail()};   int temp = jdbcTemplate.update(sql, args);   if(temp > 0) {    return "文章新增成功";   }   return "新增出现错误";  } 

我们做一个测试。在postman测试工具中输入http://localhost:8080/items/add

我们可以看到,新增已经成功了,确实很方便,也没有繁琐的配置信息。

其余删除,更新操作与新增代码不变,只是sql的变化,这里不做演示。

全部查询操作

/**   * @return   * 查询全部信息   */  @RequestMapping("/list")  public List<Map<String, Object>> itemsList() {   String sql = "select * from items";   List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);   return list;  } 

我们做一个测试。在postman测试工具中输入http://localhost:8080/items/list

我们看到,包括刚才新增的数据,都已经被查出来了。

这里为了学习一下springboot的JdbcTemplate操作,所有增删改查代码都写在ItemsController类中,也方便演示,这里把代码贴出来,需要的可以运行一下

package org.amuxia.start; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.ComponentScan; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.bind.annotation.RestController; @ComponentScan @RestController @RequestMapping("/items") public class ItemsController {  @Autowired  private JdbcTemplate jdbcTemplate;  /**   * @return   * 查询全部信息   */  @RequestMapping("/list")  public List<Map<String, Object>> itemsList() {   String sql = "select * from items";   List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);   return list;  }  /**   * @param id   * @return   * 根据ID查询单条信息   */  @RequestMapping("/detail/{id}")  public Map<String, Object> detail(@PathVariable int id) {   Map<String, Object> map = null;   List<Map<String, Object>> list = itemsList();   map = list.get(id);   return map;  }  /**   * 新增数据   * @param items   * @return   */  @RequestMapping("/add")  public @ResponseBody String addItems(Items items) {   String sql = "insert into items (id,title,name,detail) value (?,?,?,?)";   Object args[] = {items.getId(),items.getTitle(),items.getName(),items.getDetail()};   int temp = jdbcTemplate.update(sql, args);   if(temp > 0) {    return "文章新增成功";   }   return "新增出现错误";  }  /**   * @param items   * @return   * 删除数据   */  @RequestMapping("/del")  public @ResponseBody String delItems(Items items) {   String sql = "delete from items where id = ?";   Object args[] = {items.getId()};   int temp = jdbcTemplate.update(sql, args);   if(temp > 0) {    return "文章删除成功";   }   return "删除出现错误";  }  /**   * @param items   * @return   * 更新操作   */  @RequestMapping("/upd")  public @ResponseBody String updItems(Items items) {   String sql = "update items set title = ?,detail = ? where id = ?";   Object args[] = {items.getTitle(),items.getDetail(),items.getId()};   int temp = jdbcTemplate.update(sql, args);   if(temp > 0) {    return "文章修改成功";   }   return "修改出现错误";  } } 

这里解释一个注解

@ComponentScan:

        @ComponentScan告诉Spring 哪个注解标识的类会被spring自动扫描并且装入bean容器。如果你有个类用@Controller注解标识了,那么,如果不加上@ComponentScan自动扫描该controller,那么该Controller就不会被spring扫描到,更不会装入spring容器中,Controller就不会起作用。

启动类代码

package org.amuxia.start; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.web.bind.annotation.RestController; @RestController @EnableAutoConfiguration public class App {  public static void main( String[] args )  {   System.out.println( "start....." );   SpringApplication.run(ItemsController.class, args);  } } 

总结

以上所述是小编给大家介绍的springboot使用JdbcTemplate完成对数据库的增删改查功能,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对武林网网站的支持!

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表