Форум программистов, компьютерный форум, киберфорум
Java: Spring, Spring Boot
Войти
Регистрация
Восстановить пароль
Блоги Сообщество Поиск Заказать работу  
 
-13 / 6 / 6
Регистрация: 04.08.2015
Сообщений: 622

Не получается избавиться от EntityManagerFactory в Spring Boot 1

26.05.2025, 09:18. Показов 1276. Ответов 1
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
Имеется проект Spring Boot 1.5.9.RELEASE который преобразован из проекта на Spring MVC, где был EntityManagerFactory и sessionFactory. Но в этом проекте используется только sessionFactory. Проект включает в себя авторизацию с ролями и разрешениями (roles, permissions). На MVC все работало без проблем. Но возникла необходимость перейти на Spring Boot. Архив можно скачать по ссылке ниже. Там также имеется sql дамп базы данных. Первый вариант проекта на Spring MVC находится на этой странице Пример демо проекта на Spring Boot и смежных технологиях Файл под названием AdminSpringSecurity.zip
Конфигурация
AppConfig.java
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
@Configuration
DataSourceTransactionManagerAutoConfiguration.class})
@EnableWebMvc
@ComponentScan(basePackages = "com.websystique.springboot")
public abstract class AppConfig implements WebMvcConfigurer {
 
 
    /**
     * Configure ViewResolvers to deliver preferred views.
     */
    @Override
    public void configureViewResolvers(ViewResolverRegistry registry) {
 
        InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
        viewResolver.setViewClass(JstlView.class);
        viewResolver.setPrefix("/WEB-INF/views/");
        viewResolver.setSuffix(".jsp");
        registry.viewResolver(viewResolver);
    }
    
    /**
     * Configure ResourceHandlers to serve static resources like CSS/ Javascript etc...
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/static/**").addResourceLocations("/static/");
        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
        registry.addResourceHandler("/resources/css/**").addResourceLocations("/resources/css/").setCachePeriod(31556926);
        registry.addResourceHandler("/resources/img/**").addResourceLocations("/resources/img/").setCachePeriod(31556926);
        registry.addResourceHandler("/resources/js/**").addResourceLocations("/resources/js/").setCachePeriod(31556926);
    }
 
 
    /**
     * Configure MessageSource to lookup any validation/error message in internationalized property files
     */
    @Bean
    public MessageSource messageSource() {
        ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
        messageSource.setBasename("messages");
        return messageSource;
    }
    
    /**Optional. It's only required when handling '.' in @PathVariables which otherwise ignore everything after last '.' in @PathVaidables argument.
     * It's a known bug in Spring [https://jira.spring.io/browse/SPR-6164], still present in Spring 4.1.7.
     * This is a workaround for this issue.
     */
    @Override
    public void configurePathMatch(PathMatchConfigurer matcher) {
        matcher.setUseRegisteredSuffixPatternMatch(true);
    }
}
HibernateConfiguration.java
Java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
@Configuration
@EnableTransactionManagement
@ComponentScan({ "com.websystique.springboot.configuration" })
@PropertySource(value = { "classpath:application.properties" })
public class HibernateConfiguration {
 
    @Autowired
    private Environment environment;
 
    @Bean
    public DataSource dataSource() {
        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(environment.getRequiredProperty("mssql.jdbc.driverClassName"));
        dataSource.setUrl(environment.getRequiredProperty("mssql.jdbc.url"));
        dataSource.setUsername(environment.getRequiredProperty("mssql.jdbc.username"));
        dataSource.setPassword(environment.getRequiredProperty("mssql.jdbc.password"));
        return dataSource;
    }
 
    @Bean
    public LocalSessionFactoryBean sessionFactory() {
        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setDataSource(dataSource());
        sessionFactory.setPackagesToScan(new String[] { "com.websystique.springboot.model" });
        sessionFactory.setHibernateProperties(hibernateProperties());
        return sessionFactory;
     }
    
    private Properties hibernateProperties() {
        Properties properties = new Properties();
        properties.put("hibernate.dialect", environment.getRequiredProperty("mssql.hibernate.dialect"));
        properties.put("hibernate.show_sql", environment.getRequiredProperty("mssql.hibernate.show_sql"));
        properties.put("hibernate.format_sql", environment.getRequiredProperty("mssql.hibernate.format_sql"));
        properties.put("hibernate.hbm2ddl.auto", environment.getRequiredProperty("mssql.hibernate.hbm2ddl.auto"));
        return properties;
    }
    
