鐵人賽
Templates
先看一下這張圖,介紹一下架構
controller不會直接跟model交互,而是中間透過一層service操控
而service layer透過di 叫一層repository class進來
DI如果有問題可以看前面的文章有介紹
然後中間有一個jpa/spring data標示
jpa / jdbc的關係可以看這張圖
ok!那就開始吧
回顧一下上一篇我們創好了model
而這個其實就是Spring Data JPA做orm持久層的實現
pom.xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
@Entity(name = "usertable")
public class UserModel {
@Column(name="id")
private Integer id;
@Column(name="username")
private String username;
@Column(name="password")
private String password;
@Column(name="email")
private String email;
public UserModel(){
}
public UserModel(Integer id, String username, String password, String email) {
this.id = id;
this.username = username;
this.password = password;
this.email = email;
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
public Integer getId(){
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
接下來我們照上面那張圖創 repository吧
這個是一個interface主要是用來對應資料庫操作
而crud基本上都是內建的,如果要用甚麼操作像找特定欄位可以像這樣使用
findBy欄位名,也可以下SQL語法 ex @Query("sql語法")
基本上用JpaRepository 參數第一個是放連到的model,第二個是他的主鍵key格式
@Repository
public interface UserRepository extends JpaRepository<UserModel,Integer> {
UserModel findByUsername(String username);
}
接下來在service層用DI注入,而delete,save等等是本來就有的,
接下來在service標注好方法,就可以在controller使用了
@Service
@Transactional
public class UserService {
@Autowired
private UserRepository userRepository;
public List<UserModel> listUserAll(){
return userRepository.findAll();
}
public void saveUser(UserModel userModel){
userRepository.save(userModel);
}
public UserModel findUserById(Integer id){
return userRepository.findById(id).get();
}
public UserModel findByUsername(String usrName){
return userRepository.findByUsername(usrName);
}
public void deleteById(Integer id){
userRepository.deleteById(id);
}
}
controller的部分標注是@RestController,與@Controller的差異為
@Controller他會認為你回傳的是畫面 (jsp,thymleaf等等)
而@RestController認為你回傳的是資料 (預設是json格式)
@RestController
public class UsersController {
@Autowired
private UserService service;...}
** mapping方式差別
@RequestMapping(method = RequestMethod.GET) = @GetMapping()
為get方法
@RequestMapping(method = RequestMethod.POST) = @PostMapping()
為post方法
@PutMapping 為updatez方法
@DeleteMapping為delete方法
1.列出所有的資料,回傳值為list
@GetMapping("/users")
public List<UserModel> fetchUserList(){
return service.listUserAll();
}
2.create資料,傳入資料庫
@PostMapping("/users")
public void add(@RequestBody UserModel user) {
service.saveUser(user);
}
3.delete資料,根據id去delete資料
@DeleteMapping("/users/{id}")
public void delete(@PathVariable Integer id) {
service.deleteById(id);
}
4.update資料
@PutMapping("/users/{id}")
public ResponseEntity<?> update(@RequestBody UserModel putuser, @PathVariable Integer id) {
try {
UserModel userModel = service.findUserById(id);
userModel.setEmail(putuser.getEmail());
userModel.setPassword(putuser.getPassword());
userModel.setUsername(putuser.getUsername());
service.saveUser(userModel);
return new ResponseEntity<>(HttpStatus.OK);
} catch (NoSuchElementException e) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
}
5.find特定id的資料,PathVariable是讓他在path傳入
ex:/users/1 就是找id為1的資料
@GetMapping("/users/{id}")
public ResponseEntity<UserModel> get(@PathVariable(required = false) Integer id) {
try {
UserModel product = service.findUserById(id);
return new ResponseEntity<UserModel>(product, HttpStatus.OK);
} catch (NoSuchElementException e) {
return new ResponseEntity<UserModel>(HttpStatus.NOT_FOUND);
}
}