SpringBoot之整合 jdbcTemplate

jdbcTemplate 就是类似一个 BASEDAO,很方便,因为最原生,所以效率最高。也最麻烦。

1.导入  spring-boot-starter-jdbc,mysql,spring boot web启动器

        
        
            org.springframework.boot
            spring-boot-starter-jdbc
        
        
        
            mysql
            mysql-connector-java
        
        
        
            org.springframework.boot
            spring-boot-starter-web
        

2.编写实体。

public class Userinfo {
    private String uid;

    private String username;

    private String pwd;

    private String userimg;

    ...省略getset
}

建表语句:

DROP TABLE IF EXISTS `userinfo`;
CREATE TABLE `userinfo` (
  `uid` varchar(255) NOT NULL,
  `username` varchar(255) DEFAULT NULL,
  `pwd` varchar(255) DEFAULT NULL,
  `userimg` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

3.application.yml配置

spring:
  datasource:
    url: jdbc:mysql://127.0.0.1:3306/zhangzq?useUnicode=true&characterEncoding=utf-8&useSSL=false&useLegacyDatetimeCode=false&serverTimezone=Hongkong&zeroDateTimeBehavior=convertToNull
    username: root
    password: root
server:
  port: 1219

4.编写控制器,在这里我就直接在控制器里面放sql了,记录下,以后用看一下就想的起来

@Controller
public class BaseController {

    private final JdbcTemplate jdbcTemplate;

    @Autowired
    public BaseController(JdbcTemplate jdbcTemplate){
        this.jdbcTemplate = jdbcTemplate;
    }

    @RequestMapping("/query")
    @ResponseBody
    public Object save(){
        String sql = "select * from userinfo ";
        List list = this.jdbcTemplate.query(sql, new Object[]{}, new BeanPropertyRowMapper<>(Userinfo.class));

        return list;
    }
}

5.启动类

@SpringBootApplication
public class Application {

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

}

6.运行效果

SpringBoot之整合 jdbcTemplate_第1张图片

你可能感兴趣的:(springboot,SpringBoot菜鸟教程)