Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Cassandra Foo Repository with JHipster
package com.mycompany.myapp.repository;
import com.datastax.driver.core.*;
import com.datastax.driver.mapping.Mapper;
import com.datastax.driver.mapping.MappingManager;
import com.mycompany.myapp.domain.Foo;
import org.springframework.stereotype.Repository;
import javax.annotation.PostConstruct;
import javax.inject.Inject;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
/**
* Cassandra repository for the Foo entity.
*/
@Repository
public class FooRepository {
@Inject
private Session session;
private Mapper<Foo> mapper;
private PreparedStatement findAllStmt;
private PreparedStatement truncateStmt;
@PostConstruct
public void init() {
mapper = new MappingManager(session).mapper(Foo.class);
findAllStmt = session.prepare("SELECT * FROM foo");
truncateStmt = session.prepare("TRUNCATE foo");
}
public List<Foo> findAll() {
List<Foo> foos = new ArrayList<>();
BoundStatement stmt = findAllStmt.bind();
session.execute(stmt).all().stream().map(
row -> {
Foo foo = new Foo();
foo.setId(row.getUUID("id"));
foo.setBar(row.getInt("bar"));
foo.setBuzz(row.getString("buzz"));
return foo;
}
).forEach(foos::add);
return foos;
}
public Foo findOne(UUID id) {
return mapper.get(id);
}
public void save(Foo foo) {
if (foo.getId() == null) {
foo.setId(UUID.randomUUID());
}
mapper.save(foo);
}
public void delete(UUID id) {
mapper.delete(id);
}
public void deleteAll() {
BoundStatement stmt = truncateStmt.bind();
session.execute(stmt);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment