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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package cn.flightfeather.supervision.domain.ds1.repository
 
import cn.flightfeather.supervision.domain.ds1.entity.City
import cn.flightfeather.supervision.domain.ds1.entity.District
import cn.flightfeather.supervision.domain.ds1.entity.Province
import cn.flightfeather.supervision.domain.ds1.entity.Town
import cn.flightfeather.supervision.domain.ds1.mapper.CityMapper
import cn.flightfeather.supervision.domain.ds1.mapper.DistrictMapper
import cn.flightfeather.supervision.domain.ds1.mapper.ProvinceMapper
import cn.flightfeather.supervision.domain.ds1.mapper.TownMapper
import org.springframework.stereotype.Repository
 
/**
 * 地域信息相关数据库操作
 */
@Repository
class RegionRep(
    private val provinceMapper: ProvinceMapper,
    private val cityMapper: CityMapper,
    private val districtMapper: DistrictMapper,
    private val townMapper: TownMapper,
) {
    private val cacheMap = mutableMapOf<String, Any?>()
 
    private fun<T : Any?> findCache(key: String?, findDb: () -> T?): T? {
        key ?: return null
        val s = cacheMap[key]
        return if (s == null) {
            val value = findDb()
            cacheMap[key] = value
            value
        } else {
            try {
                s as T
            } catch (e: Exception) {
                null
            }
        }
    }
 
    fun findProvince(name: String?): Province? {
        return findCache(name) {
            provinceMapper.selectOne(Province().apply { provincename = name })
        }
    }
 
    fun findCity(name: String?): City? {
        return findCache(name) {
            cityMapper.selectOne(City().apply { cityname = name })
        }
    }
 
    fun findDistrict(name: String?): District? {
        return findCache(name) {
            districtMapper.selectOne(District().apply { districtname = name })
        }
    }
 
    fun findTown(name: String?): Town? {
        return findCache(name) {
            townMapper.selectOne(Town().apply { townname = name })
        }
    }
}