2

I would like to receive all of the records, which extend from my abstract class. I have the following:

Product.java

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
@DiscriminatorColumn(name="descriminatorColumn")
@Table(name="ProductCatalog")
public abstract class Product {
    @Id
    private Long id;
}

PC.java

@Entity
@Table(name = "PC")
public class PC extends Product{
    private String pcType;
}

TV.java

@Entity
@Table(name = "TV")
public class TV extends Product{
    private String tvType;
}

And ProductRepository.java

public interface ProductRepository extends CrudRepository<Product, Long> {
    <T extends Product>List<T> findAll(); // not working
}

In my controller I have:

@RequestMapping(value = "/product", method = GET)
public <T extends Product>List<T> findProducts(){
    return productRepository.findAll();
}

How can I make the findAll() return all of the items from the subclasses that extend class Product?

UPDATE:

I have added the following method to the ProductRepository:

<T extends Product>List<T> findProducts();

and changed it in the controller - is this the proper way to do it ?

The error that I've using this is:

 Caused by:
 org.springframework.data.mapping.PropertyReferenceException: No
 property findProducts found for type Product!
Apostolos
  • 10,033
  • 5
  • 24
  • 39
uksz
  • 18,239
  • 30
  • 94
  • 161

1 Answers1

0

I do it the following way in my repository. Is a generic answer so you could use it for any class, even your abstract class:

public <T> List<T> findAll(Class<T> type) {
    CriteriaBuilder builder = entityManager.getCriteriaBuilder();
    CriteriaQuery<T> criteria = builder.createQuery(type);
    Root<T> root = criteria.from(type);     
    CriteriaQuery<T> all = criteria.select(root);
    TypedQuery<T> allQuery = entityManager.createQuery(all);

    return (List<T>) allQuery.getResultList();
}

Edit: False remark removed.

kaba713
  • 484
  • 6
  • 17
  • Oh I'm sorry I over read that. But shouldn't you then use the `@SecondaryTable` annotation? Take a look at http://stackoverflow.com/q/3915026/6505091 – kaba713 Jul 29 '16 at 14:11