编写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);
}
}
测试