Я новичок в Spring и попытался включить работающий проект Hibernate в среду Spring. Проекты работают соло отлично, но не в сочетании. Сначала я попытался выполнить свой тест Hibernate (последний фрагмент кода) в основном перед SpringApplikation.run (), но он был выполнен дважды. Затем я прочитал, что вы должны пометить класс как @Component, если я хочу получить его экземпляр при запуске приложения - без успеха. Любые предложения, как решить эту проблему? (:
это вывод моей консоли:
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.2.4.RELEASE)
17:02:01.782 [restartedMain] INFO d.s.k.KeyCloakTutorial - Starting KeyCloakTutorial on XXX with PID 16765 (/home/user/test_environment/slackspace-angular2-spring-keycloak/backend/target/classes started by mario in /home/user/test_environment/slackspace-angular2-spring-keycloak/backend)
17:02:01.784 [restartedMain] INFO d.s.k.KeyCloakTutorial - No active profile set, falling back to default profiles: default
17:02:01.812 [restartedMain] INFO o.s.b.d.restart.ChangeableUrls - The Class-Path manifest attribute in /home/user/.m2/repository/org/glassfish/jaxb/jaxb-runtime/2.3.2/jaxb-runtime-2.3.2.jar referenced one or more files that do not exist: file:/home/user/.m2/repository/org/glassfish/jaxb/jaxb-runtime/2.3.2/jakarta.xml.bind-api-2.3.2.jar,file:/home/user/.m2/repository/org/glassfish/jaxb/jaxb-runtime/2.3.2/txw2-2.3.2.jar,file:/home/user/.m2/repository/org/glassfish/jaxb/jaxb-runtime/2.3.2/istack-commons-runtime-3.0.8.jar,file:/home/user/.m2/repository/org/glassfish/jaxb/jaxb-runtime/2.3.2/stax-ex-1.8.1.jar,file:/home/user/.m2/repository/org/glassfish/jaxb/jaxb-runtime/2.3.2/FastInfoset-1.2.16.jar,file:/home/user/.m2/repository/org/glassfish/jaxb/jaxb-runtime/2.3.2/jakarta.activation-api-1.2.1.jar
17:02:01.813 [restartedMain] INFO o.s.b.d.e.DevToolsPropertyDefaultsPostProcessor - Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
17:02:01.813 [restartedMain] INFO o.s.b.d.e.DevToolsPropertyDefaultsPostProcessor - For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
17:02:02.621 [restartedMain] INFO o.s.b.w.e.tomcat.TomcatWebServer - Tomcat initialized with port(s): 8000 (http)
17:02:02.628 [restartedMain] INFO o.a.coyote.http11.Http11NioProtocol - Initializing ProtocolHandler ["http-nio-8000"]
17:02:02.628 [restartedMain] INFO o.a.catalina.core.StandardService - Starting service [Tomcat]
17:02:02.628 [restartedMain] INFO o.a.catalina.core.StandardEngine - Starting Servlet engine: [Apache Tomcat/9.0.30]
17:02:02.692 [restartedMain] INFO o.a.c.c.C.[Tomcat].[localhost].[/] - Initializing Spring embedded WebApplicationContext
17:02:02.692 [restartedMain] INFO o.s.web.context.ContextLoader - Root WebApplicationContext: initialization completed in 879 ms
17:02:02.801 [restartedMain] INFO o.s.s.c.ThreadPoolTaskExecutor - Initializing ExecutorService 'applicationTaskExecutor'
17:02:02.842 [restartedMain] INFO o.s.b.a.w.s.WelcomePageHandlerMapping - Adding welcome page: ServletContext resource [/index.html]
17:02:02.896 [restartedMain] INFO o.s.b.d.a.OptionalLiveReloadServer - LiveReload server is running on port 35729
------------------------------------------------------
Hibernate wird initialisiert
17:02:02.950 [restartedMain] INFO org.hibernate.Version - HHH000412: Hibernate ORM core version 5.4.12.Final
17:02:03.032 [restartedMain] WARN org.hibernate.orm.deprecation - HHH90000012: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/hibernate-configuration. Use namespace http://www.hibernate.org/dtd/hibernate-configuration instead. Support for obsolete DTD/XSD namespaces may be removed at any time.
17:02:03.189 [restartedMain] INFO o.h.annotations.common.Version - HCANN000001: Hibernate Commons Annotations {5.1.0.Final}
17:02:03.248 [restartedMain] WARN o.hibernate.orm.connections.pooling - HHH10001002: Using Hibernate built-in connection pool (not for production use!)
17:02:03.253 [restartedMain] INFO o.hibernate.orm.connections.pooling - HHH10001005: using driver [org.postgresql.Driver] at URL [jdbc:postgresql://localhost:5432/postgres]
17:02:03.253 [restartedMain] INFO o.hibernate.orm.connections.pooling - HHH10001001: Connection properties: {password=****, user=postgres}
17:02:03.253 [restartedMain] INFO o.hibernate.orm.connections.pooling - HHH10001003: Autocommit mode: false
17:02:03.255 [restartedMain] INFO o.h.e.j.c.i.DriverManagerConnectionProviderImpl - HHH000115: Hibernate connection pool size: 20 (min=1)
17:02:03.298 [restartedMain] INFO org.hibernate.dialect.Dialect - HHH000400: Using dialect: org.hibernate.dialect.PostgreSQLDialect
Hibernate: drop table if exists NOTIFICATION cascade
17:02:03.703 [restartedMain] INFO org.hibernate.orm.connections.access - HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@68a556ca] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
Hibernate: drop sequence if exists hibernate_sequence
Hibernate: create sequence hibernate_sequence start 1 increment 1
17:02:03.712 [restartedMain] INFO org.hibernate.orm.connections.access - HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@158e367f] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
Hibernate: create table NOTIFICATION (ID int8 not null, channel varchar(255), message varchar(1024) not null, name varchar(64), trigger varchar(64) not null, primary key (ID))
17:02:03.737 [restartedMain] INFO o.h.e.t.j.p.i.JtaPlatformInitiator - HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
Hibernate wurde initialisiert
------------------------------------------------------
de.slackspace.keycloaktutorial.notification.Notification@c76354a
Hibernate: select nextval ('hibernate_sequence')
17:02:03.784 [restartedMain] INFO o.a.catalina.core.StandardService - Stopping service [Tomcat]
17:02:03.792 [restartedMain] INFO o.s.b.a.l.ConditionEvaluationReportLoggingListener -
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
17:02:03.794 [restartedMain] ERROR o.s.boot.SpringApplication - Application run failed
org.hibernate.PropertyAccessException: Could not set field value [1] value by reflection : [class de.slackspace.keycloaktutorial.notification.Notification.id] setter of de.slackspace.keycloaktutorial.notification.Notification.id
at org.hibernate.property.access.spi.SetterFieldImpl.set(SetterFieldImpl.java:61)
at org.hibernate.tuple.entity.AbstractEntityTuplizer.setIdentifier(AbstractEntityTuplizer.java:258)
at org.hibernate.persister.entity.AbstractEntityPersister.setIdentifier(AbstractEntityPersister.java:5124)
at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:183)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:135)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:194)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:179)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:75)
at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:102)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:626)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:619)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:614)
at de.slackspace.keycloaktutorial.notification.NotificationDao.create(NotificationDao.java:19)
at de.slackspace.keycloaktutorial.init.DatabaseStarter.init(DatabaseStarter.java:24)
at de.slackspace.keycloaktutorial.init.DatabaseStarter.contextRefreshedEvent(DatabaseStarter.java:16)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.springframework.context.event.ApplicationListenerMethodAdapter.doInvoke(ApplicationListenerMethodAdapter.java:305)
at org.springframework.context.event.ApplicationListenerMethodAdapter.processEvent(ApplicationListenerMethodAdapter.java:190)
at org.springframework.context.event.ApplicationListenerMethodAdapter.onApplicationEvent(ApplicationListenerMethodAdapter.java:153)
at org.springframework.context.event.SimpleApplicationEventMulticaster.doInvokeListener(SimpleApplicationEventMulticaster.java:172)
at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:165)
at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:139)
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:403)
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:360)
at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:897)
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.finishRefresh(ServletWebServerApplicationContext.java:162)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:553)
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:141)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:747)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:315)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1215)
at de.slackspace.keycloaktutorial.KeyCloakTutorial.main(KeyCloakTutorial.java:10)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:566)
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49)
Caused by: java.lang.IllegalArgumentException: Can not set java.lang.Long field de.slackspace.keycloaktutorial.notification.Notification.id to de.slackspace.keycloaktutorial.notification.Notification
at java.base/jdk.internal.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167)
at java.base/jdk.internal.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:171)
at java.base/jdk.internal.reflect.UnsafeFieldAccessorImpl.ensureObj(UnsafeFieldAccessorImpl.java:58)
at java.base/jdk.internal.reflect.UnsafeObjectFieldAccessorImpl.set(UnsafeObjectFieldAccessorImpl.java:75)
at java.base/java.lang.reflect.Field.set(Field.java:780)
at org.hibernate.property.access.spi.SetterFieldImpl.set(SetterFieldImpl.java:41)
... 43 common frames omitted
17:02:03.796 [restartedMain] INFO o.s.s.c.ThreadPoolTaskExecutor - Shutting down ExecutorService 'applicationTaskExecutor'
класс уведомлений:
package de.slackspace.keycloaktutorial.notification;
import javax.persistence.*;
import de.slackspace.keycloaktutorial.Channel;
@Entity
@Table(name = "NOTIFICATION")
public class Notification {
@Id @GeneratedValue
@Column(name = "ID")
private Long id;
@Column(length=64, nullable=true)
private String name;
@Column(length=64, nullable=false)
private String trigger;
@Enumerated(EnumType.STRING)
private Channel channel;
@Column(length=1024, nullable=false)
private String message;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getTrigger() {
return trigger;
}
public void setTrigger(String trigger) {
this.trigger = trigger;
}
public Channel getChannel() {
return channel;
}
public void setChannel(Channel channel) {
this.channel = channel;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
dao:
public class NotificationDao {
public void create(Session session, String name, String trigger, String channel, String message) {
Notification notification = new Notification();
notification.setName(name);
notification.setTrigger(trigger);
notification.setChannel(Channel.valueOf(channel.toUpperCase()));
notification.setMessage(message);
session.beginTransaction();
session.save(notification);
session.getTransaction().commit();
session.refresh(notification);
}
}
my попробуйте инициализировать hibernate:
@Component
public class DatabaseStarter {
@EventListener(ContextRefreshedEvent.class)
public void contextRefreshedEvent() {
init();
}
private void init() {
HibernateConfigurator hibernateConfigurator = new HibernateConfigurator();
Session session = hibernateConfigurator.getSession();
NotificationDao notificationDao = new NotificationDao();
notificationDao.create(session, "test_name", "test_trigger", "EMAIL", "test_message");
}
}
Спасибо за помощь! (=
Редактировать: у меня есть решение. Это дико и жестоко, но оно работает. Я перешел из Hibernate на JPA и имею больше никаких проблем.