Cassandra mapper的使用

首先,建立一個MappingManager. It wraps an existing Session instance:html

MappingManager manager = new MappingManager(session);

MappingManager是線程安全的.java

實體mappersgit

實體類(@Table註解)由專門的Mapper對象管理.github

Mapper<User> mapper = manager.mapper(User.class);

Mapper是線程安全的. manager內部緩存Mappper類,因此針對同一個class, manage#mapper獲得的是以前生成的mapper.緩存

Basic CRUD operations

save安全

UUID userId = ...;
User u = new User(userId, "John Doe", new Address("street", 01000));
mapper.save(u);

 

retrievesession

UUID userId = ...;
User u = mapper.get(userId);

 

deleteapp

delete的參數能夠是  its primary keys, or the objec異步

UUID userId = ...;
mapper.delete(userId);
mapper.delete(u);

 

全部CRUD操做是同步的,可是Mapper提供了相應的異步方法ide

ListenableFuture<Void> saveFuture = mapper.saveAsync(u);
ListenableFuture<User> userFuture = mapper.getAsync(userId);
ListenableFuture<Void> deleteFuture = mapper.deleteAsync(userId);

 

Mapper options

基本的CRUD操做接收其餘選項來定製化基本的查詢

  • ttl: add a time-to-live value for the operation.
  • timestamp: add a timestamp value for the operation.
  • consistencyLevel: specify a consistency level.
  • tracing: set tracing flag for the query.
  • saveNullFields: if set to true, fields with value null in an instance that is to be persisted will be explicitly written asnull in the query. If set to false, fields with null value won't be included in the write query (thus avoiding tombstones). If not specified, the default behavior is to persist null fields.

 

Some options don't apply to all operations:

Option save/saveQuery get/getQuery delete/deleteQuery
Ttl yes no no
Timestamp yes no yes
ConsistencyLevel yes yes yes
Tracing yes yes yes
SaveNullFields yes no no

Note that Option.consistencyLevel 和 由@Table定義的consistency level冗餘.

若是兩者都定義了,以Option爲準

apper.setDefaultGetOption(tracing(true), consistencyLevel(QUORUM));
mapper.setDefaultSaveOption(saveNullFields(false));
mapper.setDefaultDeleteOption(consistencyLevel(ONE));

// Given the defaults above, this will use tracing(true), consistencyLevel(ONE)
mapper.get(uuid, consistencyLevel(ONE));

To reset default options, use the following methods:

mapper.resetDefaultGetOption();
mapper.resetDefaultSaveOption();
mapper.resetDefaultDeleteOption();

 

Access to underlying Statements

Mapper能夠返回相應的Statement 對象, 而不是直接執行操做.

這是的client能夠定製化statement

  • Mapper.saveQuery(entity): returns a statement generated by the mapper to save entity into the database.
  • Mapper.getQuery(userId): returns a statement to select a row in the database, selected on the given userId, and matching the mapped object structure.
  • Mapper.deleteQuery(userID): returns a statement to delete a row in the database given the userId provided. This method can also accept a mapped object instance.

 

Manual mapping

Mapper#map 能夠轉換常規查詢的結果:

ResultSet results = session.execute("SELECT * FROM user");
Result<User> users = mapper.map(results);
for (User u : users) {
    System.out.println("User : " + u.getUserId());
}

Result is similar to ResultSet but for a given mapped class. It provides methods one()all()iterator(),getExecutionInfo() and isExhausted(). Note that iterating the Result will consume the ResultSet, and vice-versa.

Accessors

Accessors提供一種映射自定義查詢, 這種查詢是默認實體映射不支持的

經過註解@Accessor 在每一個方法上提供相應的CQL查詢

@Accessor
public interface UserAccessor {
    @Query("SELECT * FROM user")
    Result<User> getAll();
}

這樣以來,MappingManager就能夠處理這個接口,自動generate an implementation for it

UserAccessor userAccessor = manager.createAccessor(UserAccessor.class);
User user = userAccessor.getOne(uuid);

accessors也是線程安全的

 

Parameters

查詢語句能夠綁定標記, 標記將會由方法的參數填充

@Query("insert into user (id, name) values (?, ?)")
ResultSet insert(UUID userId, String name);

若是是命名標記, 要使用帶@Param的參數來標示相應的標記

@Query("insert into user (userId, name) values (:u, :n)")
ResultSet insert(@Param("u") UUID userId, @Param("n") String name);

若是方法參數是枚舉類, 則必須用@Enumerated來標明怎麼把它轉化爲CQL

@Query("insert into user (key, gender) values (?,?)")
ResultSet addUser(int key, @Enumerated(EnumType.ORDINAL) Enum value);

 

Return type

聲明的返回類型影像這一個query是如何執行的

 

Return type Effect
void Synchronous execution, discards the results of the query.
ResultSet Synchronous execution, returns unmapped results.
T T must be a mapped class.
Synchronous execution, returns the first row (or null if there are no results).
Result<T> T must be a mapped class.
Synchronous execution, returns a list of mapped objects.
ResultSetFuture Asynchronous execution, returns unmapped results.
ListenableFuture<T> T must be a mapped class.
Asynchronous execution, returns the first row (or null if there are no results).
ListenableFuture<Result<T>> T must be a mapped class.
Asynchronous execution, returns a list of mapped objects.

 

Example:

@Query("SELECT * FROM user")
public ListenableFuture<Result<User>> getAllAsync();

 

Customizing the statement

一個Accessor query (見上面內容)中,使用@QueryParameters 註解定製化查詢參數.

好比consistency levelfetchsize or tracing

@Query("SELECT * FROM ks.users")
@QueryParameters(consistency="QUORUM")
public ListenableFuture<Result<User>> getAllAsync();
相關文章
相關標籤/搜索