### Example JSON response from PagedResourcesAssembler Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle Sample JSON output for a GET request to /persons with 30 Person instances, showing the next link, content array, and pageMetadata with size, totalElements, totalPages, and number. ```json { "links" : [ { "rel" : "next", "href" : "http://localhost:8080/persons?page=1&size=20 } ], "content" : [ … // 20 Person instances rendered here ], "pageMetadata" : { "size" : 20, "totalElements" : 30, "totalPages" : 2, "number" : 0 } } ``` -------------------------------- ### Configuration example for repository-impl-postfix Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle Namespace configuration for repository scanning. The first line uses the default postfix 'Impl', the second overrides it with 'FooBar'. ```xml ``` -------------------------------- ### Inject and use repository instance Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle Step 4: Get the repository instance injected and use it to execute query methods. ```java public class SomeClient { _@Autowired_ private PersonRepository repository; public void doSomething() { List persons = repository.findByLastname("Matthews"); } } ``` -------------------------------- ### Declaring a Jackson repository populator (Example 3.26) Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle XML configuration that uses the repository:jackson-populator element to load data from data.json. The _class attribute in the JSON determines the target type, and the infrastructure selects the appropriate repository. ```xml ``` -------------------------------- ### Sample annotation based repository configuration Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle Enables Spring Data repositories using the store-specific @EnableJpaRepositories annotation. The example uses JPA-specific annotation and EntityManagerFactory bean; adjust for your store module. ```java @Configuration @EnableJpaRepositories("com.acme.repositories") class ApplicationConfiguration { @Bean public EntityManagerFactory entityManagerFactory() { // … } } ``` -------------------------------- ### Query creation from method names - PersonRepository interface Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle Example repository interface showing how to derive queries from method names using prefixes like findBy, readBy, queryBy, countBy, getBy, and combining conditions with And/Or, IgnoreCase, and OrderBy. The actual parsing depends on the persistence store. ```java public interface PersonRepository extends Repository { List findByEmailAddressAndLastname(EmailAddress emailAddress, String lastname); // Enables the distinct flag for the query List findDistinctPeopleByLastnameOrFirstname(String lastname, String firstname); List findPeopleDistinctByLastnameOrFirstname(String lastname, String firstname); // Enabling ignoring case for an individual property List findByLastnameIgnoreCase(String lastname); // Enabling ignoring case for all suitable properties List findByLastnameAndFirstnameAllIgnoreCase(String lastname, String firstname); // Enabling static ORDER BY for a query List findByLastnameOrderByFirstnameAsc(String lastname); List findByLastnameOrderByFirstnameDesc(String lastname); } ``` -------------------------------- ### Data defined in JSON (Example 3.25) Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle JSON data file (data.json) used to populate repositories. Each object includes a _class attribute that determines the target type for deserialization. ```json [ { "_class" : "com.acme.Person", "firstname" : "Dave", "lastname" : "Matthews" }, { "_class" : "com.acme.Person", "firstname" : "Carter", "lastname" : "Beauford" } ] ``` -------------------------------- ### Declaring an unmarshalling repository populator using JAXB (Example 3.27) Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle XML configuration using repository:unmarshaller-populator with an OXM unmarshaller (JAXB) to populate repositories from XML data. Requires an oxm:jaxb2-marshaller with a contextPath. ```xml ``` -------------------------------- ### Query multiple rows with select() and map to POJO Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle Uses cassandraOperations.select(cqlAll, Person.class) to execute a CQL query and map all results to a list of Person objects. The example iterates over the results and logs each person's name and id. ```java String cqlAll = "select * from person"; List results = cassandraOperations.select(cqlAll, Person.class); for (Person p : results) { LOG.info(String.format("Found People with Name [%s] for id [%s]", p.getName(), p.getId())); } ``` -------------------------------- ### Autowire CassandraOperations Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle Autowire the CassandraOperations interface to get a CassandraTemplate bean. Assumes only one bean of type CassandraOperations exists in the ApplicationContext. ```java @Autowired private CassandraOperations cassandraOperations; ``` -------------------------------- ### Query a single row with selectOne() and map to POJO Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle Uses cassandraOperations.selectOne(cqlOne, Person.class) to execute a CQL query that returns a single row and maps it to a Person object. The example logs the found person's name and id. ```java String cqlOne = "select * from person where id = '123123123'"; Person p = cassandraOperations.selectOne(cqlOne, Person.class); LOG.info(String.format("Found Person with Name [%s] for id [%s]", p.getName(), p.getId())); ``` -------------------------------- ### Selectively exposing CRUD methods with @NoRepositoryBean Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle Example 3.5: Define a base repository interface with @NoRepositoryBean to selectively expose CRUD methods. The intermediate interface must be annotated with @NoRepositoryBean to prevent Spring Data from creating instances for it. ```java _@NoRepositoryBean_ interface MyBaseRepository extends Repository { T findOne(ID id); T save(T entity); } interface UserRepository extends MyBaseRepository { User findByEmailAddress(EmailAddress emailAddress); } ``` -------------------------------- ### Create and drop table using execute() with different API objects Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle Shows two execute() calls: first with a CQL string to create a table, then with a DropTableSpecification object to drop it. Demonstrates passing different API objects to the execute() method. ```java cassandraOperations.execute("create table test_table (id uuid primary key, event text)"); ``` ```java DropTableSpecification dropper = DropTableSpecification.dropTable("test_table"); cassandraOperations.execute(dropper); ``` -------------------------------- ### Create CassandraApp main application Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle A main application that connects to Cassandra, inserts a Person, queries it, and truncates the table using CassandraTemplate. ```java package org.spring.cassandra.example; import java.net.InetAddress; import java.net.UnknownHostException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.data.cassandra.core.CassandraOperations; import org.springframework.data.cassandra.core.CassandraTemplate; import com.datastax.driver.core.Cluster; import com.datastax.driver.core.Session; import com.datastax.driver.core.querybuilder.QueryBuilder; import com.datastax.driver.core.querybuilder.Select; public class CassandraApp { private static final Logger LOG = LoggerFactory.getLogger(CassandraApp.class); private static Cluster cluster; private static Session session; public static void main(String[] args) { try { cluster = Cluster.builder().addContactPoints(InetAddress.getLocalHost()).build(); session = cluster.connect("mykeyspace"); CassandraOperations cassandraOps = new CassandraTemplate(session); cassandraOps.insert(new Person("1234567890", "David", 40)); Select s = QueryBuilder.select().from("person"); s.where(QueryBuilder.eq("id", "1234567890")); LOG.info(cassandraOps.queryForObject(s, Person.class).getId()); cassandraOps.truncate("person"); } catch (UnknownHostException e) { e.printStackTrace(); } } } ``` -------------------------------- ### Manual wiring of custom implementations (I) Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle Declare a bean with the name following the convention (e.g., 'userRepositoryImpl') to manually wire the custom implementation. ```xml ``` -------------------------------- ### Configure Spring with JavaConfig using @EnableJpaRepositories Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle Step 3 (JavaConfig): Set up Spring to create proxy instances for repository interfaces using @EnableJpaRepositories. The package is not configured explicitly; the package of the annotated class is used by default. ```java import org.springframework.data.jpa.repository.config.EnableJpaRepositories; _@EnableJpaRepositories_ class Config {} ``` -------------------------------- ### Java Configuration for Cassandra using AnnotationConfigApplicationContext Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle Defines a minimal Spring Data Cassandra configuration class. It sets up a Cassandra cluster, mapping context, converter, session, and template. The configuration reads properties from cassandra.properties and enables Cassandra repositories in the specified package. ```java package org.spring.cassandra.example.config; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.core.env.Environment; import org.springframework.data.cassandra.config.CassandraClusterFactoryBean; import org.springframework.data.cassandra.config.CassandraSessionFactoryBean; import org.springframework.data.cassandra.config.SchemaAction; import org.springframework.data.cassandra.convert.CassandraConverter; import org.springframework.data.cassandra.convert.MappingCassandraConverter; import org.springframework.data.cassandra.core.CassandraOperations; import org.springframework.data.cassandra.core.CassandraTemplate; import org.springframework.data.cassandra.mapping.BasicCassandraMappingContext; import org.springframework.data.cassandra.mapping.CassandraMappingContext; import org.springframework.data.cassandra.repository.config.EnableCassandraRepositories; @Configuration @PropertySource(value = { "classpath:cassandra.properties" }) @EnableCassandraRepositories(basePackages = { "org.spring.cassandra.example.repo" }) public class CassandraConfig { private static final Logger LOG = LoggerFactory.getLogger(CassandraConfig.class); @Autowired private Environment env; @Bean public CassandraClusterFactoryBean cluster() { CassandraClusterFactoryBean cluster = new CassandraClusterFactoryBean(); cluster.setContactPoints(env.getProperty("cassandra.contactpoints")); cluster.setPort(Integer.parseInt(env.getProperty("cassandra.port"))); return cluster; } @Bean public CassandraMappingContext mappingContext() { return new BasicCassandraMappingContext(); } @Bean public CassandraConverter converter() { return new MappingCassandraConverter(mappingContext()); } @Bean public CassandraSessionFactoryBean session() throws Exception { CassandraSessionFactoryBean session = new CassandraSessionFactoryBean(); session.setCluster(cluster().getObject()); session.setKeyspaceName(env.getProperty("cassandra.keyspace")); session.setConverter(converter()); session.setSchemaAction(SchemaAction.NONE); return session; } @Bean public CassandraOperations cassandraTemplate() throws Exception { return new CassandraTemplate(session().getObject()); } } ``` -------------------------------- ### Configure Spring with XML using jpa:repositories Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle Step 3 (XML): Set up Spring to create proxy instances for repository interfaces using the JPA namespace. For other stores, change the namespace accordingly (e.g., mongodb). ```xml ``` -------------------------------- ### Using PagingAndSortingRepository to access second page Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle Shows how to retrieve the second page of User entities with a page size of 20 using a PageRequest. ```java PagingAndSortingRepository repository = // … get access to a bean Page users = repository.findAll(new PageRequest(1, 20)); ``` -------------------------------- ### Simplified controller with Pageable parameter Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle Shows the simplified controller after configuring the resolver, using a Pageable parameter directly without manual parsing. ```java _@Controller_ _@RequestMapping("/users")_ public class UserController { _@RequestMapping_ public String showUsers(Model model, Pageable pageable) { model.addAttribute("users", userRepository.findAll(pageable)); return "users"; } } ``` -------------------------------- ### Standalone usage of repository factory Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle Shows how to use RepositoryFactorySupport outside a Spring container, e.g., in CDI environments. Requires Spring libraries on the classpath. ```java RepositoryFactorySupport factory = … // Instantiate factory here UserRepository repository = factory.getRepository(UserRepository.class); ``` -------------------------------- ### Declare query method on repository interface Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle Step 2: Declare query methods on the repository interface. ```java List findByLastname(String lastname); ``` -------------------------------- ### Manual pagination with HttpServletRequest Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle Shows the less desirable approach where the controller manually parses 'page' and 'pageSize' request parameters to create a PageRequest. Omits failure handling and adds boilerplate. ```java _@Controller_ _@RequestMapping("/users")_ public class UserController { // DI code omitted _@RequestMapping_ public String showUsers(Model model, HttpServletRequest request) { int page = Integer.parseInt(request.getParameter("page")); int pageSize = Integer.parseInt(request.getParameter("pageSize")); Pageable pageable = new PageRequest(page, pageSize); model.addAttribute("users", userService.getUsers(pageable)); return "users"; } } ``` -------------------------------- ### Using the custom factory with the namespace Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle Configures the custom repository factory via the Spring XML namespace by setting the factory-class attribute on the repositories element. This tells the repository infrastructure to use the custom factory implementation. ```xml ``` -------------------------------- ### Spring MVC controller with manual repository lookup Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle Shows the boilerplate approach of resolving a User entity from a path variable using UserRepository.findOne(). Requires a repository dependency and null checks for id and user. ```java _@Controller_ _@RequestMapping("/users")_ public class UserController { private final UserRepository userRepository; _@Autowired_ public UserController(UserRepository userRepository) { Assert.notNull(repository, "Repository must not be null!"); userRepository = userRepository; } _@RequestMapping("/{id}")_ public String showUserForm(_@PathVariable("id")_ Long id, Model model) { // Do null check for id User user = userRepository.findOne(id); // Do null check for user model.addAttribute("user", user); return "user"; } } ``` -------------------------------- ### Using multiple Pageable arguments with @Qualifier Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle Shows a method signature that uses two Pageable arguments distinguished by @Qualifier. Request parameters must be prefixed with the qualifier, e.g., foo_page and bar_page. ```java public String showUsers(Model model, @Qualifier("foo") Pageable first, @Qualifier("bar") Pageable second) { … } ``` -------------------------------- ### Enable Spring Data web support with @EnableSpringDataWebSupport Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle Use this JavaConfig configuration class to enable Spring Data web support. Requires Spring 3.2 or later and Spring MVC JARs on the classpath. It also detects Spring HATEOAS and registers integration components if present. ```java @Configuration @EnableWebMvc @EnableSpringDataWebSupport class WebConfiguration { } ``` -------------------------------- ### Enable Spring Data web support in XML with HateoasAwareSpringDataWebConfiguration Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle?%3F%3F= Use this XML bean definition to enable Spring Data web support when using Spring HATEOAS. Register this bean *instead* of the former (SpringDataWebConfiguration) when using Spring HATEOAS. ```xml ``` -------------------------------- ### XML configuration for Spring Data repositories Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle Defines a base package for Spring to scan for repository interfaces. The repositories element registers FactoryBeans for each interface found, with bean names derived from the interface name (e.g., UserRepository becomes userRepository). The base-package attribute supports wildcards. ```xml ``` -------------------------------- ### Changes to the basic repository interface Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle Extend the standard repository interface with the custom interface to combine CRUD and custom functionality. ```java public interface UserRepository extends CrudRepository, UserRepositoryCustom { // Declare query methods here } ``` -------------------------------- ### JavaConfig configuration for DomainClassConverter Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle Extends WebMvcConfigurationSupport and provides a DomainClassConverter bean using the mvcConversionService() method from the superclass. ```java class WebConfiguration extends WebMvcConfigurationSupport { // Other configuration omitted _@Bean_ public DomainClassConverter domainClassConverter() { return new DomainClassConverter(mvcConversionService()); } } ``` -------------------------------- ### Using PagedResourcesAssembler as controller method argument Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle?%3F%3F= Controller method that accepts a Pageable and PagedResourcesAssembler, retrieves a Page from the repository, and returns a ResponseEntity with PagedResources. Requires Spring HATEOAS and Spring Data Cassandra. ```java @Controller class PersonController { @Autowired PersonRepository repository; @RequestMapping(value = "/persons", method = RequestMethod.GET) HttpEntity> persons(Pageable pageable, PagedResourcesAssembler assembler) { Page persons = repository.findAll(pageable); return new ResponseEntity<>(assembler.toResources(persons), HttpStatus.OK); } } ``` -------------------------------- ### Custom repository base class Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle Implements the intermediate interface by extending SimpleJpaRepository. This class acts as a custom base class for repository proxies. It includes two constructors to choose from and uses the recommended method for accessing inherited class dependencies. ```java public class MyRepositoryImpl extends SimpleJpaRepository implements MyRepository { private EntityManager entityManager; // There are two constructors to choose from, either can be used. public MyRepositoryImpl(Class domainClass, EntityManager entityManager) { super(domainClass, entityManager); // This is the recommended method for accessing inherited class dependencies. this.entityManager = entityManager; } public void sharedCustomMethod(ID id) { // implementation goes here } } ``` -------------------------------- ### Using PagedResourcesAssembler as controller method argument Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle Controller method that accepts a Pageable and PagedResourcesAssembler, retrieves a Page from the repository, and returns a ResponseEntity with PagedResources. Requires Spring HATEOAS configuration to enable the assembler as a controller argument. ```java @Controller class PersonController { @Autowired PersonRepository repository; @RequestMapping(value = "/persons", method = RequestMethod.GET) HttpEntity> persons(Pageable pageable, PagedResourcesAssembler assembler) { Page persons = repository.findAll(pageable); return new ResponseEntity<>(assembler.toResources(persons), HttpStatus.OK); } } ``` -------------------------------- ### Multiple inserts using ingest() Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle Uses CassandraOperations.ingest() to insert multiple rows with bind markers. The method prepares a static PreparedStatement once and executes asynchronously for high performance. ```java String cqlIngest = "insert into person (id, name, age) values (?, ?, ?)"; List person1 = new ArrayList(); person1.add("10000"); person1.add("David"); person1.add(40); List person2 = new ArrayList(); person2.add("10001"); person2.add("Roger"); person2.add(65); List> people = new ArrayList>(); people.add(person1); people.add(person2); cassandraOperations.ingest(cqlIngest, people); ``` -------------------------------- ### Execute asynchronous CQL command with AsynchronousQueryListener Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle Use executeAsynchronously() to run a CQL command and handle the result via AsynchronousQueryListener. The listener's onQueryComplete() receives a ResultSetFuture; here it logs a message. Requires a CassandraOperations instance and a logger. ```java cassandraOperations.executeAsynchronously("delete from person where id = '123123123'", new AsynchronousQueryListener() { public void onQueryComplete(ResultSetFuture rsf) { LOG.info("Async Query Completed"); } }); ``` -------------------------------- ### Enable Spring Data web support in XML with SpringDataWebConfiguration Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle Register SpringDataWebConfiguration as a Spring bean to enable web support in XML configuration. Use HateoasAwareSpringDataWebConfiguration instead when using Spring HATEOAS. ```xml ``` -------------------------------- ### Implementation of custom repository functionality Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle Provide the implementation of the custom interface. The implementation can be a regular Spring bean and does not depend on Spring Data. ```java class UserRepositoryImpl implements UserRepositoryCustom { public void someCustomMethod(User user) { // Your custom implementation } } ``` -------------------------------- ### Declare repository interface extending Repository Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle Step 1: Declare an interface extending Repository or a subinterface, typed to the domain class and ID type. ```java public interface PersonRepository extends Repository { … } ``` -------------------------------- ### Insert a row using raw CQL Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle Executes a raw CQL insert statement via CassandraOperations.execute(). ```java String cql = "insert into person (id, name, age) values ('123123123', 'Alison', 39)"; cassandraOperations.execute(cql); ``` -------------------------------- ### Query using DataStax QueryBuilder.Select Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle Builds a query using QueryBuilder.select().from("person") and adds a where clause with QueryBuilder.eq("id", "123123123"). The resulting Select object is passed to cassandraOperations.selectOne() to map the result to a Person. ```java Select select = QueryBuilder.select().from("person"); select.where(QueryBuilder.eq("id", "123123123")); Person p = cassandraOperations.selectOne(select, Person.class); LOG.info(String.format("Found Person with Name [%s] for id [%s]", p.getName(), p.getId())); ``` -------------------------------- ### Multiple Pageables with @Qualifier Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle Shows a method signature using @Qualifier to distinguish multiple Pageable parameters, requiring request parameters prefixed with the qualifier. ```java public String showUsers(Model model, _@Qualifier("foo")_ Pageable first, _@Qualifier("bar")_ Pageable second) { … } ``` -------------------------------- ### Configure PageableHandlerArgumentResolver with JavaConfig Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle Shows how to register PageableHandlerArgumentResolver by overriding configureMessageConverters in a WebMvcConfigurationSupport subclass. ```java @Configuration public class WebConfig extends WebMvcConfigurationSupport { @Override public void configureMessageConverters(List> converters) { converters.add(new PageableHandlerArgumentResolver()); } } ``` -------------------------------- ### Truncate a table using raw CQL Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle Executes a raw CQL truncate statement via CassandraOperations.execute(). ```java String cql = "truncate person"; cassandraOperations.execute(cql); ``` -------------------------------- ### XML configuration for Spring Data Cassandra Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle Basic XML configuration for connecting to Cassandra using Spring Data Cassandra. It loads the properties file, defines the cluster, session, mapping, converter, template, and optionally scans for repositories. All elements use default bean names for clean configuration. ```xml ``` -------------------------------- ### PagingAndSortingRepository interface Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle Extends CrudRepository to add pagination and sorting support. Provides findAll(Sort) and findAll(Pageable) methods. ```java public interface PagingAndSortingRepository extends CrudRepository { Iterable findAll(Sort sort); Page findAll(Pageable pageable); } ``` -------------------------------- ### DetailedLoginEventKey complex composite primary key class Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle Java class for a complex composite primary key with 5 columns: 2 partition keys and 3 clustering keys. Uses @PrimaryKeyClass and @PrimaryKeyColumn annotations. Getters/setters, hashCode, and equals are omitted for brevity. ```java package org.spring.cassandra.example; import java.io.Serializable; import java.util.Date; import org.springframework.cassandra.core.Ordering; import org.springframework.cassandra.core.PrimaryKeyType; import org.springframework.data.cassandra.mapping.PrimaryKeyClass; import org.springframework.data.cassandra.mapping.PrimaryKeyColumn; @PrimaryKeyClass public class DetailedLoginEventKey implements Serializable { @PrimaryKeyColumn(name = "person_id", ordinal = 0, type = PrimaryKeyType.PARTITIONED) private String personId; @PrimaryKeyColumn(name = "wks_id", ordinal = 1, type = PrimaryKeyType.PARTITIONED) private String workstationId; @PrimaryKeyColumn(ordinal = 2, type = PrimaryKeyType.CLUSTERED, ordering = Ordering.ASCENDING) private Date application; @PrimaryKeyColumn(name = "event_code", ordinal = 3, type = PrimaryKeyType.CLUSTERED, ordering = Ordering.ASCENDING) private Date eventCode; @PrimaryKeyColumn(name = "event_time", ordinal = 4, type = PrimaryKeyType.CLUSTERED, ordering = Ordering.DESCENDING) private Date eventTime; ... } ``` -------------------------------- ### LoginEvent entity class with composite primary key Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle Java class mapping the login_event table. It uses @Table and @PrimaryKey annotations, with the composite key as an attribute and additional columns for event_code and ip_address. ```java package org.spring.cassandra.example; import org.springframework.data.cassandra.mapping.Column; import org.springframework.data.cassandra.mapping.PrimaryKey; import org.springframework.data.cassandra.mapping.Table; @Table(value = "login_event") public class LoginEvent { @PrimaryKey private LoginEventKey pk; @Column(value = "event_code") private int eventCode; @Column(value = "ip_address") private String ipAddress; public LoginEventKey getPk() { return pk; } public void setPk(LoginEventKey pk) { this.pk = pk; } public int getEventCode() { return eventCode; } public void setEventCode(int eventCode) { this.eventCode = eventCode; } public String getIpAddress() { return ipAddress; } public void setIpAddress(String ipAddress) { this.ipAddress = ipAddress; } } ``` -------------------------------- ### Add Spring Milestone repository to pom.xml Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle Add the Spring Milestone repository location to the pom.xml at the same level as the dependencies element. ```xml spring-milestone Spring Maven MILESTONE Repository http://repo.spring.io/libs-milestone ``` -------------------------------- ### Interface for custom repository functionality Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle Define an interface with custom methods to be implemented by a custom repository class. This interface is later extended by the main repository interface. ```java interface UserRepositoryCustom { public void someCustomMethod(User user); } ``` -------------------------------- ### Truncate a table using truncate() Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle Uses CassandraOperations.truncate() to truncate the person table. ```java cassandraOperations.truncate("person"); ``` -------------------------------- ### Controller method specific defaults with @PageableDefaults Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle Shows how to set controller method specific defaults for Pageable using @PageableDefaults annotation attributes. ```java public String showUsers(Model model, _@PageableDefaults(pageNumber = 0, value = 30)_ Pageable pageable) { … } ``` -------------------------------- ### XML configuration for DomainClassConverter Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle Declares a DomainClassConverter bean and pipes the ConversionService into its constructor. Used with Spring 3.0+ conversion infrastructure. ```xml ``` -------------------------------- ### Autowire CassandraOperations with @Qualifier Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle Use @Qualifier to select a specific CassandraTemplate bean when multiple beans of type CassandraOperations exist, such as when working with multiple keyspaces. ```java @Autowired @Qualifier("myTemplateBeanId") private CassandraOperations cassandraOperations; ``` -------------------------------- ### Custom repository factory bean Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle Defines a custom RepositoryFactoryBean that produces a custom RepositoryFactory. The factory provides MyRepositoryImpl as the implementation for interfaces extending Repository, replacing SimpleJpaRepository. The inner factory overrides getTargetRepository and getRepositoryBaseClass. ```java public class MyRepositoryFactoryBean, T, I extends Serializable> extends JpaRepositoryFactoryBean { protected RepositoryFactorySupport createRepositoryFactory(EntityManager entityManager) { return new MyRepositoryFactory(entityManager); } private static class MyRepositoryFactory extends JpaRepositoryFactory { private EntityManager entityManager; public MyRepositoryFactory(EntityManager entityManager) { super(entityManager); this.entityManager = entityManager; } protected Object getTargetRepository(RepositoryMetadata metadata) { return new MyRepositoryImpl((Class) metadata.getDomainClass(), entityManager); } protected Class getRepositoryBaseClass(RepositoryMetadata metadata) { // The RepositoryMetadata can be safely ignored, it is used by the JpaRepositoryFactory //to check for QueryDslJpaRepository's which is out of scope. return MyRepository.class; } } } ``` -------------------------------- ### Configure PageableHandlerArgumentResolver with XML Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle Shows XML configuration to register PageableHandlerArgumentResolver as a custom argument resolver on RequestMappingHandlerAdapter. ```xml ``` -------------------------------- ### Spring MVC controller with PropertyEditor-based binding Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle After configuring the DomainClassPropertyEditorRegistrar, the controller can directly accept a User parameter from the path variable, eliminating boilerplate repository lookups. ```java _@Controller_ _@RequestMapping("/users")_ public class UserController { _@RequestMapping("/{id}")_ public String showUserForm(_@PathVariable("id")_ User user, Model model) { model.addAttribute("user", user); return "userForm"; } } ``` -------------------------------- ### Set Spring framework version in pom.xml Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle Change the Spring framework version to 3.2.8.RELEASE in the pom.xml. ```xml 3.2.8.RELEASE ``` -------------------------------- ### LoginEventKey composite primary key class Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle Java class representing the composite primary key for the login_event table. It implements Serializable and provides hashCode() and equals() as required. Uses @PrimaryKeyClass and @PrimaryKeyColumn annotations with partition and clustering types. ```java package org.spring.cassandra.example; import java.io.Serializable; import java.util.Date; import org.springframework.cassandra.core.Ordering; import org.springframework.cassandra.core.PrimaryKeyType; import org.springframework.data.cassandra.mapping.PrimaryKeyClass; import org.springframework.data.cassandra.mapping.PrimaryKeyColumn; @PrimaryKeyClass public class LoginEventKey implements Serializable { @PrimaryKeyColumn(name = "person_id", ordinal = 0, type = PrimaryKeyType.PARTITIONED) private String personId; @PrimaryKeyColumn(name = "event_time", ordinal = 1, type = PrimaryKeyType.CLUSTERED, ordering = Ordering.DESCENDING) private Date eventTime; public String getPersonId() { return personId; } public void setPersonId(String personId) { this.personId = personId; } public Date getEventTime() { return eventTime; } public void setEventTime(Date eventTime) { this.eventTime = eventTime; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((eventTime == null) ? 0 : eventTime.hashCode()); result = prime * result + ((personId == null) ? 0 : personId.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; LoginEventKey other = (LoginEventKey) obj; if (eventTime == null) { if (other.eventTime != null) return false; } else if (!eventTime.equals(other.eventTime)) return false; if (personId == null) { if (other.personId != null) return false; } else if (!personId.equals(other.personId)) return false; return true; } } ``` -------------------------------- ### Insert a record with an annotated POJO Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle Uses CassandraOperations.insert() to insert a single Person object. Requires a configured cassandraTemplate. ```java cassandraOperations.insert(new Person("123123123", "Alison", 39)); ``` -------------------------------- ### Create Person entity class Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle A simple Person class annotated with @Table and @PrimaryKey for Cassandra persistence. ```java package org.spring.cassandra.example; import org.springframework.data.cassandra.mapping.PrimaryKey; import org.springframework.data.cassandra.mapping.Table; @Table public class Person { @PrimaryKey private String id; private String name; private int age; public Person(String id, String name, int age) { this.id = id; this.name = name; this.age = age; } public String getId() { return id; } public String getName() { return name; } public int getAge() { return age; } @Override public String toString() { return "Person [id=" + id + ", name=" + name + ", age=" + age + "]"; } } ``` -------------------------------- ### Add spring-data-cassandra dependency to pom.xml Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle Add the spring-data-cassandra 1.0.0.RELEASE dependency to the Maven pom.xml dependencies section. ```xml org.springframework.data spring-data-cassandra 1.0.0.RELEASE ``` -------------------------------- ### Update a row using raw CQL Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle Executes a raw CQL update statement via CassandraOperations.execute(). ```java String cql = "update person set age = 35 where id = '123123123'"; cassandraOperations.execute(cql); ``` -------------------------------- ### Insert a row using QueryBuilder.Insert Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle Builds an insert statement with the DataStax QueryBuilder, sets consistency level to ONE, and executes it via CassandraOperations. ```java Insert insert = QueryBuilder.insertInto("person"); insert.setConsistencyLevel(ConsistencyLevel.ONE); insert.value("id", "123123123"); insert.value("name", "Alison"); insert.value("age", 39); cassandraOperations.execute(insert); ``` -------------------------------- ### cassandra.properties: Externalize Cassandra connection properties Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle Defines the minimal required fields for connecting to Cassandra: contact points and keyspace, with port added for clarity. This file is loaded into the Spring Context via a property placeholder in the XML configuration. ```properties cassandra.contactpoints=10.1.55.80,10.1.55.81 cassandra.port=9042 cassandra.keyspace=showcase ``` -------------------------------- ### Derived Delete Query Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle Defines repository methods that derive delete queries from method names deleteByLastname and removeByLastname. ```java public interface UserRepository extends CrudRepository { Long deleteByLastname(String lastname); List removeByLastname(String lastname); } ``` -------------------------------- ### CDI injection of PersonRepository Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle Shows how to obtain a Spring Data Cassandra repository via CDI by declaring an @Inject-ed property. The container provides a proxy for the repository type. ```java class RepositoryClient { _@Inject_ PersonRepository repository; public void businessMethod() { List people = repository.findAll(); } } ``` -------------------------------- ### Truncate a table using QueryBuilder.Truncate Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle Builds a truncate statement with the DataStax QueryBuilder and executes it. ```java Truncate truncate = QueryBuilder.truncate("person"); cassandraOperations.execute(truncate); ``` -------------------------------- ### Query with custom RowMapper Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle Uses cassandraOperations.query(cqlAll, new RowMapper()) to execute a CQL query and map each row manually. The RowMapper implementation extracts id, name, and age from the Row and constructs a Person object. The results are then iterated and logged. ```java String cqlAll = "select * from person"; List results = cassandraOperations.query(cqlAll, new RowMapper() { public Person mapRow(Row row, int rowNum) throws DriverException { Person p = new Person(row.getString("id"), row.getString("name"), row.getInt("age")); return p; } }); for (Person p : results) { LOG.info(String.format("Found People with Name [%s] for id [%s]", p.getName(), p.getId())); } ``` -------------------------------- ### Using Pageable as controller method argument Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle Shows how to use Pageable as a controller method argument. Spring MVC derives a Pageable instance from request parameters (page, size, sort) with default configuration. The default Pageable is equivalent to new PageRequest(0, 20) and can be customized with @PageableDefaults. ```java @Controller @RequestMapping("/users") public class UserController { @Autowired UserRepository repository; @RequestMapping public String showUsers(Model model, Pageable pageable) { model.addAttribute("users", repository.findAll(pageable)); return "users"; } } ``` -------------------------------- ### CQL table definition for login_event with composite primary key Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle Defines the Cassandra table 'login_event' with a composite primary key (person_id, event_time) and clustering order by event_time descending. This is the CQL schema that the Java POJOs map to. ```cql create table login_event( person_id text, event_time timestamp, event_code int, ip_address text, primary key (person_id, event_time)) with CLUSTERING ORDER BY (event_time DESC) ; ``` -------------------------------- ### Delete a row using raw CQL Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle Executes a raw CQL delete statement via CassandraOperations.execute(). ```java String cql = "delete from person where id = '123123123'"; cassandraOperations.execute(cql); ``` -------------------------------- ### Lookup CassandraTemplate Bean from ApplicationContext Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle Retrieve the CassandraTemplate bean directly from the ApplicationContext by its bean name and expected type. ```java CassandraOperations cassandraOperations = applicationContext.getBean("cassandraTemplate", CassandraOperations.class); ``` -------------------------------- ### XML configuration for DomainClassPropertyEditorRegistrar Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle Configures Spring MVC's AnnotationMethodHandlerAdapter with a ConfigurableWebBindingInitializer that registers the DomainClassPropertyEditorRegistrar. Used for Spring versions before 3.0. ```xml ``` -------------------------------- ### CrudRepository interface Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle Defines the core CRUD operations for entities. Extends Repository and provides methods like save, findOne, findAll, count, delete, and exists. ```java public interface CrudRepository extends Repository { S save(S entity); T findOne(ID primaryKey); Iterable findAll(); Long count(); void delete(T entity); boolean exists(ID primaryKey); // … more functionality omitted. } ``` -------------------------------- ### Using exclude-filter element Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle Excludes interfaces matching the given regex from being instantiated as repositories. The semantics are equivalent to Spring's context namespace elements. ```xml ``` -------------------------------- ### Spring MVC controller using domain types in method signatures Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle Shows how to use a domain type (User) directly in a controller method signature. Spring MVC resolves the User instance from the path variable using the DomainClassConverter, which requires the repository to implement CrudRepository. ```java @Controller @RequestMapping("/users") public class UserController { @RequestMapping("/{id}") public String showUserForm(@PathVariable("id") User user, Model model) { model.addAttribute("user", user); return "userForm"; } } ``` -------------------------------- ### Derived Count Query Source: https://docs.spring.io/spring-data/cassandra/docs/1.0.0.RELEASE/reference/htmlsingle Defines a repository method that derives a count query from the method name countByLastname. ```java public interface UserRepository extends CrudRepository { Long countByLastname(String lastname); } ```