### 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