springboot連線mysql資料庫——jdbc
阿新 • • 發佈:2021-02-16
編寫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);
}
}
測試