首先,建立一个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.缓存
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);
基本的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();
Statement
sMapper能够返回相应的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.
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提供一种映射自定义查询, 这种查询是默认实体映射不支持的
经过注解@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也是线程安全的
查询语句能够绑定标记, 标记将会由方法的参数填充
@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);
声明的返回类型影像这一个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();
一个Accessor query (见上面内容)中,使用@QueryParameters 注解定制化查询参数.
好比consistency level, fetchsize or tracing
@Query("SELECT * FROM ks.users") @QueryParameters(consistency="QUORUM") public ListenableFuture<Result<User>> getAllAsync();