如何覆盖唯一ID生成

时间:2018-02-21 21:40:02

标签: jpa spring-boot

我尝试实现自定义ID生成器,它将生成15-25位数的唯一编号(格式如:' 12345678901234567890')但是我卡在了我无法使用的地方{{1在fooRepository类中,因为它在该类中为null。我有一个FooGenerator,但我不想取得SessionImplementer字符串的替代方法,将它们转换为ResultSet,然后找到当前的最大ID。我如何能够更轻松,更优雅地找到当前最大id?

让Foo.class:

BigInteger

FooGenerator.class

@Entity
@Table(name = "foos")
public class Foo {

  @Id
  @GeneratedValue(generator = "foo-generator")
  @GenericGenerator(name = "foo-generator",
          parameters = {@Parameter(name = "min", value = "15"),
                  @Parameter(name = "max", value = "25")},
          strategy = "org.learn.domain.generator.FooGenerator")
  private String id;
}

FooRepository.class:

public class FooGenerator implements IdentifierGenerator, Configurable {

  @Autowired
  private FooRepository fooRepository;

  private Integer min;
  private Integer max;

  @Override
  public Serializable generate(SessionImplementor session, Object object) throws HibernateException {
    BigInteger minId = BigInteger.TEN.pow(min - 1);
    BigInteger maxId = BigInteger.TEN.pow(max).subtract(BigInteger.ONE);

    List<String> invoiceIds = fooRepository.findFooIds();
    BigInteger currentId = invoiceIds.stream().map(BigInteger::new).max(Comparator.naturalOrder()).orElse(minId);

    if (currentId.compareTo(maxId) >= 0) {
      throw new HibernateException("ID reached max digits limit");
    }

    return maxId.add(BigInteger.valueOf(1)).toString();
  }

  @Override
  public void configure(Type type, Properties properties, ServiceRegistry serviceRegistry) throws MappingException {
    min = Integer.valueOf(properties.getProperty("min"));
    max = Integer.valueOf(properties.getProperty("max"));
  }
}

application.properties

@Repository
public interface FooRepository extends JpaRepository<Foo, String> {

  @Query(value = "SELECT id FROM foos", nativeQuery = true)
  List<String> findFoosIds();
}

0 个答案:

没有答案