GreenDao 学习笔记 5


简介


这篇将介绍 GreenDao 中的双向关联和那啥。


双向关联


hibernate 中是使用 mapped by 注解来实现双向关联的。
而在 GreenDao 中,双向关联就是两次单项关联而已。

 public static void main(String[] args) throws Exception {

        Schema schema = new Schema(1, "com.example.GreenDao5");

        Entity customerEntity = schema.addEntity("Customer");
        customerEntity.addIdProperty();
        customerEntity.addStringProperty("name").notNull();

        Entity orderEntity = schema.addEntity("Orders");  // order 是关键字
        orderEntity.addIdProperty();
        orderEntity.addStringProperty("name").notNull();

        Property customerIdProperty = orderEntity.addLongProperty("customerId").notNull().getProperty();
        customerEntity.addToMany(orderEntity, customerIdProperty);

        orderEntity.addToOne(customerEntity,customerIdProperty);

        new DaoGenerator().generateAll(schema, "D:\\");
    }


那啥


就是树形结构,表结构是递归表,有一个 parentId 的字段。
GreenDao 每个Relation 必须有唯一的名称,所以这里通过 setName 覆盖了。

 public static void main(String[] args) throws Exception {

        Schema schema = new Schema(1, "com.example.GreenDao5");

        Entity personEntity = schema.addEntity("Person");
        personEntity.addIdProperty();
        personEntity.addStringProperty("name").notNull();
        Property parentIdProperty = personEntity.addLongProperty("parentId").getProperty();

        personEntity.addToOne(personEntity, parentIdProperty).setName("parent");
        personEntity.addToMany(personEntity, parentIdProperty).setName("children");

        new DaoGenerator().generateAll(schema, "D:\\");
    }


ListViewAdapter.java


public class ListViewAdapter extends BaseAdapter {

    private List<Person> data = new ArrayList<Person>();

    private LayoutInflater layoutInflater;

    public ListViewAdapter(Activity activity) {

        layoutInflater = activity.getLayoutInflater();
    }

    @Override
    public int getCount() {

        return data.size();
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        Person person = data.get(position);
        String text = person.getName() + "\r\n";

        person.resetChildren();
        for (Person child : person.getChildren()) {
            text += (child.getName() + "");
        }

        TextView textView = (TextView) layoutInflater.inflate(R.layout.listview_item, parent, false);
        textView.setText(text);

        return textView;
    }

    public List<Person> getData() {

        return data;
    }

    @Override
    public Object getItem(int position) {

        return null;
    }

    @Override
    public long getItemId(int position) {

        return 0;
    }

}

所有 GreenDao 产生的实体,都是默认缓存的,想要取得当前数据库的数据,需要 reset 一下。


my_activity.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

    <LinearLayout android:layout_width="match_parent"
                  android:layout_height="50dp"
                  android:orientation="horizontal">

        <EditText android:id="@+id/etPersonName"
                  android:layout_weight="1" android:layout_width="0dp"
                  android:layout_height="match_parent"
                  android:hint="人名"/>

        <Button android:id="@+id/btnAdd"
                android:layout_width="wrap_content"
                android:layout_height="match_parent"
                android:text="添加"/>

    </LinearLayout>

    <ListView android:id="@+id/lvNote"
              android:layout_width="match_parent"
              android:layout_height="0dp" android:layout_weight="1"/>

</LinearLayout>


MyActivity.java


public class MyActivity extends Activity implements View.OnClickListener, AdapterView.OnItemClickListener {

    private PersonDao personDao;

    private ListViewAdapter listViewAdapter;

    private EditText etPersonName;

    // 顶层节点的 parentId 为 -1
    private final long DEFAULT_PARENT_ID = -1L;

    // 默认创建顶层节点
    private Long parentId = DEFAULT_PARENT_ID;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_activity);

        initDao();
        initView();

        refreshListView();
    }

    @Override
    public void onClick(View v) {

        onBtnAddClick();
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        onListViewItemClick(position);
    }

    private void initDao() {

        DaoMaster.DevOpenHelper helper = new DaoMaster.DevOpenHelper(this, "person-db", null);
        SQLiteDatabase db = helper.getWritableDatabase();

        DaoMaster daoMaster = new DaoMaster(db);
        DaoSession daoSession = daoMaster.newSession();
        personDao = daoSession.getPersonDao();
    }

    private void initView() {

        etPersonName = (EditText) findViewById(R.id.etPersonName);
        findViewById(R.id.btnAdd).setOnClickListener(this);

        ListView listView = (ListView) findViewById(R.id.lvNote);
        listViewAdapter = new ListViewAdapter(this);
        listView.setAdapter(listViewAdapter);
        listView.setOnItemClickListener(this);
    }

    private void refreshListView() {

        // 注意,GreenDao 默认的查询都是懒加载
        List<Person> dataFromDb = personDao._queryPerson_Children(DEFAULT_PARENT_ID);
        List<Person> listViewData = listViewAdapter.getData();
        listViewData.clear();
        listViewData.addAll(dataFromDb);
        listViewAdapter.notifyDataSetChanged();
    }

    private void onBtnAddClick() {

        String personName = etPersonName.getText().toString();
        if (personName.equals("")) {
            return;
        }

        Person person = new Person(null, personName, parentId);
        personDao.insert(person);

        refreshListView();
    }

    private void onListViewItemClick(int position) {

        Person person = listViewAdapter.getData().get(position);
        parentId = person.getId();

        Log.e("result", "parentId: " + parentId);
    }

}


小结

这样一来,GreenDao 中所有的 Relation 都已经实践过一遍了,如果需要更多的例子

https://github.com/greenrobot/greenDAO/tree/master/DaoGenerator 
https://github.com/greenrobot/greenDAO/tree/master/DaoTest








你可能感兴趣的:(android,greenDAO)