Guest User

Untitled

a guest
Feb 21st, 2018
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.15 KB | None | 0 0
  1. @Entity
  2. @Table(name = "foos")
  3. public class Foo {
  4.  
  5. @Id
  6. @GeneratedValue(generator = "foo-generator")
  7. @GenericGenerator(name = "foo-generator",
  8. parameters = {@Parameter(name = "min", value = "15"),
  9. @Parameter(name = "max", value = "25")},
  10. strategy = "org.learn.domain.generator.FooGenerator")
  11. private String id;
  12. }
  13.  
  14. public class FooGenerator implements IdentifierGenerator, Configurable {
  15.  
  16. @Autowired
  17. private FooRepository fooRepository;
  18.  
  19. private Integer min;
  20. private Integer max;
  21.  
  22. @Override
  23. public Serializable generate(SessionImplementor session, Object object) throws HibernateException {
  24. BigInteger minId = BigInteger.TEN.pow(min - 1);
  25. BigInteger maxId = BigInteger.TEN.pow(max).subtract(BigInteger.ONE);
  26.  
  27. List<String> invoiceIds = fooRepository.findFooIds();
  28. BigInteger currentId = invoiceIds.stream().map(BigInteger::new).max(Comparator.naturalOrder()).orElse(minId);
  29.  
  30. if (currentId.compareTo(maxId) >= 0) {
  31. throw new HibernateException("ID reached max digits limit");
  32. }
  33.  
  34. return maxId.add(BigInteger.valueOf(1)).toString();
  35. }
  36.  
  37. @Override
  38. public void configure(Type type, Properties properties, ServiceRegistry serviceRegistry) throws MappingException {
  39. min = Integer.valueOf(properties.getProperty("min"));
  40. max = Integer.valueOf(properties.getProperty("max"));
  41. }
  42. }
  43.  
  44. @Repository
  45. public interface FooRepository extends JpaRepository<Foo, String> {
  46.  
  47. @Query(value = "SELECT id FROM foos", nativeQuery = true)
  48. List<String> findFoosIds();
  49. }
  50.  
  51. ###
  52. # Database Settings
  53. ###
  54. spring.datasource.url=jdbc:h2:mem:omniva;DB_CLOSE_DELAY=-1;DB_CLOSE_ON_EXIT=FALSE
  55. spring.datasource.platform=h2
  56. spring.datasource.username = sa
  57. spring.datasource.password =
  58. spring.datasource.driverClassName = org.h2.Driver
  59. spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
  60. spring.jpa.show-sql = true
  61.  
  62. ###
  63. # H2 Settings
  64. ###
  65. spring.h2.console.enabled=true
  66. spring.h2.console.path=/console
  67. spring.h2.console.settings.trace=false
  68. spring.h2.console.settings.web-allow-others=false
  69.  
  70.  
  71. ###
  72. # Hibernate Settings
  73. ###
  74. spring.jpa.hibernate.ddl-auto = none
  75. spring.jpa.hibernate.use-new-id-generator-mappings=true
Add Comment
Please, Sign In to add comment