问题描述
在我们的实体bean中,我们使用自定义ID格式,其中包含校验和以验证ID实际上是否有效。 Ids看起来像 ID827391738979
。为了确保所有代码只使用正确的ID,我们在ID字符串周围创建了一个代码包装器:
In our entity beans we use a custom ID format which includes a checksum to verify that the ID is actually valid. Ids look like ID827391738979
. To make sure that all code uses correct IDs only we created a code wrapper around an ID String:
class ID {
public ID(String id) {
// parse and verify ID
}
public String toString() {
return id;
}
}
所有代码只使用此 ID
对象。但是在我们的实体中,我们将ID定义为字符串
:
All code just uses this ID
object. However in our entity we have defined the ID as a String
:
class SomeEntity {
@Column
private String itsID;
}
现在我们想用Spring-Data-JPA来查询一些对象吧ID。我们这样做:
Now we want to use Spring-Data-JPA to query some object by it's id. So we do:
public SomeEntity findByItsID(ID itsId);
问题是,现在Spring Data JPA尝试将ID类型参数分配给查询,而查询当然需要字符串
。
Problem is, that now Spring Data JPA tries to assign the ID-typed parameter to the query, while the query of course expects a String
.
是否可以让Spring Data JPA将参数转换为预期值在插入查询之前输入类型(例如通过注册Spring转换器)?或者,我们是否必须让方法采用如下字符串:
Is it possible to have Spring Data JPA convert the parameter to the expected type (e.g. by registering a Spring converter) before it is inserted into the query? Or, do we have to let the method take a String like this:
public SomeEntity findByItsId(String itsId);
我宁愿避免这种情况,所以所有代码都可以使用 ID
类而不是求助于字符串。
I would rather avoid this, so all code can use the ID
class instead of resorting to Strings.
推荐答案
你可以使用,因此JPA会为您进行转换(我已经使用Spring Data JPA测试它,并且它透明地工作!),参见:
You could use a custom type in your entity with JPA 2.1 @Convert
, so JPA makes the conversion for you (I've tested it with Spring Data JPA also, and it worked transparently!), see:
实体:
@Entity
class SomeEntity {
@Column(name = "my_id_column_name")
@Convert(converter = MyIDConverter.class)
private ID itsID;
}
转换器:
public class MyIDConverter implements AttributeConverter<ID, String> {
@Override
public String convertToDatabaseColumn(ItStaticDataKey javaKey) {
// your implementation here
}
@Override
public ItStaticDataKey convertToEntityAttribute(final String databaseKey) {
// your implementation here
}
}
注意:
- 确保您使用的是兼容JPA-2.1的Spring数据JPA版。 (我确信Spring Data JPA 1.7.0(及更高版本)是(或者至少应该)兼容)。
- 不幸的是,进行注释,它将无效。
- 如果使用EclipseLink,则必须在persistence.xml中定义转换器,否则它不会启动它。 。
- 在Spring上使用JPA,包含转换器的软件包必须出现在 packageToScan 中> EntityManagerFactoryBean 。
- Make sure you're using a JPA-2.1-compatible Spring Data JPA version. (I'm sure that Spring Data JPA 1.7.0 (and above) are (or at least should) be compatible).
- Unfortunately, it won't work if that field should also be annotated with
@Id
. - If you use EclipseLink, you have to define converter in persistence.xml, or it doesn't pick it up. https://bugs.eclipse.org/bugs/show_bug.cgi?id=412454.
- With JPA on Spring, package containing converters have to appear in property
packageToScan
onEntityManagerFactoryBean
.
这篇关于使用Spring Data JPA自动转换参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!