mardi 6 août 2019

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

When you save an object to the database, I know I should:

DogEntity savedDogEntity = repository.save(dogEntityToSave);

because the saving process may return a null right? Error?

Service

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

@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);
}

Aucun commentaire:

Enregistrer un commentaire