黑马程序员技术交流社区

标题: 【郑州校区】springboot学习(2)springboot使用JdbcTemplate完成... [打印本页]

作者: 我是色色    时间: 2018-1-2 11:44
标题: 【郑州校区】springboot学习(2)springboot使用JdbcTemplate完成...
本帖最后由 我是色色 于 2018-1-2 11:49 编辑

上一篇对springboot有一个简单的介绍以及使用一个简单的例子熟悉了一下springboot写法的简单流程。这一篇介绍springboot使用JdbcTemplate完成对数据库的增删改查。

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

  • [AppleScript] 纯文本查看 复制代码
    [sql] view plain copy
    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依赖及连接类
[AppleScript] 纯文本查看 复制代码
[html] view plain copy
<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文件夹下
[AppleScript] 纯文本查看 复制代码
[plain] view plain copy
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字段
[AppleScript] 纯文本查看 复制代码
[java] view plain copy
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 + "]";  
    }  
      
}

新增操作
[AppleScript] 纯文本查看 复制代码
[java] view plain copy
/**
     * 新增数据
     * @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的变化,这里不做演示。

全部查询操作

[AppleScript] 纯文本查看 复制代码
[java] view plain copy
/**
     * @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类中,也方便演示,这里把代码贴出来,需要的可以运行一下

  • [AppleScript] 纯文本查看 复制代码
    [mw_shl_code=applescript,true][java] view plain copy
    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 "修改出现错误";
    }
    }
    [/mw_shl_code]
这里解释一个注解
@ComponentScan:
        @ComponentScan告诉Spring 哪个注解标识的类会被spring自动扫描并且装入bean容器。如果你有个类用@Controller注解标识了,那么,如果不加上@ComponentScan自动扫描该controller,那么该Controller就不会被spring扫描到,更不会装入spring容器中,Controller就不会起作用。

启动类代码

[AppleScript] 纯文本查看 复制代码
[java] view plain copy
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);  
    }  
}  






作者: 我是色色    时间: 2018-1-2 11:49

作者: wheat    时间: 2018-1-2 13:39
现在传智都讲springboot了?真是与时俱进啊





欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) 黑马程序员IT技术论坛 X3.2