添加电影并检查类别是否存在

0s0u357o  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(220)

我想创建一个端点,在那里我可以添加电影,并将其添加到数据库中,一切正常,但我有问题的类别。保存电影后,它应该检查该类别是否存在,如果不存在=抛出异常。我用值进行了枚举,但是如何检查请求中的类别是否已经存在?当然,我试图创建类、repo等,但我无法检查,因为数据库并没有记录。
在前端,我将创建选项字段,所以用户不能犯错误,但我认为这并不重要,在后端,我应该检查无论如何。
我试着这样:

@Entity
@Table(name = "category")
public class Category {
    @Id
    @GeneratedValue(generator = "inc")
    @GenericGenerator(name = "inc", strategy = "increment")
    private int id;
    @Enumerated(EnumType.STRING)
    private ECategory name;
    @OneToMany(fetch = FetchType.LAZY, mappedBy = "category", cascade = CascadeType.ALL)
    private Set<Movie> movies = new HashSet<>();

// TODO: add more categories
public enum ECategory {
    ACTION,
    COMEDY,
    DRAMA,
    FANTASY,
    HORROR,
    ROMANCE,
    THRILLER
}

public interface CategoryRepository {
    Optional<Category> findByName(ECategory name);
}

服务:

@Service
class CategoryService {
    private final CategoryRepository repository;

    CategoryService(final CategoryRepository repository) {
        this.repository = repository;
    }

        public Set<Category> checkCategories(Set<String> categoriesToCheck) {
            Set<Category> categories = new HashSet<>();

            if (categoriesToCheck.isEmpty()) {
                throw new IllegalStateException("Categories are empty!");
            }

            categoriesToCheck.forEach(cat -> {
                Category category = repository
                        .findByName(ECategory.valueOf(cat))
                        .orElseThrow(() -> new IllegalStateException("That category not exists!"));
                categories.add(category);
            });
            return categories;
        }
    }

@更新我想我可以试着用这个开关,但也许有人有更好的主意。

ukqbszuj

ukqbszuj1#

更新
我向实体添加了enum,但不幸的是我不得不从列表中辞职。

@Enumerated(EnumType.STRING)
    private ECategory category;

类别类(和repo)已被删除,现在只有ecategory-enum类。
服务看起来像:

@Service
class CategoryService {

    public ECategory checkCategory(String categoryToCheck) {
        for (ECategory cat : ECategory.values()) {
            if (cat.name().equals(categoryToCheck)) {
                return cat;
            }
        }
        throw new IllegalStateException("That category not exists!");
    }
}

此解决方案将保留一段时间。。

相关问题