我對模式的概念很陌生。我正在練習依賴注入技能以及使用DAO原則。我編寫的代碼很有用,但我覺得它可以用更優雅的方式編寫。我已經嘗試重組它,我看到一個模式,但是那些複雜的事情,所以不知道我是否正確實施它。作爲Web應用程序與數據庫通信並拋出結果的一般規則,應該如何構造其項目? 我聽說過MVC原理,但並不一定會將數據庫添加到組合中。如何構造與數據庫通信的控制器
這是我到目前爲止有:
一個在Controller
包包含控制器類:
@RestController
public class ResponseController {
@Autowired
MongoBase dbConnection;
@RequestMapping(value = "/jsonresult", method = RequestMethod.GET)
@ResponseBody
public String jsonresult(@RequestParam(value = "id", required = true) String id){
return dbConnection.documentToJSON(id, Constants.database,Constants.collection);
}
@RequestMapping(value = "/alljsonresult", method = RequestMethod.GET)
@ResponseBody
public String alljsonresult(){
return dbConnection.allDocumentToJSON(Constants.database,Constants.collection);
}}
一個包含CRUD方法到數據庫中Database
包裝類:
@Component
public class MongoBase {
@Autowired
MongoClient mongoClient;
public MongoBase() {
try {
mongoClient = new MongoClient("localhost", 27017);
} catch (Exception e) {
e.printStackTrace();
}
}
public void printAllCollection(String databaseName, String collectionName) {
...
}
那麼有沒有更好的方法/更有效的寫作方式?此外,我覺得在Monogbase
類我還沒有完全實現DI,因爲它包含了new
關鍵詞..
Spring的數據推薦非常出色。 Spring Boot是要走的路。 – duffymo