Guest User

Untitled

a guest
Aug 6th, 2018
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.07 KB | None | 0 0
  1. package sample;
  2.  
  3. import org.hibernate.boot.MetadataSources;
  4. import org.hibernate.cfg.Configuration;
  5.  
  6. import org.springframework.boot.SpringApplication;
  7. import org.springframework.boot.context.event.ApplicationReadyEvent;
  8. import org.springframework.context.ApplicationListener;
  9. import org.springframework.context.annotation.ComponentScan;
  10. import org.springframework.data.jpa.repository.support.JpaRepositoryFactory;
  11. import org.springframework.data.repository.Repository;
  12. import org.springframework.stereotype.Component;
  13.  
  14. import java.util.Optional;
  15. import javax.persistence.*;
  16.  
  17. @ComponentScan
  18. public class Main {
  19. public static void main(String[] args) {
  20. SpringApplication.run(Main.class, args);
  21. }
  22. }
  23.  
  24. @Entity
  25. class Widget {
  26. @Id
  27. private Integer id;
  28. }
  29.  
  30. interface WidgetRepository extends Repository<Widget, Integer> {
  31. Optional<Widget> findById(Integer id);
  32. }
  33.  
  34. @Component
  35. class Sample implements ApplicationListener<ApplicationReadyEvent> {
  36. @Override
  37. public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) {
  38. MetadataSources metadataSources = new MetadataSources()
  39. .addAnnotatedClass(Widget.class);
  40.  
  41. Configuration configuration = new Configuration(metadataSources)
  42. .setProperty("hibernate.connection.url", "jdbc:postgresql://localhost/database");
  43.  
  44. EntityManagerFactory entityManagerFactory = configuration.buildSessionFactory();
  45. EntityManager entityManager = entityManagerFactory.createEntityManager();
  46. JpaRepositoryFactory repositoryFactory = new JpaRepositoryFactory(entityManager);
  47.  
  48. // prints class sample.Widget
  49. entityManager.getMetamodel().getManagedTypes().forEach(ty -> System.err.println(ty.getJavaType()));
  50.  
  51. // throws java.lang.IllegalArgumentException: Not a managed type: class sample.Widget
  52. entityManager.getMetamodel().managedType(Widget.class);
  53.  
  54. // throws java.lang.IllegalArgumentException: Not a managed type: class sample.Widget
  55. WidgetRepository widgetRepository = repositoryFactory.getRepository(WidgetRepository.class);
  56. }
  57. }
Add Comment
Please, Sign In to add comment