springboot连接mysql数据库——jdbc

编写application.yml文件

server:
  port: 5001

spring:
  application:
    name: config-server
  profiles:
    active: jdbc

  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/ordertest?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
    username: root
    password: root

pom文件

        <!--连接数据库相关的jar包-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>

        <dependency>
            <groupId>io.mateu</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

启动类

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

}

Entity层

@Getter
@Setter
public class Student {
    private int id;
    private String name;
}

Dao层

public interface StudentDao {
    public String getUserNameById(int id);
}
@Repository
public class StudentDaoImpl implements StudentDao {
	// 用Autowired也行
	// @Resource的作用和@Autowired一样,只不过@Autowired是按byType自动注入,而@Resource默认按byName自动注入
    @Resource
    private JdbcTemplate jdbcTemplate;


    @Override
    public String getUserNameById(int id) {
        return jdbcTemplate.queryForObject("select name from student where id=? ", String.class);
    }

}

Service层

public interface StudentService {
    public String getUserNameById(int id);
}
@Service
public class StudentServiceImpl implements StudentService {
    @Resource
    private StudentDao studentDao;

    @Override
    public String getUserNameById(int id) {
        return studentDao.getUserNameById(id);

    }
}

Controller层

@RestController
@RequestMapping("/mydb")
public class StudentController {

    @Resource
    private StudentService studentService;

    @GetMapping("/hello")
    public String getUserNameById(int id){
        return studentService.getUserNameById(id);
    }

}

测试
在这里插入图片描述

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值