Spring Data JPA如何通过原始字符串查询值对象类型的实体主键?
JPA值对象类型主键的前缀匹配查询方案
问题背景
现有定义如下:
- 主键为值对象类型的实体类
class CustomerEntity { @Id @Column(name = "customer_id", nullable = false) private CustomerId customerId; }
- 封装String类型value的值对象
class CustomerId implements Serializable { private final String value; // 为简洁省略构造器、getter }
- 可正常运行的基础Repository
interface CustomerRepository extends JpaRepository<CustomerEntity, CustomerId> { Optional<Customer> findByCustomerId(CustomerId customerId); }
需求是实现customer_id字段的字符串前缀匹配查询,等效SQL为SELECT * FROM Customers where customer_id like '?%',期望定义如下查询方法:
Optional<Customer> findByCustomerIdStartsWith(String search);
核心难点为JPQL中如何将值对象字段转为字符串处理。
可行实现方案
方案1:临时变通方案
利用concat函数拼接空字符串实现隐式类型转换,写法简单但不够优雅:
@Query("FROM CustomerEntity e where concat(e.customerId, '') like ?1%") Optional<Customer> findByCustomerIdStartsWith(String search);
方案2:规范实现方案
将值对象标注为@Embeddable,在实体类中通过@Embedded搭配@AttributeOverride引用,即可支持直接访问值对象内部属性做查询。
注意:该方案需要为值对象添加无参构造器。
内容的提问来源于stack exchange,提问作者Igor Konoplyanko
相关产品推荐
相关产品推荐

