Использование @OneToMany или @ManyToMany для таргетинга на несопоставленный класс (соединение с несколькими базами данных) - PullRequest
1 голос
/ 09 марта 2020

У меня есть проект JPA Spring. Я добавил два файла конфигурации базы данных. Когда я хочу запустить проект, я получаю эту ошибку? Я использую javax.persistence.Entity.

сущность пользователя

package com.example.local.model.entity;

@Entity
@Table(
    name = "tbl_user",
    uniqueConstraints = {
      @UniqueConstraint(name = "uc_user_data_username", columnNames = "username"),
      @UniqueConstraint(name = "uc_user_data_email", columnNames = "email")
    })
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@Getter
@Setter
@EqualsAndHashCode(callSuper = true)
@ToString(exclude = "password")
public class User extends Auditing implements Serializable {

  private static final long serialVersionUID = 1L;

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

  @NotNull
  //    @Pattern(regexp = ApplicationConstants.Entity.MOBILE_REGEX)
  @NationalCode
  //    @Size(min = 11, max = 11)
  @Column(name = "username", length = 11, nullable = false)
  private String username;

  @Pattern(regexp = regex.MOBILE_REGEX)
  @Column(name = "mobile", length = 11)
  private String mobile;

  @Email
  @Size(min = 7, max = 50)
  @Column(name = "email", length = 50)
  private String email;

  @JsonIgnore
  @NotNull
  //    @Size(min = 5, max = 50)
  @Column(name = "password", length = 60, nullable = false)
  private String password;

  @Size(max = 256)
  @Column(name = "image", length = 256)
  private String image;

  @NotNull
  @Size(max = 30)
  @Column(name = "first_name", length = 30)
  private String firstName;

  @NotNull
  @Size(max = 30)
  @Column(name = "last_name", length = 30)
  private String lastName;

  @Column(name = "national_code", length = 11)
  private String nationalCode;

  @Size(max = 20)
  @Column(name = "activation_key", length = 20)
  @JsonIgnore
  private String activationKey;

  @Size(max = 20)
  @Column(name = "reset_key", length = 20)
  @JsonIgnore
  private String resetKey;

  @Column(name = "reset_at")
  private LocalDateTime resetAt = null;

  @ColumnDefault("1")
  @Column(name = "account_enabled")
  private Boolean isAccountEnabled = true;

  @ColumnDefault("0")
  @Column(name = "account_expired")
  private Boolean isAccountExpired = false;

  @ColumnDefault("0")
  @Column(name = "credentials_expired")
  private Boolean isCredentialsExpired = false;

  @ColumnDefault("0")
  @Column(name = "account_locked")
  private Boolean isAccountLocked = false;

  @ColumnDefault("1")
  @Column(name = "priority")
  private Byte priority = 1;

  @ColumnDefault("1")
  @Column(name = "is_active")
  private Boolean isActive = true;

  @Column(
    name = "user_type",
    length = 10,
    columnDefinition = "VARCHAR2(10 CHAR) DEFAULT 'USER'",
    insertable = false)
  @Enumerated(value = EnumType.STRING)
  private UserType userType = UserType.USER;

  @JsonIgnore
  @ManyToOne
  @JsonIgnoreProperties("")
  private AgencyType agencyType;

  @JsonIgnore
  @ManyToMany
  @JoinTable(
      name = "tbl_auth_user_authority",
      joinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "id")},
      inverseJoinColumns = {@JoinColumn(name = "authority_name", referencedColumnName = "name")})
  @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
  @BatchSize(size = 20)
  private Set<Authority> authorities = new HashSet<>();

  @JsonIgnore
  @ManyToMany
  @JoinTable(
      name = "tbl_auth_user_permission",
      joinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "id")},
      inverseJoinColumns = {@JoinColumn(name = "permission_name", referencedColumnName = "name")})
  @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
  @BatchSize(size = 20)
  private Set<Permission> permissions = new HashSet<>();

  @JsonIgnore
  @ManyToMany
  @JoinTable(
      name = "tbl_auth_user_permission_omitted",
      joinColumns = {@JoinColumn(name = "user_id", referencedColumnName = "id")},
      inverseJoinColumns = {@JoinColumn(name = "permission_name", referencedColumnName = "name")})
  @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
  @BatchSize(size = 20)
  private Set<Permission> omittedPermissions = new HashSet<>();
}

сущность разрешения

package com.example.local.core.auth.domain;

@Entity
@Table(
    name = "tbl_auth_permission",
    indexes = {@Index(name = "tbl_auth_permission_indexes", columnList = "name, is_active")})
@Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
@Getter
@Setter
@EqualsAndHashCode(callSuper = true)
@ToString
// @Audited
public class Permission extends Auditing implements Serializable {

  private static final long serialVersionUID = 1L;

  @Id
  @NotNull
  @Size(min = 2, max = 100)
  @Pattern(
      regexp = regex.ALPHA_UNDERSCORE_REGEX,
      message = "permission.property.name.uppercase.message")
  @Column(name = "name", length = 100, unique = true)
  private String name;

  @ColumnDefault("1")
  @Column(name = "priority")
  private Byte priority = 1;

  @ColumnDefault("1")
  @Column(name = "is_active")
  private Boolean isActive = true;
}

файл конфигурации базы данных

package com.example.local.config;

@Configuration
@PropertySource({"classpath:application.yml"})
@EnableJpaRepositories(
    basePackages = "com.sepehrpay.mps.model.dao")
@EnableJpaAuditing(auditorAwareRef = "auditorProvider") // "springSecurityAuditorAware"
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.sepehrpay.mps.model.entity", "com.sepehrpay.mps.model.mapper")
        .persistenceUnit("MpsPU")
        .properties(properties)
        .build();
  }

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

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

ошибка:

org.hibernate.AnnotationException: использование таргетинга @OneToMany или @ManyToMany не сопоставленный класс: com.example.local.model.entity.User.permissions [com.example.local.core.auth.domain.Permission]

1 Ответ

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

Я решил свою проблему, изменив адрес пакетов для сканирования в entityManagerFactory

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