我想为两个域对象创建一个通用存储库类:产品和类别,并能够列出 index.html 中的所有元素。
这是我的代码:
@Controller
public class IndexController {
private final ProdCatService<Category> categoryProdCatService;
public IndexController(ProdCatService<Category> categoryProdCatService) {
this.categoryProdCatService = categoryProdCatService;
}
@RequestMapping({"","/","index"})
public String getIndexPage(Model model)
{
model.addAttribute("cat", categoryProdCatService.getAll());
return "index";
}
}
存储库:
public interface ProdCatRepository<T> extends CrudRepository<T, Long> { }
服务:
public interface ProdCatService<T> {
Set<T> getAll();
T findById(Long id);
}
@Service
public class ProdCatServiceImpl<T> implements ProdCatService {
private final ProdCatRepository<T> prodCatRepository;
public ProdCatServiceImpl(ProdCatRepository<T> prodCatRepository) {
this.prodCatRepository = prodCatRepository;
}
@Override
public Set<T> getAll() {
Set<T> productsSet = new HashSet<>();
prodCatRepository.findAll().iterator().forEachRemaining(productsSet::add);
return productsSet;
}
@Override
public T findById(Long id) {
return prodCatRepository.findById(id).get();
}
}
所以问题是我得到了一些错误,比如:
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'indexController' defined in file [C:\Users\Michał\Documents\webstore-v-1\target\classes\info\mike\webstorev1\controllers\IndexController.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'prodCatServiceImpl' defined in file [C:\Users\Michał\Documents\webstore-v-1\target\classes\info\mike\webstorev1\service\ProdCatServiceImpl.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'prodCatRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class java.lang.Object
和
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'prodCatRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class java.lang.Object
我正在寻求帮助。我查看了 S/O,但找不到答案。
编辑类别域类。
@Entity
public class Category {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String categoryName;
@ManyToMany(mappedBy = "categories")
private Set<Product> products;
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Category other = (Category) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}