    @Bean
    @Autowired
    public HibernateTransactionManager transactionManager(SessionFactory s) {
       HibernateTransactionManager txManagerHiber = new HibernateTransactionManager();
        txManagerHiber.setSessionFactory(s);
       return txManagerHiber;
    }
 
}
application.properties
Java
1
2
3
4
5
6
7
8
9
mssql.jdbc.driverClassName = com.microsoft.sqlserver.jdbc.SQLServerDriver
mssql.jdbc.url = jdbc:sqlserver://localhost;databaseName=websystique
mssql.jdbc.username = sa
mssql.jdbc.password = 
 
mssql.hibernate.dialect = org.hibernate.dialect.SQLServerDialect
mssql.hibernate.show_sql = true
mssql.hibernate.format_sql = true
mssql.hibernate.hbm2ddl.auto = update
pom.xml
XML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
                        http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
 
    <groupId>com.websystique.springboot</groupId>
    <artifactId>AdminSpringBootSecurity</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
 
    <name>AdminSpringBootSecurity</name>
    <description>Learn Spring MVC with Real Apps</description>
 
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>1.5.9.RELEASE</version>
        <relativePath /> <!-- lookup parent from repository -->
    </parent>
 
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>
 
    <dependencies>
 
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.hibernate</groupId>
                    <artifactId>hibernate-entitymanager</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.hibernate</groupId>
                    <artifactId>hibernate-core</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
 
        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>4.2.10.Final</version>
        </dependency>
 
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <!-- JSP support -->
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <scope>provided</scope>
        </dependency>
        <!-- JSTL suppport -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
 
        <dependency>
            <groupId>org.dom4j</groupId>
            <artifactId>dom4j</artifactId>
            <version>2.1.3</version>
        </dependency>
        <dependency>
            <groupId>com.microsoft.sqlserver</groupId>
            <artifactId>mssql-jdbc</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-configuration-processor</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.14</version>
        </dependency>
 
    </dependencies>
 
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
 
