minor cleanup

This commit is contained in:
eugenp 2015-12-24 11:39:47 +02:00
parent 41910d7bdf
commit 62fd1e6eda
11 changed files with 269 additions and 115 deletions

View File

@ -0,0 +1,31 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" output="target/classes" path="src/main/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" output="target/test-classes" path="src/test/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.7">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="output" path="target/classes"/>
</classpath>

View File

@ -0,0 +1,29 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>spring-data-cassandra</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.m2e.core.maven2Builder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.springframework.ide.eclipse.core.springbuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.springframework.ide.eclipse.core.springnature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.m2e.core.maven2Nature</nature>
</natures>
</projectDescription>

View File

@ -17,8 +17,8 @@ import org.springframework.data.cassandra.repository.config.EnableCassandraRepos
@PropertySource(value = { "classpath:cassandra.properties" }) @PropertySource(value = { "classpath:cassandra.properties" })
@EnableCassandraRepositories(basePackages = "org.baeldung.spring.data.cassandra.repository") @EnableCassandraRepositories(basePackages = "org.baeldung.spring.data.cassandra.repository")
public class CassandraConfig extends AbstractCassandraConfiguration { public class CassandraConfig extends AbstractCassandraConfiguration {
private static final Log LOGGER = LogFactory.getLog(CassandraConfig.class); private static final Log LOGGER = LogFactory.getLog(CassandraConfig.class);
@Autowired @Autowired
private Environment environment; private Environment environment;
@ -27,15 +27,17 @@ public class CassandraConfig extends AbstractCassandraConfiguration {
return environment.getProperty("cassandra.keyspace"); return environment.getProperty("cassandra.keyspace");
} }
@Override
@Bean @Bean
public CassandraClusterFactoryBean cluster() { public CassandraClusterFactoryBean cluster() {
CassandraClusterFactoryBean cluster = new CassandraClusterFactoryBean(); final CassandraClusterFactoryBean cluster = new CassandraClusterFactoryBean();
cluster.setContactPoints(environment.getProperty("cassandra.contactpoints")); cluster.setContactPoints(environment.getProperty("cassandra.contactpoints"));
cluster.setPort(Integer.parseInt(environment.getProperty("cassandra.port"))); cluster.setPort(Integer.parseInt(environment.getProperty("cassandra.port")));
LOGGER.info("Cluster created with contact points [" + environment.getProperty("cassandra.contactpoints") + "] " + "& port [" + Integer.parseInt(environment.getProperty("cassandra.port")) + "]."); LOGGER.info("Cluster created with contact points [" + environment.getProperty("cassandra.contactpoints") + "] " + "& port [" + Integer.parseInt(environment.getProperty("cassandra.port")) + "].");
return cluster; return cluster;
} }
@Override
@Bean @Bean
public CassandraMappingContext cassandraMapping() throws ClassNotFoundException { public CassandraMappingContext cassandraMapping() throws ClassNotFoundException {
return new BasicCassandraMappingContext(); return new BasicCassandraMappingContext();

View File

@ -1,28 +1,31 @@
package org.baeldung.spring.data.cassandra.model; package org.baeldung.spring.data.cassandra.model;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
import org.springframework.cassandra.core.Ordering; import org.springframework.cassandra.core.Ordering;
import org.springframework.cassandra.core.PrimaryKeyType; import org.springframework.cassandra.core.PrimaryKeyType;
import org.springframework.data.cassandra.mapping.Column; import org.springframework.data.cassandra.mapping.Column;
import org.springframework.data.cassandra.mapping.PrimaryKeyColumn; import org.springframework.data.cassandra.mapping.PrimaryKeyColumn;
import org.springframework.data.cassandra.mapping.Table; import org.springframework.data.cassandra.mapping.Table;
import java.util.HashSet;
import java.util.Set;
import java.util.UUID;
@Table @Table
public class Book { public class Book {
@PrimaryKeyColumn(name = "id", ordinal = 0, type = PrimaryKeyType.CLUSTERED, ordering = Ordering.DESCENDING) @PrimaryKeyColumn(name = "id", ordinal = 0, type = PrimaryKeyType.CLUSTERED, ordering = Ordering.DESCENDING)
private UUID id; private UUID id;
@PrimaryKeyColumn(name = "title", ordinal = 1, type = PrimaryKeyType.PARTITIONED) @PrimaryKeyColumn(name = "title", ordinal = 1, type = PrimaryKeyType.PARTITIONED)
private String title; private String title;
@PrimaryKeyColumn(name = "publisher", ordinal = 2, type = PrimaryKeyType.PARTITIONED) @PrimaryKeyColumn(name = "publisher", ordinal = 2, type = PrimaryKeyType.PARTITIONED)
private String publisher; private String publisher;
@Column @Column
private Set<String> tags = new HashSet<>(); private Set<String> tags = new HashSet<>();
public Book(UUID id, String title, String publisher, Set<String> tags) { public Book(final UUID id, final String title, final String publisher, final Set<String> tags) {
this.id = id; this.id = id;
this.title = title; this.title = title;
this.publisher = publisher; this.publisher = publisher;
@ -45,19 +48,20 @@ public class Book {
return tags; return tags;
} }
public void setId(UUID id) { public void setId(final UUID id) {
this.id = id; this.id = id;
} }
public void setTitle(String title) { public void setTitle(final String title) {
this.title = title; this.title = title;
} }
public void setPublisher(String publisher) { public void setPublisher(final String publisher) {
this.publisher = publisher; this.publisher = publisher;
} }
public void setTags(Set<String> tags) { public void setTags(final Set<String> tags) {
this.tags = tags; this.tags = tags;
} }
} }

View File

@ -7,6 +7,8 @@ import org.springframework.stereotype.Repository;
@Repository @Repository
public interface BookRepository extends CassandraRepository<Book> { public interface BookRepository extends CassandraRepository<Book> {
@Query("select * from book where title = ?0 and publisher=?1") @Query("select * from book where title = ?0 and publisher=?1")
Iterable<Book> findByTitleAndPublisher(String title, String publisher); Iterable<Book> findByTitleAndPublisher(String title, String publisher);
} }

View File

@ -1,9 +1,11 @@
package org.baeldung.spring.data.cassandra.repository; package org.baeldung.spring.data.cassandra.repository;
import com.datastax.driver.core.Cluster; import static org.junit.Assert.assertEquals;
import com.datastax.driver.core.Session; import static org.junit.Assert.assertNotEquals;
import com.datastax.driver.core.utils.UUIDs;
import com.google.common.collect.ImmutableSet; import java.io.IOException;
import java.util.HashMap;
import org.apache.cassandra.exceptions.ConfigurationException; import org.apache.cassandra.exceptions.ConfigurationException;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
@ -11,7 +13,11 @@ import org.apache.thrift.transport.TTransportException;
import org.baeldung.spring.data.cassandra.config.CassandraConfig; import org.baeldung.spring.data.cassandra.config.CassandraConfig;
import org.baeldung.spring.data.cassandra.model.Book; import org.baeldung.spring.data.cassandra.model.Book;
import org.cassandraunit.utils.EmbeddedCassandraServerHelper; import org.cassandraunit.utils.EmbeddedCassandraServerHelper;
import org.junit.*; import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cassandra.core.cql.CqlIdentifier; import org.springframework.cassandra.core.cql.CqlIdentifier;
@ -19,16 +25,14 @@ import org.springframework.data.cassandra.core.CassandraAdminOperations;
import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.io.IOException; import com.datastax.driver.core.Cluster;
import java.util.HashMap; import com.datastax.driver.core.Session;
import com.datastax.driver.core.utils.UUIDs;
import static org.junit.Assert.assertEquals; import com.google.common.collect.ImmutableSet;
import static org.junit.Assert.assertNotEquals;
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = CassandraConfig.class) @ContextConfiguration(classes = CassandraConfig.class)
public class BookRepositoryIntegrationTest { public class BookRepositoryIntegrationTest {
private static final Log LOGGER = LogFactory.getLog(BookRepositoryIntegrationTest.class); private static final Log LOGGER = LogFactory.getLog(BookRepositoryIntegrationTest.class);
public static final String KEYSPACE_CREATION_QUERY = "CREATE KEYSPACE IF NOT EXISTS testKeySpace WITH replication = { 'class': 'SimpleStrategy', 'replication_factor': '3' };"; public static final String KEYSPACE_CREATION_QUERY = "CREATE KEYSPACE IF NOT EXISTS testKeySpace WITH replication = { 'class': 'SimpleStrategy', 'replication_factor': '3' };";
@ -43,13 +47,14 @@ public class BookRepositoryIntegrationTest {
@Autowired @Autowired
private CassandraAdminOperations adminTemplate; private CassandraAdminOperations adminTemplate;
//
@BeforeClass @BeforeClass
public static void startCassandraEmbedded() throws InterruptedException, TTransportException, ConfigurationException, IOException { public static void startCassandraEmbedded() throws InterruptedException, TTransportException, ConfigurationException, IOException {
EmbeddedCassandraServerHelper.startEmbeddedCassandra(); EmbeddedCassandraServerHelper.startEmbeddedCassandra();
Cluster cluster = Cluster.builder().addContactPoints("127.0.0.1") final Cluster cluster = Cluster.builder().addContactPoints("127.0.0.1").withPort(9142).build();
.withPort(9142).build();
LOGGER.info("Server Started at 127.0.0.1:9142... "); LOGGER.info("Server Started at 127.0.0.1:9142... ");
Session session = cluster.connect(); final Session session = cluster.connect();
session.execute(KEYSPACE_CREATION_QUERY); session.execute(KEYSPACE_CREATION_QUERY);
session.execute(KEYSPACE_ACTIVATE_QUERY); session.execute(KEYSPACE_ACTIVATE_QUERY);
LOGGER.info("KeySpace created and activated."); LOGGER.info("KeySpace created and activated.");
@ -63,54 +68,54 @@ public class BookRepositoryIntegrationTest {
@Test @Test
public void whenSavingBook_thenAvailableOnRetrieval() { public void whenSavingBook_thenAvailableOnRetrieval() {
Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", final Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software"));
"O'Reilly Media", ImmutableSet.of("Computer", "Software"));
bookRepository.save(ImmutableSet.of(javaBook)); bookRepository.save(ImmutableSet.of(javaBook));
Iterable<Book> books = bookRepository.findByTitleAndPublisher("Head First Java", "O'Reilly Media"); final Iterable<Book> books = bookRepository.findByTitleAndPublisher("Head First Java", "O'Reilly Media");
assertEquals(javaBook.getId(), books.iterator().next().getId()); assertEquals(javaBook.getId(), books.iterator().next().getId());
} }
@Test @Test
public void whenUpdatingBooks_thenAvailableOnRetrieval() { public void whenUpdatingBooks_thenAvailableOnRetrieval() {
Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); final Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software"));
bookRepository.save(ImmutableSet.of(javaBook)); bookRepository.save(ImmutableSet.of(javaBook));
Iterable<Book> books = bookRepository.findByTitleAndPublisher("Head First Java", "O'Reilly Media"); final Iterable<Book> books = bookRepository.findByTitleAndPublisher("Head First Java", "O'Reilly Media");
javaBook.setTitle("Head First Java Second Edition"); javaBook.setTitle("Head First Java Second Edition");
bookRepository.save(ImmutableSet.of(javaBook)); bookRepository.save(ImmutableSet.of(javaBook));
Iterable<Book> updateBooks = bookRepository.findByTitleAndPublisher("Head First Java Second Edition", "O'Reilly Media"); final Iterable<Book> updateBooks = bookRepository.findByTitleAndPublisher("Head First Java Second Edition", "O'Reilly Media");
assertEquals(javaBook.getTitle(), updateBooks.iterator().next().getTitle()); assertEquals(javaBook.getTitle(), updateBooks.iterator().next().getTitle());
} }
@Test(expected = java.util.NoSuchElementException.class) @Test(expected = java.util.NoSuchElementException.class)
public void whenDeletingExistingBooks_thenNotAvailableOnRetrieval() { public void whenDeletingExistingBooks_thenNotAvailableOnRetrieval() {
Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); final Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software"));
bookRepository.save(ImmutableSet.of(javaBook)); bookRepository.save(ImmutableSet.of(javaBook));
bookRepository.delete(javaBook); bookRepository.delete(javaBook);
Iterable<Book> books = bookRepository.findByTitleAndPublisher("Head First Java", "O'Reilly Media"); final Iterable<Book> books = bookRepository.findByTitleAndPublisher("Head First Java", "O'Reilly Media");
assertNotEquals(javaBook.getId(), books.iterator().next().getId()); assertNotEquals(javaBook.getId(), books.iterator().next().getId());
} }
@Test @Test
public void whenSavingBooks_thenAllShouldAvailableOnRetrieval() { public void whenSavingBooks_thenAllShouldAvailableOnRetrieval() {
Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", final Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software"));
"O'Reilly Media", ImmutableSet.of("Computer", "Software")); final Book dPatternBook = new Book(UUIDs.timeBased(), "Head Design Patterns", "O'Reilly Media", ImmutableSet.of("Computer", "Software"));
Book dPatternBook = new Book(UUIDs.timeBased(), "Head Design Patterns",
"O'Reilly Media", ImmutableSet.of("Computer", "Software"));
bookRepository.save(ImmutableSet.of(javaBook)); bookRepository.save(ImmutableSet.of(javaBook));
bookRepository.save(ImmutableSet.of(dPatternBook)); bookRepository.save(ImmutableSet.of(dPatternBook));
Iterable<Book> books = bookRepository.findAll(); final Iterable<Book> books = bookRepository.findAll();
int bookCount = 0; int bookCount = 0;
for (Book book : books) bookCount++; for (final Book book : books) {
bookCount++;
}
assertEquals(bookCount, 2); assertEquals(bookCount, 2);
} }
@After @After
public void dropTable() { public void dropTable() {
adminTemplate.dropTable(CqlIdentifier.cqlId(DATA_TABLE_NAME)); adminTemplate.dropTable(CqlIdentifier.cqlId(DATA_TABLE_NAME));
} }
@AfterClass @AfterClass
public static void stopCassandraEmbedded() { public static void stopCassandraEmbedded() {
EmbeddedCassandraServerHelper.cleanEmbeddedCassandra(); EmbeddedCassandraServerHelper.cleanEmbeddedCassandra();
} }
} }

