我正在尝试使用spring数据将实体保存到solr并获取其自动生成的id。我看到id已生成但它没有返回给我。代码很简单
实体:
@SolrDocument(solrCoreName = "bank")
@Canonical
class Shop {
@Id
@Field
String id
@Field
String name
}
存储库:
@Repository
interface ShopRepository extends SolrCrudRepository<Shop, String>{
}
处理程序:
@Autowired
ShopRepository repository
void save() {
Shop shop = new Shop()
shop.name = 'shop1'
log.info("before {}", shop)
Shop savedShop = repository.save(shop)
log.info("after {}", savedShop)
}
依赖关系:
dependencies {
compile lib.groovy_all
compile 'org.springframework.boot:spring-boot-starter-data-solr:1.5.10.RELEASE'
}
结果是:
before com.entity.Shop(null, shop1)
after com.entity.Shop(null, shop1)
但是通过solr的管理控制台,我看到生成的id:
{ "responseHeader":{
"status":0,
"QTime":0,
"params":{
"q":"*:*",
"_":"1527472154657"}}, "response":{"numFound":3,"start":0,"docs":[
{
"name":["shop1"],
"id":"4db1eb1d-718b-4a38-b960-6d52f9b6240c",
"_version_":1601670593291223040,
"name_str":["shop1"]},
{
"name":["shop1"],
"id":"6ad52214-0f23-498d-82b8-82f360ef22f1",
"_version_":1601670855078707200,
"name_str":["shop1"]},
{
"name":["shop1"],
"id":"b45b5773-f2b9-4474-b177-92c98810978b",
"_version_":1601670887722975232,
"name_str":["shop1"]}] }}
和repository.findAll()也返回带有映射id的正确结果。它是一个功能还是错误?
答案 0 :(得分:0)
流程按预期工作(返回的对象中没有可用的 ID):
在保存操作期间
所以...最终对象与原始对象完全相同(id null)。
一个快速的“解决方法”可以实现为:
@Repository
public interface PlaceRepo extends SolrCrudRepository<PlaceModel, String> {
default PlaceModel create(PlaceModel model, Duration commit) {
model.setId(IDGenerator.generateID());
return this.save(model, commit);
}
default PlaceModel create(PlaceModel model) {
return this.create(model, Duration.ZERO);
}
}
您正在将 ID 生成逻辑移至 Java 层。 可以将 Id 生成为
public static String generateID() {
return UUID.randomUUID().toString();
}