如果说,入门二的用法是hibernate,那么这篇入门三的用法就更像ibatis。
完整的代码请参考:https://github.com/yankai913/cassandra-java-userguide。
由于本文复用了入门二的部分代码,所以这里只贴新增的。
新增表:
CREATE TABLE complex.users ( id uuid PRIMARY KEY, name text, addresses map<text,frozen<address>> );
UserAccessor类:
import java.util.Map; import java.util.UUID; import com.datastax.driver.core.ResultSet; import com.datastax.driver.mapping.Result; import com.datastax.driver.mapping.annotations.Accessor; import com.datastax.driver.mapping.annotations.Param; import com.datastax.driver.mapping.annotations.Query; import com.google.common.util.concurrent.ListenableFuture; import com.zoo.Address; @Accessor public interface UserAccessor { @Query("SELECT * FROM complex.users WHERE id = ?") User getOnePosition(UUID userId); @Query("SELECT * FROM complex.users") Result<User> getAll(); @Query("SELECT * FROM complex.users") ListenableFuture<Result<User>> getAllAsync(); @Query("insert into complex.users(id, name, addresses) values (:id, :name, :addresses)") ResultSet insertUser(@Param("id") UUID id, @Param("name") String name, @Param("addresses") Map<String, Address> addresses); @Query("UPDATE complex.users SET name= :name WHERE id= :id") ResultSet updateName(@Param("id") UUID id, @Param("name") String name); @Query("UPDATE complex.users SET addresses[:name]=:address WHERE id= :id") ResultSet updateAddress(@Param("id") UUID id, @Param("name") String addressName, @Param("address") Address address); @Query("DELETE FROM complex.users WHERE id = ?") ResultSet deleteOne(UUID userId); }
User类:
import java.util.Map; import java.util.UUID; import com.datastax.driver.mapping.annotations.Column; import com.datastax.driver.mapping.annotations.Frozen; import com.datastax.driver.mapping.annotations.Table; import com.zoo.Address; import com.zoo.BaseEntity; @Table(keyspace = "complex", name = "users") public class User extends BaseEntity { private UUID id; private String name; @Column(name = "addresses") @Frozen("map<text,frozen<address>>") private Map<String, Address> address; public UUID getId() { return id; } public void setId(UUID id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Map<String, Address> getAddress() { return address; } public void setAddress(Map<String, Address> address) { this.address = address; } }
BaseEntity类,就是做了toString()重写:
import com.alibaba.fastjson.JSON; public class BaseEntity { @Override public String toString() { return JSON.toJSONString(this); } }
测试类AccessorClient:
import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import com.datastax.driver.core.Cluster; import com.datastax.driver.core.Host; import com.datastax.driver.core.Metadata; import com.datastax.driver.core.Session; import com.datastax.driver.mapping.MappingManager; import com.datastax.driver.mapping.Result; import com.google.common.util.concurrent.ListenableFuture; import com.zoo.Address; import com.zoo.Phone; /** * * @author yankai913@gmail.com * @date 2015-11-4 * */ public class AccessorClient { private Cluster cluster; private Session session; // 放一个公共userId private UUID userId = UUID.fromString("fbdf82ed-0063-4796-9c7c-a3d4f47b4b25"); public Session getSession() { return this.session; } /** * 连接集群,创建执行cql的session对象。 * * @param node */ public void connect(String node) { cluster = Cluster.builder().addContactPoint(node).build(); Metadata metadata = cluster.getMetadata(); System.out.printf("Connected to cluster: %s\n", metadata.getClusterName()); for (Host host : metadata.getAllHosts()) { System.out.printf("Datacenter: %s; Host: %s; Rack: %s\n", host.getDatacenter(), host.getAddress(), host.getRack()); } session = cluster.connect(); System.out.println(); } public void insert() { MappingManager manager = new MappingManager(getSession()); UserAccessor userAccessor = manager.createAccessor(UserAccessor.class); Map<String, Address> addresses = new HashMap<String, Address>(); Address address = new Address(); address.setCity("Honolulu"); address.setStreet("123 Arnold Drive"); address.setZipCode(95476); List<Phone> phones = new ArrayList<Phone>(); Phone phone1 = new Phone("job1", "10086"); Phone phone2 = new Phone("job2", "10000"); phones.add(phone1); phones.add(phone2); address.setPhones(phones); addresses.put("Work", address); userAccessor.insertUser(userId, "tom", addresses); } public void select() { // getAll MappingManager manager = new MappingManager(getSession()); UserAccessor userAccessor = manager.createAccessor(UserAccessor.class); Result<User> users = userAccessor.getAll(); for (User user : users) { System.out.println("getAll:" + user); } // getOne User user = userAccessor.getOnePosition(userId); System.out.println("getOne:" + user); // getAllAsync ListenableFuture<Result<User>> future = userAccessor.getAllAsync(); try { for (User _user : future.get()) { System.out.println("getAsync:" + _user); } } catch (Exception e) { e.printStackTrace(); } } public void update() { MappingManager manager = new MappingManager(getSession()); UserAccessor userAccessor = manager.createAccessor(UserAccessor.class); userAccessor.updateName(userId, "jack"); } public void update2() { MappingManager manager = new MappingManager(getSession()); UserAccessor userAccessor = manager.createAccessor(UserAccessor.class); Address address = new Address(); List<Phone> phones = new ArrayList<Phone>(); Phone phone2 = new Phone("job2", "10010"); phones.add(phone2); address.setPhones(phones); userAccessor.updateAddress(userId, "Work", address); } public void delete() { MappingManager manager = new MappingManager(getSession()); UserAccessor userAccessor = manager.createAccessor(UserAccessor.class); userAccessor.deleteOne(userId); } public void dropSchema() { session.execute("DROP KEYSPACE complex;"); } public void close() { session.close(); cluster.close(); } public static void main(String[] args) { AccessorClient client = new AccessorClient(); try { client.connect("127.0.0.1"); client.select(); client.insert(); client.select(); client.update(); client.select(); client.update2(); client.select(); client.delete(); client.select(); client.dropSchema(); } catch (Exception e) { e.printStackTrace(); } finally { client.close(); } } }
打印结果部分显示做对比:
Connected to cluster: Test Cluster
Datacenter: datacenter1; Host: /127.0.0.1; Rack: rack1
getOne:null
getOne:{“address”:{“Work”:{“city”:”Honolulu”,”phones”:[{“alias”:”job1″,”number”:”10086″},{“alias”:”job2″,”number”:”10000″}],”street”:”123 Arnold Drive”,”zipCode”:95476}},”id”:”fbdf82ed-0063-4796-9c7c-a3d4f47b4b25″,”name”:”tom”}
getOne:{“address”:{“Work”:{“city”:”Honolulu”,”phones”:[{“alias”:”job1″,”number”:”10086″},{“alias”:”job2″,”number”:”10000″}],”street”:”123 Arnold Drive”,”zipCode”:95476}},”id”:”fbdf82ed-0063-4796-9c7c-a3d4f47b4b25″,”name”:”jack”}
getOne:{“address”:{“Work”:{“phones”:[{“alias”:”job2″,”number”:”10010″}],”zipCode”:0}},”id”:”fbdf82ed-0063-4796-9c7c-a3d4f47b4b25″,”name”:”jack”}
getOne:null