自己用Java的注解實現了Android SQLite的ORM庫,之前寫過XML的,不過感覺不是很穩定,效率、魯棒性各方面都不太好,今天花了一下午的時間,補全了所有的注解、注釋,生成了javadoc,寫了樣例程序,並發布到了Github上,地址是:https://github.com/Steven-Luo/AnnotationDao,感興趣的可以試著用用,比之前純手動實現SQLite數據庫的操作簡單了許多,可擴展性也較好,用法如下:
復制代碼
1 //實體類
2 @Table(name = "dog")
3 public class Dog {
4 private boolean alive;
5 private int id;
6 private String name;
7
8 public Dog() {
9
10 }
11
12 public Dog(boolean alive, String name) {
13 this.alive = alive;
14 this.name = name;
15 }
16
17 @Id(name = "id")
18 @Column(name = "id", type = DataType.Integer)
19 public int getId() {
20 return id;
21 }
22
23 @Column(name = "name", type = DataType.Varchar, length = 20)
24 public String getName() {
25 return name;
26 }
27
28 @Column(name = "alive", type = DataType.Boolean)
29 public boolean isAlive() {
30 return alive;
31 }
32
33 public void setAlive(boolean alive) {
34 this.alive = alive;
35 }
36
37 public void setId(int id) {
38 this.id = id;
39 }
40
41 public void setName(String name) {
42 this.name = name;
43 }
44 }
45
46 //添加
47 AnnotationDao dao = new AnnotationDao(this, Dog.class);
48
49 String name = "dog1";
50 boolean alive = true;
51
52 Dog dog = new Dog(alive, name);
53 dao.insert(dog);
54
55 //查找
56 //列出所有對象
57 List list = dao.list();
58 //根據ID查詢
59 dao.query(3);
60
61 //刪除
62 dao.delete(dog);
63
64 //更新,更新時需要保證id字段跟數據庫中的值是對應的,也就是之前調用list或query取出來的
65 dog.setName("dog2");
66 dao.update(dog);