0

I am trying to generate code for JPA repository below using JavaPOET library but i am getting "only classes have super classes, not INTERFACE" error.

@Repository 
public interface UserRepository extends PagingAndSortingRepository<User, Long> { 
}

Here is the JavaPOET code i tried..

TypeSpec userRepository = TypeSpec.interfaceBuilder("UserRepository")
                .addAnnotation(Repository.class)
                .addModifiers(Modifier.PUBLIC)
                .superclass(ParameterizedTypeName.get(ClassName.get(PagingAndSortingRepository.class),  
                                                      ClassName.get(User.class),
                                                      ClassName.get(Long.class)))
                .build();

Any solution/best practice for generating interface extending a class? Thanks,

mrgenco
  • 348
  • 2
  • 9
  • 27

1 Answers1

1

The message is rather clear :

"only classes have super classes, not INTERFACE" error.

TypeSpec.Builder.superclass() indeed allows to specify only classes.
To specify an interface, use TypeSpec.Builder.addSuperinterface().

It would give :

TypeSpec userRepository = TypeSpec.interfaceBuilder("UserRepository")
                .addAnnotation(Repository.class)
                .addModifiers(Modifier.PUBLIC)
                .addSuperinterface(ParameterizedTypeName.get(ClassName.get(PagingAndSortingRepository.class),  
                                                      ClassName.get(User.class),
                                                      ClassName.get(Long.class)))
                .build();

It should generate this code:

@org.springframework.data.repository.Repository
public interface UserRepository extends org.springframework.data.repository.PagingAndSortingRepository<User, java.lang.Long> {
}

You can find complete examples in the unit tests of the JavaPOET project.
See the git .

davidxxx
  • 125,838
  • 23
  • 214
  • 215
  • Thanks a lot it worked.. Could you also suggest me a way for compiling this generated code at runtime so that it can work without redeploy. As far as i know JavaPOET doesnt have this capability right? If you want me to post another question for this. Thats ok. – mrgenco Oct 15 '17 at 18:06
  • You are welcome. Sorry, I don't know a lot this lib. This issue may maybe interest you : https://github.com/square/javapoet/pull/396. – davidxxx Oct 15 '17 at 19:33