</project>
Попытка запустить проект на Tomcat 9 завершается со странной ошибкой типа
Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Connected to server
[2025-05-26 09:04:48,739] Artifact AdminSpringBootSecurity:war exploded: Artifact is being deployed, please wait...
...
Files\Java\jdk1.8.0_161\jre\classes,  Spring Boot      (v1.5.9.RELEASE)
...
[/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2025-05-26 09:05:02.152  INFO 8408 --- [on(3)-127.0.0.1] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2025-05-26 09:05:02.336  INFO 8408 --- [on(3)-127.0.0.1] o.s.w.s.handler.SimpleUrlHandlerMapping  : Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2025-05-26 09:05:02.599  WARN 8408 --- [on(3)-127.0.0.1] ationConfigEmbeddedWebApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaMappingContext': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: At least one JPA metamodel must be present!
2025-05-26 09:05:02.599  INFO 8408 --- [on(3)-127.0.0.1] o.s.j.e.a.AnnotationMBeanExporter        : Unregistering JMX-exposed beans on shutdown
2025-05-26 09:05:02.616  INFO 8408 --- [on(3)-127.0.0.1] utoConfigurationReportLoggingInitializer : 
 
Error starting ApplicationContext. To display the auto-configuration report re-run your application with 'debug' enabled.
2025-05-26 09:05:02.633 ERROR 8408 --- [on(3)-127.0.0.1] o.s.boot.SpringApplication               : Application startup failed
 
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaMappingContext': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: At least one JPA metamodel must be present!
    at 
        ... 63 more
[2025-05-26 09:05:02,732] Artifact AdminSpringBootSecurity:war exploded: Error during artifact deployment. See server log for details.
Вроде в проекте не используется JPA и даже в pom это заблокировано
XML
1
2
3
4
5
6
7
8
9
10
11
12
13
14
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.hibernate</groupId>
                    <artifactId>hibernate-entitymanager</artifactId>
                </exclusion>
                <exclusion>
                    <groupId>org.hibernate</groupId>
                    <artifactId>hibernate-core</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
но ошибка говорит про jpa
Code
1
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jpaMappingContext': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: At least one JPA metamodel must be present!
Подскажите пожалуйста что в данном проекте не так. Почему At least one JPA metamodel must be present! если в проекте не используется JPA?
Как выйти из положения?
Вложения
Тип файла: rar AdminSpringBootSecurity.rar (9.50 Мб, 0 просмотров)
0
Programming
Эксперт
39485 / 9562 / 3019
Регистрация: 12.04.2006
Сообщений: 41,671
Блог
26.05.2025, 09:18
Ответы с готовыми решениями:

Ошибка entityManagerFactory (Spring)
Изучаю Spring, в качестве примера использую уроки из сети, но возникли трудности, с ошибкой...

Project 'org.springframework.boot:spring-boot-starter-parent:2.3.2.RELEASE' not found
&lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt; &lt;project xmlns=&quot;http://maven.apache.org/POM/4.0.0&quot; ...

Что такое Spring, Spring Boot?
Здравствуйте. Никогда не использовал Spring, Spring Boot. Возник такой вопрос можно ли его...

1
 Аватар для andrey_f
884 / 537 / 228
Регистрация: 21.02.2011
Сообщений: 5,705
27.05.2025, 18:45
Судя по описанию и конфигурации, основная причина ошибки — Spring Boot пытается автоматически настроить JPA, потому что в зависимостях есть spring-boot-starter-data-jpa, даже если вы явно не используете JPA. В итоге, при запуске создается бина jpaMappingContext, который требует наличие метамодели JPA, которая у вас отсутствует.
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
inter-admin
Эксперт
29715 / 6470 / 2152
Регистрация: 06.03.2009
Сообщений: 28,500
Блог
27.05.2025, 18:45
Помогаю со студенческими работами здесь

Spring в Spring Boot context
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext( ...

Spring Boot VS Tomcat+Spring - что выбрать?
Всем доброго дня! Я наверное еще из старой школы - пилю мелкие проект на Spring + Tomcat... ...

Spring Boot или Spring MVC?
Добрый день форумчане. Прошу совета у опытных коллег знающих и работающих с фреймворком Spring....

Hibernate : EntityManager и EntityManagerFactory (есть ли стандартные реализации ?)
В сгенерированном коде у меня всё завязано на EntityManager, который сразу видно рассчитывает на...

Attempting to execute an operation on a closed EntityManagerFactory
Создаю dataTable: &lt;h:dataTable value=&quot;#{friend.list}&quot; var=&quot;f2&quot;&gt; &lt;h:column&gt; ...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
2
Ответ Создать тему
Новые блоги и статьи
Уведомление о неверно выбранном значении справочника
Maks 06.04.2026
Алгоритм из решения ниже реализован на примере нетипового документа "НарядПутевка", разработанного в конфигурации КА2. Задача: уведомлять пользователя, если в документе выбран неверный склад. . .
Установка Qt Creator для C и C++: ставим среду, CMake и MinGW без фреймворка Qt
8Observer8 05.04.2026
Среду разработки Qt Creator можно установить без фреймворка Qt. Есть отдельный репозиторий для этой среды: https:/ / github. com/ qt-creator/ qt-creator, где можно скачать установщик, на вкладке Releases:. . .
AkelPad-скрипты, структуры, и немного лирики..
testuser2 05.04.2026
Такая программа, как AkelPad существует уже давно, и также давно существуют скрипты под нее. Тем не менее, прога живет, периодически что-то не спеша дополняется, улучшается. Что меня в первую очередь. . .
Отображение реквизитов в документе по условию и контроль их заполнения
Maks 04.04.2026
Алгоритм из решения ниже реализован на примере нетипового документа "ПланированиеСпецтехники", разработанного в конфигурации КА2. Данный документ берёт данные из другого нетипового документа. . .
Фото всей Земли с борта корабля Orion миссии Artemis II
kumehtar 04.04.2026
Это первое подобное фото сделанное человеком за 50 лет. Снимок называют новым вариантом легендарной фотографии «The Blue Marble» 1972 года, сделанной с борта корабля «Аполлон-17». Новое фото. . .
Вывод диалогового окна перед закрытием, если документ не проведён
Maks 04.04.2026
Алгоритм из решения ниже реализован на примере нетипового документа "СписаниеМатериалов", разработанного в конфигурации КА2. Задача: реализовать программный контроль на предмет проведения документа. . .
Программный контроль заполнения реквизитов табличной части документа
Maks 02.04.2026
Алгоритм из решения ниже реализован на примере нетипового документа "СписаниеМатериалов", разработанного в конфигурации КА2. Задача: 1. Реализовать контроль заполнения реквизита. . .
wmic не является внутренней или внешней командой
Maks 02.04.2026
Решение: DISM / Online / Add-Capability / CapabilityName:WMIC~~~~ Отсюда: https:/ / winitpro. ru/ index. php/ 2025/ 02/ 14/ komanda-wmic-ne-naydena/
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru