【问题标题】:Spring JPA Data: Query ElementCollectionSpring JPA 数据:查询 ElementCollection
【发布时间】:2021-02-17 00:22:31
【问题描述】:

我有一个带有 elementCollection 的实体:

@Entity
class Customer {
  @Column(name = "id")
  int id;
  String name;
  @ElementCollection
  @CollectionTable(
    joinColumns = @JoinColumn(name = "customer_id")
  Set<Address> addresses;
}

@Embeddable
class Address {
  @Column(name = "address_id")
  String id;
  String data;
}

当然是数据库上的匹配数据:

databaseChangeLog:
  - changeSet:
      id: 1
      author: me
      changes:
        - createTable:
            tableName: customer
            columns:
              - column:
                  name: id
                  type: bigint
                  autoIncrement: true
                  constraints:
                    primaryKey: true
                    nullable: false
              - column:
                  name: name
                  type: varchar(255)
        - createTable:
            tableName: address
            columns:
              - column:
                  name: customer_id
                  type: bigint
                   constraints:
                    nullable: false
             - column:
                  name: address_id
                  type: varchar(30)
              - column:
                  name: data
                  type: varchar(255)
        - addForeignKeyConstraint:
            baseTableName: address
            baseColumnNames: customer_id
            referencedTableName: customer
            referencedColumnNames: id
            constraintName: fk_customer_id
        - addUniqueConstraint:
            tableName: address
            name: unique_address_id
            columnNames: address_id

注意:地址 id 确实是一个字符串!

插入和阅读作品。但我的目标是通过Address.id 选择Customer

我的目标:

interface CustomerJpaRepository extends JpaRepository<Customer, Long> {
  XXXX // <-- insert solution here
}

我对 XXXX 的想法:

  1. 使用 Spring Data JPA:
  Customer findByAddressWithId(String addressId);

当然,这是行不通的,因为语法错误。但我什至找不到 ElementCollections 完整语法的描述。

  1. 使用自定义查询:
  @Query(value = "select c from Customer c join Address a where a.id = '?1'")
  Customer findByStreet(String addressId);

这个不起作用,因为找不到a.id

很遗憾,上述方法均无效。 有人有XXXX 的解决方案吗?

【问题讨论】:

    标签: java spring jpa


    【解决方案1】:

    可嵌入类表示没有自己的持久标识。实体类将具有自己的持久身份。 Address 可嵌入类的实例在这里共享拥有它的实体的身份,即Customer。 由于可嵌入类仅作为另一个实体的状态存在,如果您需要 Address 的持久 ID Addressid,请考虑将地址设置为实体。 否则,还要检查持久性提供程序特定的注释,例如 CollectionId CollectionId.html 并将 addressid 定义为 collectionid

    【讨论】:

      猜你喜欢
      • 2013-01-21
      • 1970-01-01
      • 2018-01-13
      • 2017-05-22
      • 2012-05-04
      • 2012-08-19
      • 2020-01-16
      • 2019-04-01
      • 1970-01-01
      相关资源
      最近更新 更多