在上一篇文章greenDAO项目实战中,我们对GreenDao有了初步的认识。今天我们熟悉一下GreenDao中使用ToOne和ToMany实现一对一,一对多关联映射。本文在上篇的基础上进行。
添加Category类
我们现在对上一篇的Note进行扩展,添加类别。我们假设一个Note属于一个类别Category,一个类别Category可以拥有多个Note.
| 12
 3
 4
 5
 6
 7
 
 | @Entitypublic class Category {
 @Id
 private Long id;
 private String name;
 @ToMany(referencedJoinProperty = "categoryId")
 private List<Note> notes;
 
 | 
修改Note类,Category信息
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 
 | @Entity
 public class Note {
 @Id(autoincrement = true)
 private Long id;
 @NotNull
 private String text;
 private String comment;
 private java.util.Date date;
 
 @Convert(converter = NoteTypeConverter.class, columnType = String.class)
 private NoteType type;
 
 private Long categoryId;
 
 @ToOne(joinProperty = "categoryId")
 private Category category;
 
 }
 
 
 | 
注解分析
上面的Category类代码中:
@ToMany(referencedJoinProperty = "categoryId")这个注解表明,一个Category可以拥有多个Note(一对多).referencedJoinProperty= "categoryId"表示使用Note类中的categoryId字段进行关联。注意这个字段应该是Long类型.在Category中用 List<Note> notes表示拥有的Note.
上面的Note类代码中:
@ToOne(joinProperty = "categoryId")这个注解表明,一个Note属于一个Category。注意我们添加了private Long categoryId这字段,然后在@ToOne注解中使用joinProperty = "categoryId"把Category用categoryId关联起来。
经过在一的端(Category)使用@ToMany,在多的端(Note)使用@ToOne,我们就把一对多和多对一关联关系建立起来了。
使用
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 
 | Category category = new Category(1L,"技术分享");
 categoryDao.insert(category);
 
 
 category = new Category(2L,"心灵鸡汤");
 categoryDao.insert(category);
 
 
 Note note = new Note();
 note.setText("这是note内容文本,技术分享");
 note.setComment("这是note的comment");
 note.setDate(new Date());
 note.setType(NoteType.TEXT);
 note.setCategoryId(1L);
 noteDao.insert(note);
 
 
 note = new Note();
 note.setText("这是note内容文本,也是技术分享");
 note.setComment("这是note的comment");
 note.setDate(new Date());
 note.setType(NoteType.TEXT);
 note.setCategoryId(1L);
 noteDao.insert(note);
 
 
 note = new Note();
 note.setText("这是note内容文本,心灵鸡汤");
 note.setComment("这是note的comment");
 note.setDate(new Date());
 note.setType(NoteType.TEXT);
 note.setCategoryId(2L);
 noteDao.insert(note);
 
 
 List<Note> notes = categoryDao.load(1L).getNotes();
 System.out.println(notes);
 
 noteDao.load(1L).getCategory().getName();
 
 
 notes = noteDao.queryBuilder().where(NoteDao.Properties.Text.like("%心灵鸡汤%")).list();
 System.out.println(notes);
 
 |