← 中文资源

简体中文版本

代理键与自然键

代理键是系统生成的无业务语义标识符;自然键是看似稳定却会在现实压力下变更、泄漏与合并的真实属性。

阅读英文原文

概念定义

每行都需要可引用的身份,选择有二:无意义的系统值或有意义的业务值。业务重组时代理键永不变更;自然键自带解释性,但现实一旦移动,就拖着全部关系一起走。

工作机制

序列给出紧凑有序、契合聚集存储的键。随机 UUID 无需协调即可全局唯一,但把插入打散到各页;时间前缀的 UUID 变体恢复了局部性。雪花式 ID 打包时间戳与分片位,适合分布式生成。

使用场景

平衡的默认方案:代理键做主键,同时给自然标识符加唯一约束——关系稳定且唯一性仍被强制。引用类数据若确有不可变代码,可用纯自然键。

常见误区

用 email 或用户名当主键,现实变更时全模式级联改键。序列 ID 直接暴露在 URL 会泄漏业务量并开启枚举,应配不透明外部标识。只存代理键却省略自然键唯一约束,会静默积累重复;并购是自然键最大的压力测试——两个业务、一个供应商代码、两种含义。

代码示例

package main

import (
	"fmt"
	"math/bits"
)

type Bitset []uint64

func NewBitset(size int) Bitset {
	if size < 0 {
		panic("negative bitset size")
	}
	return make(Bitset, (size+63)/64)
}

func (b Bitset) Set(index int) {
	b[index/64] |= uint64(1) << (uint(index) % 64)
}

func (b Bitset) Clear(index int) {
	b[index/64] &^= uint64(1) << (uint(index) % 64)
}

func (b Bitset) Has(index int) bool {
	return b[index/64]&(uint64(1)<<(uint(index)%64)) != 0
}

func (b Bitset) Union(other Bitset) Bitset {
	size := len(b)
	if len(other) > size {
		size = len(other)
	}
	out := make(Bitset, size)
	for i := range out {
		var left, right uint64
		if i < len(b) {
			left = b[i]
		}
		if i < len(other) {
			right = other[i]
		}
		out[i] = left | right
	}
	return out
}

func (b Bitset) Intersect(other Bitset) Bitset {
	size := len(b)
	if len(other) < size {
		size = len(other)
	}
	out := make(Bitset, size)
	for i := range out {
		out[i] = b[i] & other[i]
	}
	return out
}

func (b Bitset) Count() int {
	total := 0
	for _, word := range b {
		total += bits.OnesCount64(word)
	}
	return total
}

func (b Bitset) Slice() []int {
	out := make([]int, 0, b.Count())
	for wordIndex, word := range b {
		for word != 0 {
			bit := bits.TrailingZeros64(word)
			out = append(out, wordIndex*64+bit)
			word &^= uint64(1) << uint(bit)
		}
	}
	return out
}

func main() {
	active := NewBitset(80)
	for _, id := range []int{1, 5, 64, 79} {
		active.Set(id)
	}
	blocked := NewBitset(80)
	blocked.Set(5)
	blocked.Set(9)

	fmt.Println("count:", active.Count())
	fmt.Println("has 64:", active.Has(64), "has 65:", active.Has(65))
	fmt.Println("members:", active.Slice())
	fmt.Println("union count:", active.Union(blocked).Count())
	fmt.Println("intersect:", active.Intersect(blocked).Slice())

	active.Clear(64)
	fmt.Println("after clear:", active.Count())
}
import java.util.List;
import java.util.Objects;

public class RecordClasses {

    public record Point(int x, int y) {
        public Point {
            if (x < 0 || y < 0) {
                throw new IllegalArgumentException(
                    "Coordinates must be non-negative");
            }
        }

        public double distanceTo(Point other) {
            return Math.sqrt(
                Math.pow(x - other.x, 2) +
                Math.pow(y - other.y, 2)
            );
        }
    }

    public record Rectangle(Point topLeft, Point bottomRight) {
        public int width() {
            return bottomRight.x() - topLeft.x();
        }
        public int height() {
            return bottomRight.y() - topLeft.y();
        }
        public int area() {
            return width() * height();
        }
    }

    public record Employee(
        String name,
        String department,
        double salary,
        List<String> skills
    ) {
        public Employee {
            Objects.requireNonNull(name);
            skills = List.copyOf(skills);
        }
    }

    public static void main(String[] args) {
        Point p1 = new Point(0, 0);
        Point p2 = new Point(3, 4);
        System.out.println("Distance: " + p1.distanceTo(p2));

        Rectangle rect = new Rectangle(p1, p2);
        System.out.println("Area: " + rect.area());

        Employee emp = new Employee("Alice", "Engineering", 95000,
            List.of("Java", "Python", "SQL"));
        System.out.println(emp);
    }
}