Hibernate не может загрузить запрошенный класс с составным идентификатором - PullRequest
0 голосов
/ 25 января 2020

Я использовал инструмент Hibernate Code Generation в плагинах eclipse для генерации классов pojo, hbm-файлов и классов DAO для мировой базы данных . Это сгенерировало City. java, Country. java, Countrylanguage. java и CountrylanguageId. java, но только три файла hbm City.hbm. xml Country.hbm. xml и Countrylanguage.hbm. xml.

Я добавил файлы классов java в конфигурацию через addClass

    protected SessionFactory getSessionFactory() {
    Configuration config = new Configuration()
            .configure("hibernate.cfg.xml")
            .addClass(Country.class)
            .addClass(City.class)
            .addClass(Countrylanguage.class);

Но при попытке создать реестр службы, используя

StandardServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().applySettings(config.getProperties()).build();

Выдает следующую ошибку -

Exception in thread "main" org.hibernate.HibernateException: Unable to instantiate default tuplizer [org.hibernate.tuple.component.PojoComponentTuplizer]
at org.hibernate.tuple.component.ComponentTuplizerFactory.constructTuplizer(ComponentTuplizerFactory.java:107)
at org.hibernate.tuple.component.ComponentTuplizerFactory.constructDefaultTuplizer(ComponentTuplizerFactory.java:128)
at org.hibernate.tuple.component.ComponentMetamodel.<init>(ComponentMetamodel.java:77)
at org.hibernate.tuple.component.ComponentMetamodel.<init>(ComponentMetamodel.java:52)
at org.hibernate.mapping.Component.getType(Component.java:227)
at org.hibernate.mapping.SimpleValue.isValid(SimpleValue.java:455)
at org.hibernate.mapping.RootClass.validate(RootClass.java:268)
at org.hibernate.boot.internal.MetadataImpl.validate(MetadataImpl.java:343)
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:461)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:708)
at dao.DefaultService.getSessionFactory(DefaultService.java:24)
at dao.DefaultService.<init>(DefaultService.java:14)
at dao.CityService.<init>(CityService.java:21)
at App.main(App.java:6)
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at org.hibernate.tuple.component.ComponentTuplizerFactory.constructTuplizer(ComponentTuplizerFactory.java:104)
... 13 more
Caused by: org.hibernate.MappingException: component class not found: CountrylanguageId
at org.hibernate.mapping.Component.getComponentClass(Component.java:177)
at org.hibernate.tuple.component.PojoComponentTuplizer.setComponentClass(PojoComponentTuplizer.java:147)
at org.hibernate.tuple.component.AbstractComponentTuplizer.<init>(AbstractComponentTuplizer.java:37)
at org.hibernate.tuple.component.PojoComponentTuplizer.<init>(PojoComponentTuplizer.java:41)
... 18 more
Caused by: org.hibernate.boot.registry.classloading.spi.ClassLoadingException: Unable to load class [CountrylanguageId]
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:133)
at org.hibernate.mapping.Component.getComponentClass(Component.java:174)
... 21 more
Caused by: java.lang.ClassNotFoundException: Could not load requested class : CountrylanguageId
at org.hibernate.boot.registry.classloading.internal.AggregatedClassLoader.findClass(AggregatedClassLoader.java:210)
at java.lang.ClassLoader.loadClass(ClassLoader.java:418)
at java.lang.ClassLoader.loadClass(ClassLoader.java:351)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:348)
at org.hibernate.boot.registry.classloading.internal.ClassLoaderServiceImpl.classForName(ClassLoaderServiceImpl.java:130)
... 22 more

Я пытался добавить

.addClass (CountrylanguageId.class)

, но это вызывает другую ошибку что отсутствует соответствующий файл hbm Countrylanguage.hbm. xml.

Нужны ли файлы hbm для классов, которые создаются на основе отношений составного идентификатора? Почему эта ошибка появляется, хотя класс был указан в экземпляре конфигурации Hibernate?

1 Ответ

0 голосов
/ 25 января 2020

Разобрался с проблемой. Используя инструмент hibernate, когда я генерировал классы pojo, я указал его как пакет по умолчанию, но сгенерировал их в подпапке src / main / java / entity.

Файлы hbm были обновлены, чтобы иметь class = "..." ссылки и name = "..." ссылки на entity.Countrylanguage, после чего он работает нормально.

Также проверено, что при использовании инструмента генерации гибернации, настроенного с пакетом в качестве сущности и папкой по умолчанию src / main / java выводит файлы hbm правильно, как и ожидалось.

Пометит этот вопрос как ответивший и закройте его.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...