liujie
2026-01-14 f976a39b294f8c7dd60bcd2c661983c0dcc97fc6
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package com.estate.expert.admin.domain.common.mapper;
 
import com.estate.expert.admin.domain.common.EntityBase;
import com.estate.expert.admin.domain.common.EntityRef;
import org.mapstruct.TargetType;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
 
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
 
@Component
public class EntityRefMapper {
 
    @PersistenceContext
    private EntityManager entityManager;
 
    public <T extends EntityBase> T resolve(EntityRef reference, @TargetType Class<T> entityClass) {
        return reference != null ? entityManager.find( entityClass, reference.getId() ) : null;
    }
 
    public EntityRef toReference(EntityBase entity) {
        return entity != null ? EntityRef.of(entity.getId(), entity.getName(), entity.getInfo()) : null;
    }
 
    public List<EntityRef> toReference(List<? extends EntityBase> entities) {
        if(CollectionUtils.isEmpty(entities))
            return List.of();
        return entities.stream().map(this::toReference).toList();
    }
 
    public Set<EntityRef> toReference(Set<? extends EntityBase> entities) {
        if(CollectionUtils.isEmpty(entities))
            return Set.of();
        return entities.stream().map(this::toReference).collect(Collectors.toSet());
    }
}