首先,创建一个MappingManager. It wraps an existing Session instance:
MappingManager manager = new MappingManager(session);
MappingManager是线程安全的.
实体mappers
实体类(@Table注解)由专门的Mapper对象管理.
Mappermapper = 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);
retrieve
UUID userId = ...;
User u = mapper.get(userId);
delete
delete的参数可以是 its primary keys, or the objec
UUID userId = ...;
mapper.delete(userId);
mapper.delete(u);
所有CRUD操作是同步的,但是Mapper提供了相应的异步方法
ListenableFuturesaveFuture = mapper.saveAsync(u); ListenableFuture userFuture = mapper.getAsync(userId); ListenableFuture 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 valuenull
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 persistnull
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 Statement
s
Mapper可以返回相应的Statement 对象, 而不是直接执行操作.
这是的client可以定制化statement
Mapper.saveQuery(entity)
: returns a statement generated by the mapper to saveentity
into the database.Mapper.getQuery(userId)
: returns a statement to select a row in the database, selected on the givenuserId
, and matching the mapped object structure.Mapper.deleteQuery(userID)
: returns a statement to delete a row in the database given theuserId
provided. This method can also accept a mapped object instance.
Manual mapping
Mapper#map 可以转换常规查询的结果:
ResultSet results = session.execute("SELECT * FROM user"); Resultusers = 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") ResultgetAll(); }
这样以来,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 must be a mapped class.Synchronous execution, returns a list of mapped objects. |
ResultSetFuture |
Asynchronous execution, returns unmapped results. |
ListenableFuture |
T must be a mapped class.Asynchronous execution, returns the first row (or null if there are no results). |
ListenableFuture |
T must be a mapped class.Asynchronous execution, returns a list of mapped objects. |
Example:
@Query("SELECT * FROM user") public ListenableFuture> getAllAsync();
Customizing the statement
一个Accessor query (见上面内容)中,使用@QueryParameters 注解定制化查询参数.
比如consistency level, fetchsize or tracing
@Query("SELECT * FROM ks.users") @QueryParameters(consistency="QUORUM") public ListenableFuture> getAllAsync();