三層式架構在開發中具有許多優點,有助於實現模塊化,提高可維護性、重用性與安全性等,使開發者更容易管理、測試和擴展應用程序。三層式架構模式分為三個主要層次:
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Entity
@Table(name = "_hello")
public class HelloEntity {
@Id
@GeneratedValue
private Long id;
private String title;
private String message;
}
@RestController
@RequiredArgsConstructor
@RequestMapping("/api")
public class HelloController {
private final HelloService service;
@PostMapping("/hello")
@Operation(summary = "新增Hello資料")
public ResponseEntity<?> addHello(
@RequestParam("title") String title,
@RequestParam("message")String message
) {
return ResponseEntity.ok(service.addHello(title,message));
}
@GetMapping("/hello")
public List<HelloEntity> getAllHello(){
return service.getAllHello();
}
}
@Service
@AllArgsConstructor
public class HelloService {
private final HelloRepository helloRepository;
public Map<String, Object> addHello(String title, String messge) {
var response = new LinkedHashMap<String, Object>();
var helloData = HelloEntity
.builder()
.title(title)
.message(messge)
.build();
helloRepository.save(helloData);
response.put("status", "0");
return response;
}
public List<HelloEntity> getAllHello() {
var HelloList = helloRepository.findAllHello();
return HelloList;
}
}
@Repository
public interface HelloRepository extends JpaRepository<HelloEntity, Long> {
@Query("SELECT h FROM HelloEntity h")
List<HelloEntity> findAllHello();
}