View File

@ -1,12 +1,13 @@
package org.baeldung.spring.data.cassandra.repository; package org.baeldung.spring.data.cassandra.repository;
import com.datastax.driver.core.Cluster; import static junit.framework.TestCase.assertEquals;
import com.datastax.driver.core.Session;
import com.datastax.driver.core.querybuilder.Insert; import java.io.IOException;
import com.datastax.driver.core.querybuilder.QueryBuilder; import java.util.ArrayList;
import com.datastax.driver.core.querybuilder.Select; import java.util.HashMap;
import com.datastax.driver.core.utils.UUIDs; import java.util.List;
import com.google.common.collect.ImmutableSet; import java.util.UUID;
import org.apache.cassandra.exceptions.ConfigurationException; import org.apache.cassandra.exceptions.ConfigurationException;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
@ -14,7 +15,11 @@ import org.apache.thrift.transport.TTransportException;
import org.baeldung.spring.data.cassandra.config.CassandraConfig; import org.baeldung.spring.data.cassandra.config.CassandraConfig;
import org.baeldung.spring.data.cassandra.model.Book; import org.baeldung.spring.data.cassandra.model.Book;
import org.cassandraunit.utils.EmbeddedCassandraServerHelper; import org.cassandraunit.utils.EmbeddedCassandraServerHelper;
import org.junit.*; import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cassandra.core.cql.CqlIdentifier; import org.springframework.cassandra.core.cql.CqlIdentifier;
@ -23,18 +28,17 @@ import org.springframework.data.cassandra.core.CassandraOperations;
import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.io.IOException; import com.datastax.driver.core.Cluster;
import java.util.ArrayList; import com.datastax.driver.core.Session;
import java.util.HashMap; import com.datastax.driver.core.querybuilder.Insert;
import java.util.List; import com.datastax.driver.core.querybuilder.QueryBuilder;
import java.util.UUID; import com.datastax.driver.core.querybuilder.Select;
import com.datastax.driver.core.utils.UUIDs;
import static junit.framework.TestCase.assertEquals; import com.google.common.collect.ImmutableSet;
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = CassandraConfig.class) @ContextConfiguration(classes = CassandraConfig.class)
public class CQLQueriesIntegrationTest { public class CQLQueriesIntegrationTest {
private static final Log LOGGER = LogFactory.getLog(CQLQueriesIntegrationTest.class); private static final Log LOGGER = LogFactory.getLog(CQLQueriesIntegrationTest.class);
public static final String KEYSPACE_CREATION_QUERY = "CREATE KEYSPACE IF NOT EXISTS testKeySpace " + "WITH replication = { 'class': 'SimpleStrategy', 'replication_factor': '3' };"; public static final String KEYSPACE_CREATION_QUERY = "CREATE KEYSPACE IF NOT EXISTS testKeySpace " + "WITH replication = { 'class': 'SimpleStrategy', 'replication_factor': '3' };";
@ -49,12 +53,14 @@ public class CQLQueriesIntegrationTest {
@Autowired @Autowired
private CassandraOperations cassandraTemplate; private CassandraOperations cassandraTemplate;
//
@BeforeClass @BeforeClass
public static void startCassandraEmbedded() throws InterruptedException, TTransportException, ConfigurationException, IOException { public static void startCassandraEmbedded() throws InterruptedException, TTransportException, ConfigurationException, IOException {
EmbeddedCassandraServerHelper.startEmbeddedCassandra(25000); EmbeddedCassandraServerHelper.startEmbeddedCassandra(25000);
Cluster cluster = Cluster.builder().addContactPoints("127.0.0.1").withPort(9142).build(); final Cluster cluster = Cluster.builder().addContactPoints("127.0.0.1").withPort(9142).build();
LOGGER.info("Server Started at 127.0.0.1:9142... "); LOGGER.info("Server Started at 127.0.0.1:9142... ");
Session session = cluster.connect(); final Session session = cluster.connect();
session.execute(KEYSPACE_CREATION_QUERY); session.execute(KEYSPACE_CREATION_QUERY);
session.execute(KEYSPACE_ACTIVATE_QUERY); session.execute(KEYSPACE_ACTIVATE_QUERY);
LOGGER.info("KeySpace created and activated."); LOGGER.info("KeySpace created and activated.");
@ -68,40 +74,40 @@ public class CQLQueriesIntegrationTest {
@Test @Test
public void whenSavingBook_thenAvailableOnRetrieval_usingQueryBuilder() { public void whenSavingBook_thenAvailableOnRetrieval_usingQueryBuilder() {
UUID uuid = UUIDs.timeBased(); final UUID uuid = UUIDs.timeBased();
Insert insert = QueryBuilder.insertInto(DATA_TABLE_NAME).value("id", uuid).value("title", "Head First Java").value("publisher", "OReilly Media").value("tags", ImmutableSet.of("Software")); final Insert insert = QueryBuilder.insertInto(DATA_TABLE_NAME).value("id", uuid).value("title", "Head First Java").value("publisher", "OReilly Media").value("tags", ImmutableSet.of("Software"));
cassandraTemplate.execute(insert); cassandraTemplate.execute(insert);
Select select = QueryBuilder.select().from("book").limit(10); final Select select = QueryBuilder.select().from("book").limit(10);
Book retrievedBook = cassandraTemplate.selectOne(select, Book.class); final Book retrievedBook = cassandraTemplate.selectOne(select, Book.class);
assertEquals(uuid, retrievedBook.getId()); assertEquals(uuid, retrievedBook.getId());
} }
@Test @Test
public void whenSavingBook_thenAvailableOnRetrieval_usingCQLStatements() { public void whenSavingBook_thenAvailableOnRetrieval_usingCQLStatements() {
UUID uuid = UUIDs.timeBased(); final UUID uuid = UUIDs.timeBased();
String insertCql = "insert into book (id, title, publisher, tags) values " + "(" + uuid + ", 'Head First Java', 'OReilly Media', {'Software'})"; final String insertCql = "insert into book (id, title, publisher, tags) values " + "(" + uuid + ", 'Head First Java', 'OReilly Media', {'Software'})";
cassandraTemplate.execute(insertCql); cassandraTemplate.execute(insertCql);
Select select = QueryBuilder.select().from("book").limit(10); final Select select = QueryBuilder.select().from("book").limit(10);
Book retrievedBook = cassandraTemplate.selectOne(select, Book.class); final Book retrievedBook = cassandraTemplate.selectOne(select, Book.class);
assertEquals(uuid, retrievedBook.getId()); assertEquals(uuid, retrievedBook.getId());
} }
@Test @Test
public void whenSavingBook_thenAvailableOnRetrieval_usingPreparedStatements() throws InterruptedException { public void whenSavingBook_thenAvailableOnRetrieval_usingPreparedStatements() throws InterruptedException {
UUID uuid = UUIDs.timeBased(); final UUID uuid = UUIDs.timeBased();
String insertPreparedCql = "insert into book (id, title, publisher, tags) values (?, ?, ?, ?)"; final String insertPreparedCql = "insert into book (id, title, publisher, tags) values (?, ?, ?, ?)";
List<Object> singleBookArgsList = new ArrayList<>(); final List<Object> singleBookArgsList = new ArrayList<>();
List<List<?>> bookList = new ArrayList<>(); final List<List<?>> bookList = new ArrayList<>();
singleBookArgsList.add(uuid); singleBookArgsList.add(uuid);
singleBookArgsList.add("Head First Java"); singleBookArgsList.add("Head First Java");
singleBookArgsList.add("OReilly Media"); singleBookArgsList.add("OReilly Media");
singleBookArgsList.add(ImmutableSet.of("Software")); singleBookArgsList.add(ImmutableSet.of("Software"));
bookList.add(singleBookArgsList); bookList.add(singleBookArgsList);
cassandraTemplate.ingest(insertPreparedCql, bookList); cassandraTemplate.ingest(insertPreparedCql, bookList);
//This may not be required, just added to avoid any transient issues // This may not be required, just added to avoid any transient issues
Thread.sleep(5000); Thread.sleep(5000);
Select select = QueryBuilder.select().from("book"); final Select select = QueryBuilder.select().from("book");
Book retrievedBook = cassandraTemplate.selectOne(select, Book.class); final Book retrievedBook = cassandraTemplate.selectOne(select, Book.class);
assertEquals(uuid, retrievedBook.getId()); assertEquals(uuid, retrievedBook.getId());
} }
@ -114,4 +120,5 @@ public class CQLQueriesIntegrationTest {
public static void stopCassandraEmbedded() { public static void stopCassandraEmbedded() {
EmbeddedCassandraServerHelper.cleanEmbeddedCassandra(); EmbeddedCassandraServerHelper.cleanEmbeddedCassandra();
} }
} }

View File

@ -1,11 +1,15 @@
package org.baeldung.spring.data.cassandra.repository; package org.baeldung.spring.data.cassandra.repository;
import com.datastax.driver.core.Cluster; import static junit.framework.TestCase.assertNull;
import com.datastax.driver.core.Session; import static org.hamcrest.CoreMatchers.is;
import com.datastax.driver.core.querybuilder.QueryBuilder; import static org.junit.Assert.assertEquals;
import com.datastax.driver.core.querybuilder.Select; import static org.junit.Assert.assertThat;
import com.datastax.driver.core.utils.UUIDs;
import com.google.common.collect.ImmutableSet; import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.cassandra.exceptions.ConfigurationException; import org.apache.cassandra.exceptions.ConfigurationException;
import org.apache.commons.logging.Log; import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory; import org.apache.commons.logging.LogFactory;
@ -13,7 +17,11 @@ import org.apache.thrift.transport.TTransportException;
import org.baeldung.spring.data.cassandra.config.CassandraConfig; import org.baeldung.spring.data.cassandra.config.CassandraConfig;
import org.baeldung.spring.data.cassandra.model.Book; import org.baeldung.spring.data.cassandra.model.Book;
import org.cassandraunit.utils.EmbeddedCassandraServerHelper; import org.cassandraunit.utils.EmbeddedCassandraServerHelper;
import org.junit.*; import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cassandra.core.cql.CqlIdentifier; import org.springframework.cassandra.core.cql.CqlIdentifier;
@ -22,20 +30,16 @@ import org.springframework.data.cassandra.core.CassandraOperations;
import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.io.IOException; import com.datastax.driver.core.Cluster;
import java.util.ArrayList; import com.datastax.driver.core.Session;
import java.util.HashMap; import com.datastax.driver.core.querybuilder.QueryBuilder;
import java.util.List; import com.datastax.driver.core.querybuilder.Select;
import com.datastax.driver.core.utils.UUIDs;
import static junit.framework.TestCase.assertNull; import com.google.common.collect.ImmutableSet;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
@RunWith(SpringJUnit4ClassRunner.class) @RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = CassandraConfig.class) @ContextConfiguration(classes = CassandraConfig.class)
public class CassandraTemplateIntegrationTest { public class CassandraTemplateIntegrationTest {
private static final Log LOGGER = LogFactory.getLog(CassandraTemplateIntegrationTest.class); private static final Log LOGGER = LogFactory.getLog(CassandraTemplateIntegrationTest.class);
public static final String KEYSPACE_CREATION_QUERY = "CREATE KEYSPACE IF NOT EXISTS testKeySpace " + "WITH replication = { 'class': 'SimpleStrategy', 'replication_factor': '3' };"; public static final String KEYSPACE_CREATION_QUERY = "CREATE KEYSPACE IF NOT EXISTS testKeySpace " + "WITH replication = { 'class': 'SimpleStrategy', 'replication_factor': '3' };";
@ -50,12 +54,14 @@ public class CassandraTemplateIntegrationTest {
@Autowired @Autowired
private CassandraOperations cassandraTemplate; private CassandraOperations cassandraTemplate;
//
@BeforeClass @BeforeClass
public static void startCassandraEmbedded() throws InterruptedException, TTransportException, ConfigurationException, IOException { public static void startCassandraEmbedded() throws InterruptedException, TTransportException, ConfigurationException, IOException {
EmbeddedCassandraServerHelper.startEmbeddedCassandra(); EmbeddedCassandraServerHelper.startEmbeddedCassandra();
Cluster cluster = Cluster.builder().addContactPoints("127.0.0.1").withPort(9142).build(); final Cluster cluster = Cluster.builder().addContactPoints("127.0.0.1").withPort(9142).build();
LOGGER.info("Server Started at 127.0.0.1:9142... "); LOGGER.info("Server Started at 127.0.0.1:9142... ");
Session session = cluster.connect(); final Session session = cluster.connect();
session.execute(KEYSPACE_CREATION_QUERY); session.execute(KEYSPACE_CREATION_QUERY);
session.execute(KEYSPACE_ACTIVATE_QUERY); session.execute(KEYSPACE_ACTIVATE_QUERY);
LOGGER.info("KeySpace created and activated."); LOGGER.info("KeySpace created and activated.");
@ -69,24 +75,24 @@ public class CassandraTemplateIntegrationTest {
@Test @Test
public void whenSavingBook_thenAvailableOnRetrieval() { public void whenSavingBook_thenAvailableOnRetrieval() {
Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); final Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software"));
cassandraTemplate.insert(javaBook); cassandraTemplate.insert(javaBook);
Select select = QueryBuilder.select().from("book").where(QueryBuilder.eq("title", "Head First Java")).and(QueryBuilder.eq("publisher", "O'Reilly Media")).limit(10); final Select select = QueryBuilder.select().from("book").where(QueryBuilder.eq("title", "Head First Java")).and(QueryBuilder.eq("publisher", "O'Reilly Media")).limit(10);
Book retrievedBook = cassandraTemplate.selectOne(select, Book.class); final Book retrievedBook = cassandraTemplate.selectOne(select, Book.class);
assertEquals(javaBook.getId(), retrievedBook.getId()); assertEquals(javaBook.getId(), retrievedBook.getId());
} }
@Test @Test
public void whenSavingBooks_thenAllAvailableOnRetrieval() { public void whenSavingBooks_thenAllAvailableOnRetrieval() {
Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); final Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software"));
Book dPatternBook = new Book(UUIDs.timeBased(), "Head Design Patterns", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); final Book dPatternBook = new Book(UUIDs.timeBased(), "Head Design Patterns", "O'Reilly Media", ImmutableSet.of("Computer", "Software"));
List<Book> bookList = new ArrayList<>(); final List<Book> bookList = new ArrayList<>();
bookList.add(javaBook); bookList.add(javaBook);
bookList.add(dPatternBook); bookList.add(dPatternBook);
cassandraTemplate.insert(bookList); cassandraTemplate.insert(bookList);
Select select = QueryBuilder.select().from("book").limit(10); final Select select = QueryBuilder.select().from("book").limit(10);
List<Book> retrievedBooks = cassandraTemplate.select(select, Book.class); final List<Book> retrievedBooks = cassandraTemplate.select(select, Book.class);
assertThat(retrievedBooks.size(), is(2)); assertThat(retrievedBooks.size(), is(2));
assertEquals(javaBook.getId(), retrievedBooks.get(0).getId()); assertEquals(javaBook.getId(), retrievedBooks.get(0).getId());
assertEquals(dPatternBook.getId(), retrievedBooks.get(1).getId()); assertEquals(dPatternBook.getId(), retrievedBooks.get(1).getId());
@ -94,45 +100,45 @@ public class CassandraTemplateIntegrationTest {
@Test @Test
public void whenUpdatingBook_thenShouldUpdatedOnRetrieval() { public void whenUpdatingBook_thenShouldUpdatedOnRetrieval() {
Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); final Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software"));
cassandraTemplate.insert(javaBook); cassandraTemplate.insert(javaBook);
Select select = QueryBuilder.select().from("book").limit(10); final Select select = QueryBuilder.select().from("book").limit(10);
Book retrievedBook = cassandraTemplate.selectOne(select, Book.class); final Book retrievedBook = cassandraTemplate.selectOne(select, Book.class);
retrievedBook.setTags(ImmutableSet.of("Java", "Programming")); retrievedBook.setTags(ImmutableSet.of("Java", "Programming"));
cassandraTemplate.update(retrievedBook); cassandraTemplate.update(retrievedBook);
Book retrievedUpdatedBook = cassandraTemplate.selectOne(select, Book.class); final Book retrievedUpdatedBook = cassandraTemplate.selectOne(select, Book.class);
assertEquals(retrievedBook.getTags(), retrievedUpdatedBook.getTags()); assertEquals(retrievedBook.getTags(), retrievedUpdatedBook.getTags());
} }
@Test @Test
public void whenDeletingASelectedBook_thenNotAvailableOnRetrieval() throws InterruptedException { public void whenDeletingASelectedBook_thenNotAvailableOnRetrieval() throws InterruptedException {
Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "OReilly Media", ImmutableSet.of("Computer", "Software")); final Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "OReilly Media", ImmutableSet.of("Computer", "Software"));
cassandraTemplate.insert(javaBook); cassandraTemplate.insert(javaBook);
cassandraTemplate.delete(javaBook); cassandraTemplate.delete(javaBook);
Select select = QueryBuilder.select().from("book").limit(10); final Select select = QueryBuilder.select().from("book").limit(10);
Book retrievedUpdatedBook = cassandraTemplate.selectOne(select, Book.class); final Book retrievedUpdatedBook = cassandraTemplate.selectOne(select, Book.class);
assertNull(retrievedUpdatedBook); assertNull(retrievedUpdatedBook);
} }
@Test @Test
public void whenDeletingAllBooks_thenNotAvailableOnRetrieval() { public void whenDeletingAllBooks_thenNotAvailableOnRetrieval() {
Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); final Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software"));
Book dPatternBook = new Book(UUIDs.timeBased(), "Head Design Patterns", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); final Book dPatternBook = new Book(UUIDs.timeBased(), "Head Design Patterns", "O'Reilly Media", ImmutableSet.of("Computer", "Software"));
cassandraTemplate.insert(javaBook); cassandraTemplate.insert(javaBook);
cassandraTemplate.insert(dPatternBook); cassandraTemplate.insert(dPatternBook);
cassandraTemplate.deleteAll(Book.class); cassandraTemplate.deleteAll(Book.class);
Select select = QueryBuilder.select().from("book").limit(10); final Select select = QueryBuilder.select().from("book").limit(10);
Book retrievedUpdatedBook = cassandraTemplate.selectOne(select, Book.class); final Book retrievedUpdatedBook = cassandraTemplate.selectOne(select, Book.class);
assertNull(retrievedUpdatedBook); assertNull(retrievedUpdatedBook);
} }
@Test @Test
public void whenAddingBooks_thenCountShouldBeCorrectOnRetrieval() { public void whenAddingBooks_thenCountShouldBeCorrectOnRetrieval() {
Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); final Book javaBook = new Book(UUIDs.timeBased(), "Head First Java", "O'Reilly Media", ImmutableSet.of("Computer", "Software"));
Book dPatternBook = new Book(UUIDs.timeBased(), "Head Design Patterns", "O'Reilly Media", ImmutableSet.of("Computer", "Software")); final Book dPatternBook = new Book(UUIDs.timeBased(), "Head Design Patterns", "O'Reilly Media", ImmutableSet.of("Computer", "Software"));
cassandraTemplate.insert(javaBook); cassandraTemplate.insert(javaBook);
cassandraTemplate.insert(dPatternBook); cassandraTemplate.insert(dPatternBook);
long bookCount = cassandraTemplate.count(Book.class); final long bookCount = cassandraTemplate.count(Book.class);
assertEquals(2, bookCount); assertEquals(2, bookCount);
} }

View File

@ -0,0 +1,37 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" output="target/classes" path="src/main/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" output="target/classes" path="target/generated-sources/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="src" output="target/test-classes" path="src/test/java">
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
<attributes>
<attribute name="maven.pomderived" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="output" path="target/classes"/>
</classpath>

View File

@ -0,0 +1,29 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>spring-data-mongodb</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.m2e.core.maven2Builder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.springframework.ide.eclipse.core.springbuilder</name>
<arguments>
</arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.springframework.ide.eclipse.core.springnature</nature>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>org.eclipse.m2e.core.maven2Nature</nature>
</natures>
</projectDescription>

View File

@ -169,6 +169,7 @@
</plugin> </plugin>
</plugins> </plugins>
</build> </build>
<properties> <properties>
<!-- Spring --> <!-- Spring -->
<org.springframework.version>4.2.4.RELEASE</org.springframework.version> <org.springframework.version>4.2.4.RELEASE</org.springframework.version>
@ -197,8 +198,9 @@
<maven-war-plugin.version>2.6</maven-war-plugin.version> <maven-war-plugin.version>2.6</maven-war-plugin.version>
<maven-surefire-plugin.version>2.18.1</maven-surefire-plugin.version> <maven-surefire-plugin.version>2.18.1</maven-surefire-plugin.version>
<maven-resources-plugin.version>2.7</maven-resources-plugin.version> <maven-resources-plugin.version>2.7</maven-resources-plugin.version>
<cargo-maven2-plugin.version>1.4.15</cargo-maven2-plugin.version> <cargo-maven2-plugin.version>1.4.17</cargo-maven2-plugin.version>
<!-- AspectJ --> <!-- AspectJ -->
<aspectj.version>1.8.7</aspectj.version> <aspectj.version>1.8.7</aspectj.version>
</properties> </properties>
</project> </project>