perf[orm]: load or create method

This commit is contained in:
godotg
2024-05-29 15:39:36 +08:00
parent ee84151436
commit cc27c41722
7 changed files with 12 additions and 20 deletions
+2 -4
View File
@@ -122,7 +122,7 @@ public class EntityCache<PK extends Comparable<PK>, E extends IEntity<PK>> imple
if (entity == null) {
// 数据库无法加载缓存,返回默认值
logger.warn("[{}] can not load [pk:{}] and use default entity to replace it", entityDef.getClazz().getSimpleName(), pk);
entity = (E) entityDef.newEntity(pk);
entity = (E) entityDef.newEmptyEntity();
}
pnode = new PNode<>(entity);
cache.put(pk, pnode);
@@ -130,7 +130,7 @@ public class EntityCache<PK extends Comparable<PK>, E extends IEntity<PK>> imple
}
@Override
public E loadOrInit(PK pk) {
public E loadOrCreate(PK pk) {
AssertionUtils.notNull(pk);
var pnode = cache.get(pk);
if (pnode != null) {
@@ -142,9 +142,7 @@ public class EntityCache<PK extends Comparable<PK>, E extends IEntity<PK>> imple
// 如果数据库中不存在则给一个默认值
if (entity == null) {
// 数据库无法加载缓存,返回默认值
entity = (E) entityDef.newEntity(pk);
entity.setId(pk);
OrmContext.getAccessor().insert(entity);
}
pnode = new PNode<>(entity);
+1 -1
View File
@@ -35,7 +35,7 @@ public interface IEntityCache<PK extends Comparable<PK>, E extends IEntity<PK>>
* <p>
* CN: 从数据库中加载数据到缓存,如果数据库不存在则返回一个id为传入值的默认示例。并且入库。(设置了索引唯一的无法使用该方法)
*/
E loadOrInit(PK pk);
E loadOrCreate(PK pk);
/**
* 更新缓存中的数据,只更新缓存的时间戳,并通过一定策略写入到数据库
@@ -12,6 +12,7 @@
package com.zfoo.orm.model;
import com.zfoo.orm.anno.Id;
import com.zfoo.orm.config.PersisterStrategy;
import com.zfoo.protocol.util.ReflectionUtils;
@@ -54,8 +55,15 @@ public class EntityDef {
return clazz;
}
public IEntity<?> newEmptyEntity() {
var entity = ReflectionUtils.newInstance(clazz);
return entity;
}
public IEntity<?> newEntity(Object id) {
var entity = ReflectionUtils.newInstance(clazz);
var idFields = ReflectionUtils.getFieldsByAnnoInPOJOClass(clazz, Id.class);
ReflectionUtils.setField(idFields[0], entity, id);
return entity;
}
@@ -24,10 +24,6 @@ public interface IEntity<PK extends Comparable<PK>> {
*/
PK id();
/**
* 设置主键
*/
void setId(PK pk);
/**
* 一个文档的写入到数据库的version版本,version的get和set方法
* <p>
+1 -1
View File
@@ -70,7 +70,7 @@ public class EntityCachesTest {
var mailEntityCaches = (IEntityCache<String, MailEntity>) OrmContext.getOrmManager().getEntityCaches(MailEntity.class);
for (var i = 1; i <= 10; i++) {
var entity = mailEntityCaches.loadOrInit(String.valueOf(i));
var entity = mailEntityCaches.loadOrCreate(String.valueOf(i));
entity.setContent("msg:" + i);
mailEntityCaches.update(entity);
}
@@ -68,11 +68,6 @@ public class UserEntity implements IEntity<Long> {
return id;
}
@Override
public void setId(Long id) {
this.id=id;
}
public long getId() {
return id;
}
@@ -36,11 +36,6 @@ public class MapEntity implements IEntity<Long> {
return id;
}
@Override
public void setId(Long id) {
this.id=id;
}
public long getId() {
return id;
}