Невозможно создать ограничение уникального ключа в моем проекте - PullRequest
0 голосов
/ 11 марта 2020

Моя таблица (tbl_branch_type) существует в моей базе данных. Есть все остальные столбцы, но я получаю эту ошибку:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [com/example/local/config/LocalDbConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: Unable to create unique key constraint (code, bank_type_id) on table tbl_branch_type: database column 'bank_type_id' not found. Make sure that you use the correct column name which depends on the naming strategy in use (it may not be the same as the property name in the entity, especially for relational types)

Моя BranchType сущность:

@Entity
@Table(
    name = "tbl_branch_type",
    uniqueConstraints = {
      @UniqueConstraint(
          name = "uc_branch_type_bank_id_branch_code",
          columnNames = {"code", "bank_type_id"})
    })
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@Getter
@Setter
@EqualsAndHashCode(
    callSuper = true,
    exclude = {"bankType"})
@ToString(exclude = {"bankType"})
public class BranchType extends Auditing implements Serializable {

  private static final long serialVersionUID = 1L;

  @Id
  @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seq_branch_type")
  @SequenceGenerator(sequenceName = "seq_branch_type", allocationSize = 1, name = "seq_branch_type")
  private Long id;

  @NotNull
  @Size(min = 1, max = 20)
  @Column(name = "code", length = 20, nullable = false)
  private String code;

  @NotNull
  @Size(min = 1, max = 100)
  @Column(name = "name", length = 100, nullable = false)
  private String name;

  @JsonIgnore
  @ManyToOne
  @JsonIgnoreProperties("")
  private BankType bankType;
}

Мой LocalDbConfiguration класс:

@Configuration
@PropertySource({"classpath:application.yml"})
@EnableJpaRepositories(
    basePackages = {"com.example.local.model.dao", "com.example.local.core.auth.repository"})
@EnableJpaAuditing(auditorAwareRef = "auditorProvider")
public class LocalDbConfiguration {

  @Primary
  @Bean(name = "dataSource")
  @ConfigurationProperties(prefix = "spring.datasource")
  public DataSource userDataSource() {
    return DataSourceBuilder.create().build();
  }

  @Primary
  @Bean(name = "entityManagerFactory")
  public LocalContainerEntityManagerFactoryBean entityManagerFactory(
      EntityManagerFactoryBuilder builder, @Qualifier("dataSource") DataSource dataSource) {
    Map<String, Object> properties = new HashMap<>();
    properties.put("hibernate.hbm2ddl.auto", "update");
    properties.put("database.platform", "org.hibernate.dialect.Oracle10gDialect");
    return builder
        .dataSource(dataSource)
        .packages(
            "com.example.local.model.entity",
            "com.example.local.model.mapper",
            "com.example.local.core.auth.domain")
        .persistenceUnit("localPU")
        .properties(properties)
        .build();
  }

  @Primary
  @Bean(name = "transactionManager")
  public PlatformTransactionManager transactionManager(
      @Qualifier("entityManagerFactory") EntityManagerFactory entityManagerFactory) {
    return new JpaTransactionManager(entityManagerFactory);
  }

  @Bean
  @Primary
  @ConfigurationProperties("spring.datasource.hikari")
  public HikariConfig defaultHikariConfig() {
    return new HikariConfig();
  }

  @Bean
  AuditorAware<Long> auditorProvider() {
    return new AuditorProviderAware();
  }
}

Ответы [ 2 ]

0 голосов
/ 11 марта 2020

Я решил свою проблему, добавив этот код для entityManagerFactory в LocalDbConfiguration.class

properties.put(
        "hibernate.physical_naming_strategy",
        "org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy");
    properties.put(
        "hibernate.implicit_naming_strategy",
        "org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy");
0 голосов
/ 11 марта 2020

Я считаю, что это root причина вашей проблемы: database column 'bank_type_id' not found. Попробуйте создать этот столбец

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