Маппинг Map в таблицу SQL

 
 
 
Сообщения:187
Есть сущность школьный предмет:
1

@Entity
@Table(name = "subjects")
public class Subject {
    
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    
    @NotNull
    private String name;

Есть сущность дневное расписание, которое содержит карту, где ключ - это время, а значение - предмет:
@Entity
@Table(name = "day_schedules")
public class DaySchedule {
 
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
 
     @ManyToMany
    
    @JoinTable(name = "day_schedule_subject", joinColumns = {@JoinColumn(name =
     "day_schedule_id", referencedColumnName="id")},
     inverseJoinColumns={@JoinColumn(name="subject_id",
     referencedColumnName="id")})
@MapKeyTemporal(TemporalType.TIME)
    private Map<LocalTime, Subject> subjects;

Хибернейт не может создать таблицу. Как я понимаю, ключ должен быть полем в сущности Subject?
 
 
Сообщения:874
@MapKey(name = "my_time_field")
private Map<LocalTime, Subject> subjects;

?
 
 
Сообщения:187
В этом случае в Hibernate возникает ошибка:
22-11-2019 13:14:39.149 [main] DEBUG o.h.cfg.CollectionPropertyHolder.mapKeyAttributeConverterDescriptor - Attempting to locate auto-apply AttributeConverter for collection key [ru.vallball.school01.model.DaySchedule.subjects]
22-11-2019 13:14:39.151 [main] WARN  o.s.w.c.s.AnnotationConfigWebApplicationContext.refresh - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in ru.vallball.school01.config.JpaConfig: Invocation of init method failed; nested exception is java.lang.NullPointerException: prefix or name were null attempting to build qualified name
22-11-2019 13:14:39.151 [main] TRACE o.s.b.f.s.DefaultListableBeanFactory.destroySingletons - Destroying singletons in org.s[email protected]7356ec91: defining beans [org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,org.springframework.context.event.internalEventListenerProcessor,org.springframework.context.event.internalEventListenerFactory,jpaConfig,applicationConfiguration,webSecurityConfig,restAuthenticationEntryPoint,dayScheduleController,groupRestController,subjectRestController,userRestController,dayScheduleServiceImpl,groupServiceImpl,subjectServiceImpl,userServiceImpl,org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration,org.springframework.transaction.config.internalTransactionAdvisor,transactionAttributeSource,transactionInterceptor,org.springframework.transaction.config.internalTransactionalEventListenerFactory,dataSource,entityManagerFactory,transactionManager,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.data.jpa.repository.config.JpaRepositoryConfigExtension#0,emBeanDefinitionRegistrarPostProcessor,jpaMappingContext,jpaContext,org.springframework.data.jpa.util.JpaMetamodelCacheCleanup,org.springframework.data.jpa.repository.support.JpaEvaluationContextExtension,groupRepository,dayScheduleRepository,userRepository,subjectRepository,org.springframework.web.servlet.config.annotation.DelegatingWebMvcConfiguration,requestMappingHandlerMapping,mvcPathMatcher,mvcUrlPathHelper,mvcContentNegotiationManager,viewControllerHandlerMapping,beanNameHandlerMapping,routerFunctionMapping,resourceHandlerMapping,mvcResourceUrlProvider,defaultServletHandlerMapping,requestMappingHandlerAdapter,handlerFunctionAdapter,mvcConversionService,mvcValidator,mvcUriComponentsContributor,httpRequestHandlerAdapter,simpleControllerHandlerAdapter,handlerExceptionResolver,mvcViewResolver,mvcHandlerMappingIntrospector,org.springframework.security.config.annotation.configuration.ObjectPostProcessorConfiguration,objectPostProcessor,org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration,authenticationManagerBuilder,enableGlobalAuthenticationAutowiredConfigurer,initializeUserDetailsBeanManagerConfigurer,initializeAuthenticationProviderBeanManagerConfigurer,org.springframework.security.config.annotation.web.configuration.WebSecurityConfiguration,delegatingApplicationListener,webSecurityExpressionHandler,springSecurityFilterChain,privilegeEvaluator,conversionServicePostProcessor,autowiredWebSecurityConfigurersIgnoreParents,org.springframework.security.config.annotation.web.configuration.WebMvcSecurityConfiguration,requestDataValueProcessor,passwordEncoder,org.springframework.orm.jpa.SharedEntityManagerCreator#0]; root of factory hierarchy
22-11-2019 13:14:39.151 [main] TRACE o.s.b.f.s.DisposableBeanAdapter.invokeCustomDestroyMethod - Invoking destroy method 'close' on bean with name 'dataSource'
22-11-2019 13:14:39.151 [main] INFO  com.zaxxer.hikari.HikariDataSource.close - HikariPool-1 - Shutdown initiated...

В том ли дело, что поле @MapKey(name = "my_time_field") должно содержаться в сущности Subject?
Здесь https://www.baeldung.com/hibernate-persisting-maps нашёл такую фразу:
Quote:
By default, these are similar to @MapKeyColumn in that a key column will be created in the join table. If we want to reuse the value already stored in the persisted entity, we should additionally mark the field with @MapKey.

А если у нас в мапе ключ - базовый тип, а значение - сущность, то какие нужно использовать аннотации?
Изменен:25 ноя 2019 05:20
 
Модераторы:Нет
Сейчас эту тему просматривают:Нет