Prerequisites:
- Configured Spring Boot project version 1.3 or higher.
- Cassandra instance. On this instance, create a keyspace movies and in it table movie:
CREATE TABLE movie (and insert a couple of rows:
movieid text,
name text,
PRIMARY KEY ((movieid))
)
insert into movie(movieid, name) values('id1', 'Star Wars');
insert into movie(movieid, name) values('id2', 'Casablanca');
1. Add spring-data-cassandra dependency for Spring Boot:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-cassandra</artifactId>
</dependency>
2. Create a Java Bean with mapping to cassandra table:
@Table// add getters, setters, equals, hashCode
public class Movie {
@PrimaryKey
private String movieid;
@Column
private String name;
}
3. Create Repository Interface for your bean:
public interface MovieRepository extends TypedIdCassandraRepository<Movie,String> {
}
4. Add basic RestController which can be expanded on later:
@RestController5. Update resources/application.properties with Cassandra connection details:
public class MovieController {
@Autowired
MovieRepository movieRepository;
@RequestMapping(value="/movies")
public Iterable<Movie> getTable1(){
return movieRepository.findAll();
}
}
spring.data.cassandra.keyspace-name=...6. Add mappingContext bean to your configuration with the package with mapped beans:
spring.data.cassandra.contact-points=...
spring.data.cassandra.port=...
@Bean
public CassandraMappingContext mappingContext() throws Exception {
BasicCassandraMappingContext bean = new BasicCassandraMappingContext();
bean.setInitialEntitySet(CassandraEntityClassScanner.scan(("yourpackage")));
return bean;
}
7. Run your app. You should see the following at localhost:8080/movies:
[
{
"movieid": "id1",
"name": "Star Wars"
},
{
"movieid": "id2",
"name": "Casablanca"
}
]