Guest User

Untitled

a guest
Oct 23rd, 2018
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.39 KB | None | 0 0
  1. @Repository
  2. public class PersonRepository extends SimpleCassandraRepository<Person, PersonKey> {
  3.  
  4. private final Session session;
  5. private final CassandraOperations cassandraTemplate;
  6. private final PreparedStatementCache cache = PreparedStatementCache.create();
  7.  
  8. public PersonRepository(
  9. Session session,
  10. CassandraEntityInformation entityInformation,
  11. CassandraOperations cassandraTemplate) {
  12. super(entityInformation, cassandraTemplate);
  13. this.session = session;
  14. this.cassandraTemplate = cassandraTemplate;
  15. }
  16.  
  17. // using ORM
  18. public List<Person> findByFirstNameAndDateOfBirth(String firstName, LocalDate dateOfBirth) {
  19. return cassandraTemplate
  20. .getCqlOperations()
  21. .query(
  22. findByFirstNameAndDateOfBirthQuery(firstName, dateOfBirth),
  23. (row, rowNum) -> cassandraTemplate.getConverter().read(Person.class, row));
  24. }
  25.  
  26. private BoundStatement findByFirstNameAndDateOfBirthQuery(
  27. String firstName, LocalDate dateOfBirth) {
  28. return CachedPreparedStatementCreator.of(
  29. cache,
  30. select()
  31. .all()
  32. .from("people_by_first_name")
  33. .where(eq("first_name", bindMarker("first_name")))
  34. .and(eq("date_of_birth", bindMarker("date_of_birth"))))
  35. .createPreparedStatement(session)
  36. .bind()
  37. .setString("first_name", firstName)
  38. .setDate("date_of_birth", toCqlDate(dateOfBirth));
  39. }
  40.  
  41. private com.datastax.driver.core.LocalDate toCqlDate(LocalDate date) {
  42. return com.datastax.driver.core.LocalDate.fromYearMonthDay(
  43. date.getYear(), date.getMonth().getValue(), date.getDayOfMonth());
  44. }
  45.  
  46. // without ORM
  47. public List<Person> findByFirstNameAndDateOfBirthWithoutORM(
  48. String firstName, LocalDate dateOfBirth) {
  49. return cassandraTemplate
  50. .getCqlOperations()
  51. .query(
  52. findByFirstNameAndDateOfBirthQuery(firstName, dateOfBirth),
  53. (row, rowNum) -> convert(row));
  54. }
  55.  
  56. private Person convert(Row row) {
  57. return new Person(
  58. new PersonKey(
  59. row.getString("first_name"),
  60. toLocalDate(row.getDate("date_of_birth")),
  61. row.getUUID("person_id")),
  62. row.getString("last_name"),
  63. row.getDouble("salary"));
  64. }
  65.  
  66. private LocalDate toLocalDate(com.datastax.driver.core.LocalDate date) {
  67. return LocalDate.of(date.getYear(), date.getMonth(), date.getDay());
  68. }
  69. }
Add Comment
Please, Sign In to add comment