簡體   English   中英

執行其他控制器方法的JPA.withTransaction方法錯誤:Global.java:39:錯誤:此處不允許使用“無效”類型

[英]JPA.withTransaction executing other controllers method error: Global.java:39: error: 'void' type not allowed here

我試圖在某些時間間隔執行一些數據庫插入/更新查詢。

為此,我決定使用Akka Actor系統中內置的Playframework。

我上課有方法:

public class Global extends GlobalSettings {
    @Override
    public void onStart(Application application) {
        Akka.system().scheduler().schedule(
             Duration.create(1, TimeUnit.SECONDS), // start task delay
             Duration.create(24, TimeUnit.HOURS), // between task instance delay
             //Duration.create(24, TimeUnit.HOURS), // between task instance delay
                  new Runnable() {
                      @Override
                      public void run() {
                        JPA.withTransaction(
                            ImportCrmData.start()
                        );
                      }
                  },
                  Akka.system().dispatcher()
        );

以及actor系統調用的方法:

public class ImportCrmData extends Controller {
    @Transactional
    public static void start() {
        List<Customer> customersToUpdate = CustomerCRM.importCrmData();
        for(Customer c: customersToUpdate) {
            c.toDataBase();
        }
    }
}

我在編譯時遇到錯誤:

[error] app/modules/common/app/Global.java:39: error: 'void' type not allowed here ImportCrmData.start()

我知道發生此問題是因為JPA.withTransaction()要求我從ImportCrmData.start()返回Callback0Function0<> ,但我不知道該怎么做。

我的方法就是這樣做this.persist 我為什么還要從中退回一些東西?

ImportCrmData是一個控制器,因此它必須返回有效的http響應(結果)。 典型的用例:

public class CustomerController extends Controller {

    public static Result getCustomers() {
        List<Customer> customers = CustomerService.getCustomers();
        return ok(Json.toJson(customers));
    }

}

上面的示例由控制器組成,該控制器是您應用程序的入口點,並響應客戶端請求。 CustomerService封裝了與獲取客戶有關的邏輯。 ok(...)返回Result的實現-一個有效的http響應,代碼為200,在上述情況下為json主體。 它在Controller基類中實現。 接下來,您的控制器可以在routes文件中映射到如下網址:

GET /customers controller.CustomerController.getCustomers

應用以上pattern您應該具有:

  • CrmController-入口點
  • CrmService-實際業務邏輯

這種分離允許在Global類以及Controller層中使用CrmService ,而無需重復邏輯。 注意,這只是一個建議。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM