1

I have a few tables named MEMBER, PROVIDER, EMPLOYER etc and they have few common columns like ID, ADDRESS etc. I'm using hibernate to fetch data from these tables using Spring Data JPA. Since I have many similar tables, I created a super entity class and wrote a common method to fetch the data. Here is my super class.

    @Entity
    @Getter
    @Setter
    @NoArgsConstructor
    @ToString
    public abstract class Recipient implements Serializable {

      @Id
      @Column(name = "RECIPIENT_ID", unique = true, nullable = false)
      private Long id;
}

Here is a sample entity which extends this super class.

@Entity
@Getter
@Setter
@NoArgsConstructor
@ToString
@Table(name = "MEMBER")
public class Member extends Recipient {

  @Column(name = "Member_NAME")
  private String membername;

}

Here is the Service

public class RecipientServiceImpl extends AbstractService<Recipient>
    implements RecipientService {
@Override
  public Recipient findByIdAndType(long id, String type) {
    Recipient recipient = null;
    switch (RecipientType.get(type)) {
      case MEMBER:
        recipient = recipientRepository.findMemberById(id);
      case PROVIDER:
        recipient = recipientRepository.findProviderById(id);
      case EMPLOYER:
        recipient = recipientRepository.findEmployerById(id);

    }
}

And here is the repository

 public interface RecipientRepository
        extends JpaRepository<Recipient, Long>, JpaSpecificationExecutor<Recipient> {

        public Member findMemberById(long id);
        public Provider findProviderById(long id);
        public Employer findEmployerById(long id);
    }

Obviously it didn't work since there weren't any tables mapped in the Recipient abstract entity. Is there a way to implement what I was hoping for as a generic fetching method instead of having to create repositories for each entities ?

jijo
  • 765
  • 3
  • 18
  • 35
  • 1
    Did you check [this](https://stackoverflow.com/questions/25237664/use-abstract-super-class-as-parameter-to-spring-data-repository)? – Novy Mar 19 '19 at 17:56
  • ¿¿¿¿maybe??? https://stackoverflow.com/questions/30718798/is-it-necessary-to-create-an-repository-and-a-service-for-each-entity – JuanFdz Aug 24 '19 at 01:44

0 Answers0