簡體   English   中英

在保存數據庫后,是否真的需要從事務中返回保存的實體?

[英]Is it really necessary to return saved Entity from transaction after DB save?

當您將對象保存到數據庫時,我知道應該:

DogEntity savedDogEntity = repository.save(dogEntityToSave);

因為保存過程可能會返回null權限? 錯誤?

服務

public interface RecipeService {

    List<Recipe> getAllRecipes();
    Recipe addRecipeToInMemList(Recipe recipe);
    Recipe initNewRecipe();
    RecipeEntity addRecipeToDb(final RecipeEntity recipe);
    void delete(final Recipe recipe);
    String generateId();

}

ServiceImpl

@Override
public Recipe addRecipeToInMemList(Recipe newRecipe){

    getAllRecipes().add(newRecipe); // Add to in memory list
}


// Save a recipe and log
@Override
public RecipeEntity addRecipeToDb(RecipeEntity recipeToSave) {



    log.info("Saved recipe with ID: " + savedRecipe.getRecipeId());

    return recipeRepository.save(recipeToSave);
}


// == Create new blank Recipe and save to DB and memory ==
public Recipe initNewRecipe(){

    // Create a new recipe, init it's ingredient list
    Recipe newRecipe = new Recipe();

    Ingredient newIngredient = new Ingredient(
            0,
            0.0,
            Unit.CUPS,
            ""
    );

    newRecipe.setIngredientList(newIngredient);

    addRecipeToInMemList(newRecipe);    // Save it to List

            // Save it to DB and return the result
    RecipeEntity newRecipeEntity = new RecipeEntity();
    BeanUtils.copyProperties(newRecipe, newRecipeEntity);

    Recipe returnableRecipe = new Recipe();
    addRecipeToInMemList(BeanUtils.copyProperties(addRecipeToDb(newRecipeEntity), returnableRecipe);

    return newRecipe;
}

資料庫

@Repository
public interface RecipeRepository extends CrudRepository<RecipeEntity, Long> {

    // JPA creates these methods for us
    RecipeEntity findByRecipeName(String recipeName);
    RecipeEntity findByRecipeId(String recipeId);
    //RecipeEntity findAll();         Already for me in CrudRepo
    RecipeEntity save(RecipeEntity recipeEntity);
}

存儲庫保存方法(通過JPA)返回的實體包含結果和錯誤數據,這對於確定數據完整性非常有用。

謝謝尼古拉·舍甫琴科!

暫無
暫無

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

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