PrimaryIndex
PrimaryIndex是为了一个实体类和它的主关键字,PrimaryIndex是线程安全的。
PrimaryIndex里存放的是封装好的由key type(PK)和entity type(E)组装的map对象
1. @Entity通常被用来定义一个实体类
@PrimaryKey通常被用来定义一个主关键字
例如:
- @Entity
- class Employee {
- @PrimaryKey
- long id;
- String name;
- Employee(long id, String name) {
- this.id = id;
- this.name = name;
- }
- private Employee() {} // For bindings
- }
2.通过EntityStore.getPrimaryIndex 可以获得的给定的实体类的PrimaryIndex 对象,该方法有2个参数:主关键字类型和实体类型
如:
- EntityStore store = new EntityStore(...);
- PrimaryIndex primaryIndex =
- store.getPrimaryIndex(Long.class, Employee.class);
注:这里主关键字是long基本数据类型,而getPrimayIndex里的第一个参数是Long.class.也就是说当一个基本数据类型被使用时,它对应的包装类型被用来作为getPrimaryIndex 的参数。
3.PrimaryIndex 提供一个基本的存储和访问实体的方法,PrimaryIndex 的put(E)的方法被用来做为插入一个实体或更新一个实体. 如果主关键字不存在就是insert,返回null,如果主关键存在就是update,并且返回更新前旧的实体对象。
如:
- Employee oldEntity;
- oldEntity = primaryIndex.put(new Employee(1, "Jane Smith")); // Inserts an entity
- assert oldEntity == null;
- oldEntity = primaryIndex.put(new Employee(2, "Joan Smith")); // Inserts an entity
- assert oldEntity == null;
- oldEntity = primaryIndex.put(new Employee(2, "Joan M. Smith")); // Updates an entity
- assert oldEntity != null;
putNoReturn(E) 用法一样,唯一不同的是没有返回值
putNoOverwrite(E) 返回ture或false,当insert时会返回true,当被插入的实体已经存在就会返回false.并且不会执行update,也就是说不会执行任何action
如:
- boolean inserted;
- inserted = primaryIndex.putNoOverwrite(new Employee(1, "Jane Smith")); // Inserts an entity
- assert inserted;
- inserted = primaryIndex.putNoOverwrite(new Employee(2, "Joan Smith")); // Inserts an entity
- assert inserted;
- inserted = primaryIndex.putNoOverwrite(new Employee(2, "Joan M. Smith")); // No action was taken!
- assert !inserted;
4.主关键字是唯一的,如果不想自己指定主关键的值,则可以通过PrimaryKey.sequence()来定义,主要的话,主关键字的值会自动按顺序分配一个整形值,从1开始。
如:
- @Entity
- class Employee {
- @PrimaryKey(sequence="ID")
- long id;
- String name;
- Employee(String name) {
- this.name = name;
- }
- private Employee() {} // For bindings
- }
Sequence被指定的名字为ID,这个名字可以随意。如果多个实体类的Sequence的名字相同的话,这个Sequence将被共享。
当insert时,实体类的主关键字的key将被分配一个Sequence 的一个Integer值,如:
- Employee employee;
- employee = new Employee("Jane Smith");
- primaryIndex.putNoReturn(employee); // Inserts an entity
- assert employee.id == 1;
- employee = new Employee("Joan Smith");
- primaryIndex.putNoReturn(employee); // Inserts an entity
- assert employee.id == 2;
本文详细介绍了PrimaryIndex的概念及其在实体类中的应用。通过实例演示了如何使用PrimaryIndex进行实体的存储和检索,包括插入、更新实体及自动生成主键等操作。
201

被折叠的 条评论
为什么被折叠?



