使用JDBC對 MySQL資料庫進行操作
1.application.properties加入
spring.datasource.url=jdbc:mysql://127.0.0.1:3306/liongogo?useUnicode=true&characterEncoding=utf-8
spring.datasource.username=root
spring.datasource.password=xxxxxx
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.http.encoding.force=true
2.pom.xml加入依賴
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.33</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
3.資料庫新增表結構
CREATE TABLE IF NOT EXISTS user
(
id VARCHAR(32) NOT NULL COMMENT '代號',
user_name VARCHAR(200) COMMENT '名稱',
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
4.增加domian物件
package com.liongogo.domain;
import org.springframework.stereotype.Component;
@Component
public class User {
private String id;
private String userName;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
5.增加DAO
package com.liongogo.repository;
import com.liongogo.domain.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;
@Repository
public class UserDao {
@Autowired
private JdbcTemplate jdbcTemplate;
public void addUser(User pUser){
jdbcTemplate.update("INSERT INTO user(id, user_name) "
+ "VALUES (?,?)", pUser.getId(), pUser.getUserName());
}
}
6.增加Service
package com.liongogo.service;
import com.liongogo.domain.User;
import com.liongogo.repository.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Autowired
UserDao userDao;
public void addUser(User pUser){
userDao.addUser(pUser);
}
}
7.服務接口調用測試
package com.liongogo.controller;
import com.liongogo.domain.User;
import com.liongogo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class UserController {
@Autowired
UserService userService;
@RequestMapping("/users/add")
public String addUser() {
User tUser = new User();
tUser.setId("001");
tUser.setUserName("我是001");
userService.addUser(tUser);
return "OK";
}
}