Created
April 21, 2015 09:15
-
-
Save jdubois/87441ab6733999b985ff to your computer and use it in GitHub Desktop.
Cassandra Foo Repository with JHipster
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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