Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- @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;
- }
- 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"));
- }
- }
- @Repository
- public interface FooRepository extends JpaRepository<Foo, String> {
- @Query(value = "SELECT id FROM foos", nativeQuery = true)
- List<String> findFoosIds();
- }
- ###
- # Database Settings
- ###
- spring.datasource.url=jdbc:h2:mem:omniva;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
- spring.datasource.platform=h2
- spring.datasource.username = sa
- spring.datasource.password =
- spring.datasource.driverClassName = org.h2.Driver
- spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
- spring.jpa.show-sql = true
- ###
- # H2 Settings
- ###
- spring.h2.console.enabled=true
- spring.h2.console.path=/console
- spring.h2.console.settings.trace=false
- spring.h2.console.settings.web-allow-others=false
- ###
- # Hibernate Settings
- ###
- spring.jpa.hibernate.ddl-auto = none
- spring.jpa.hibernate.use-new-id-generator-mappings=true
Add Comment
Please, Sign In to add comment