java - 数据库保存后是否真的有必要从事务中返回保存的实体?

标签 java oop model-view-controller design-patterns

当您将对象保存到数据库时,我知道我应该:

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();

}

服务实现

@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)返回的实体包含结果和错误数据,这对于确定数据完整性非常有用。

谢谢尼古拉-舍甫琴科!

关于java - 数据库保存后是否真的有必要从事务中返回保存的实体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57385580/

相关文章:

model-view-controller - 模型如何更新 MVC 模式中的 View ?

regex - 包含除下划线外的一个特殊字符的密码强度正则表达式

Java 7 对象类

java - 从 Java 7 更改 RequestMapping 方法或在 Java 8 中添加 Optional

java - 如何定义扩展父抽象的子静态类?

java - 在什么情况下一个类的方法可以在另一个类的对象上调用?

asp.net-mvc - 我的 Azure 上的 MVC 应用程序出现 500 错误

Java Web Start 安全警告 JNLP。 JWS 中的错误? 7u51

java - 如何在 JPanel 中使用 paint 方法

javascript - OO JavaScript 调用父方法