android對象關系映射框架ormlite之一對多(OneToMany)


前兩天,用ormlite對單張表進行了基本的操作,但是,我們知道通常情況對於單張表格進行操作在實際情況中很前兩天不現實,那么ormlite能否像Hibenate那樣實現多張表之間的一對多,多對多(即OneToMany,ManyToMany)的關系映射呢?帶着這個疑問,通過看了官方的文檔,發現確實能夠實現。先來看看One2Many這種情況的實現。

         我在之前的demo基礎上修改了一下,假設用戶和部門之間的關系為多對一,即一個部門對應着多個用戶,而一個用戶只屬於一個部門。同樣先將運行效果圖貼出來。



在我前面的文章中已經對中間的某些注解及類做了解釋這里就不重復了,如有不懂的請先參考: android對象關系映射框架ormlite學習,這里就直接上代碼了,說明就放到了代碼中了。

 

用戶類User.java 

  1. <span style="font-size:18px;">@DatabaseTable(tableName = "tb_user")  
  2. public class User {  
  3.     //用戶編號  
  4.     @DatabaseField(generatedId=true)  
  5.     private int userId;  
  6.     //用戶名  
  7.     @DatabaseField  
  8.     private String userName;  
  9.     //密碼  
  10.     @DatabaseField  
  11.     private int age;  
  12.     //入職時間  
  13.     @DatabaseField(format="DATE_STRING")  
  14.     private Date date;  
  15.     //用戶所屬部門  
  16.     /** 
  17.      * foreign = true:說明這是一個外部引用關系 
  18.      * foreignAutoRefresh = true:當對象被查詢時,外部屬性自動刷新(暫時我也沒看懂其作用) 
  19.      *  
  20.      */  
  21.     @DatabaseField(foreign = true,foreignAutoRefresh = true)  
  22.     private Dept dept;  
  23.       
  24.     public User() {  
  25.         //提供無參構造函數,這樣查詢的時候可以返回查詢出來的對象  
  26.     }  
  27.     public User( int userId,String userName, int age) {  
  28.         this.userId = userId;  
  29.         this.userName = userName;  
  30.         this.age = age;  
  31.     }  
  32.     get/set方法……  
  33. }  
  34. </span>  

 

部門類Dept.java 

  1. <span style="font-size:18px;">/** 
  2.  * 部門(這里假設一個用戶只對應一個部門,而一個部門對應着多個用戶,即一對多的關系) 
  3.  * @author leox 
  4.  * 
  5.  */  
  6. @DatabaseTable(tableName="tb_dept")  
  7. public class Dept {  
  8.     //部門編號  
  9.     @DatabaseField(generatedId=true)  
  10.     private int deptId;  
  11.     //部門名稱  
  12.     @DatabaseField  
  13.     private String deptName;  
  14.     //用戶信息集合  
  15.     @ForeignCollectionField  
  16.     /** 
  17.      * 這里需要注意的是:屬性類型只能是ForeignCollection<T>或者Collection<T> 
  18.      * 如果需要懶加載(延遲加載)可以在@ForeignCollectionField加上參數eager=false 
  19.      * 這個屬性也就說明一個部門對應着多個用戶 
  20.      */  
  21.     private ForeignCollection<User> users;  
  22.       
  23.     public Dept(){  
  24.           
  25.     }  
  26.       
  27.     public Dept(int deptId,String deptName){  
  28.         this.deptId = deptId;  
  29.         this.deptName = deptName;  
  30.     }  
  31.   
  32.     Get()/set()方法……  
  33. }  
  34. </span>  

SqlliteOpenHelper類: 

  1. <span style="font-size:18px;">public class DatabaseHelper extends OrmLiteSqliteOpenHelper{  
  2.     // 數據庫名稱    
  3.     private static final String DATABASE_NAME = "helloAndroid.db";   
  4.     // 數據庫version    
  5.     private static final int DATABASE_VERSION = 1;  
  6.       
  7.     /** 
  8.      * 包含兩個泛型: 
  9.      * 第一個泛型表DAO操作的類 
  10.      * 第二個表示操作類的主鍵類型 
  11.      */  
  12.     private Dao<User, Integer> userDao = null;  
  13.     private Dao<Dept,Integer> deptDao = null;  
  14.       
  15.     private RuntimeExceptionDao<User, Integer> simpleRuntimeUserDao = null;  
  16.     private RuntimeExceptionDao<Dept, Integer> simpleRuntimeDeptDao = null;  
  17.       
  18.     public DatabaseHelper(Context context) {  
  19.         super(context, DATABASE_NAME, null, DATABASE_VERSION);  
  20.     }  
  21.       
  22.     @Override  
  23.     public void onCreate(SQLiteDatabase sqliteDatabase, ConnectionSource connectionSource) {  
  24.         try {  
  25.             Log.i(DatabaseHelper.class.getName(), "onCreate");  
  26.             Log.i("test""name = "+DatabaseHelper.class.getName());  
  27.             TableUtils.createTable(connectionSource, Dept.class);  
  28.             TableUtils.createTable(connectionSource, User.class);  
  29.         } catch (SQLException e) {  
  30.             Log.e(DatabaseHelper.class.getName(), "Can't create database", e);  
  31.             throw new RuntimeException(e);  
  32.         }  
  33.           
  34.     }  
  35.     /** 
  36.      * 插入一條用戶數據 
  37.      */  
  38.     public void insert(User user){  
  39.         RuntimeExceptionDao<User, Integer> dao = getSimpleDataUserDao();  
  40.         //通過實體對象創建在數據庫中創建一條數據,成功返回1,說明插入了一條數據  
  41.         Log.i("test""dao = " + dao+"  user= "+user);  
  42.         int returnValue = dao.create(user);  
  43.         Log.i("test""插入數據后返回值:"+returnValue);  
  44.     }  
  45.     /** 
  46.      * 查詢所有的用戶信息 
  47.      * @return 
  48.      */  
  49.     public List<User> findAllUser(){  
  50.         RuntimeExceptionDao<User, Integer> dao = getSimpleDataUserDao();  
  51.         return dao.queryForAll();  
  52.     }  
  53.       
  54.     public RuntimeExceptionDao<User, Integer> getSimpleDataUserDao() {  
  55.         if (simpleRuntimeUserDao == null) {  
  56.             simpleRuntimeUserDao = getRuntimeExceptionDao(User.class);  
  57.         }  
  58.         Log.i("test""simpleRuntimeDao ======= "+simpleRuntimeUserDao);  
  59.         return simpleRuntimeUserDao;  
  60.     }  
  61.   
  62.     /** 
  63.      * 這個方法在你的應用升級以及它有一個更高的版本號時調用。所以需要你調整各種數據來適應新的版本 
  64.      */  
  65.     @Override  
  66.     public void onUpgrade(SQLiteDatabase sqliteDatabase, ConnectionSource connectionSource, int oldVersion,  
  67.             int newVersion) {  
  68.         Log.i("test""更新....");  
  69.         try {  
  70.             Log.i(DatabaseHelper.class.getName(), "onUpgrade");  
  71.             //刪掉舊版本的數據  
  72.             TableUtils.dropTable(connectionSource, User.classtrue);  
  73.             TableUtils.dropTable(connectionSource, Dept.classtrue);  
  74.             //創建一個新的版本  
  75.             onCreate(sqliteDatabase, connectionSource);  
  76.         } catch (SQLException e) {  
  77.             Log.e(DatabaseHelper.class.getName(), "Can't drop databases", e);  
  78.             throw new RuntimeException(e);  
  79.         }  
  80.     }  
  81.       
  82.     public Dao<User, Integer> getDao() throws SQLException {  
  83.         if (userDao == null) {  
  84.             userDao = getDao(User.class);  
  85.         }  
  86.         return userDao;  
  87.     }  
  88.       
  89.     /***************************************以下為部門操作******************************************/  
  90.       
  91.     public Dao<Dept, Integer> getDeptDao() throws SQLException {  
  92.         if (deptDao == null) {  
  93.             deptDao = getDao(Dept.class);  
  94.         }  
  95.         return deptDao;  
  96.     }  
  97.       
  98.     public RuntimeExceptionDao<Dept, Integer> getSimpleDataDeptDao() {  
  99.         if (simpleRuntimeDeptDao == null) {  
  100.             simpleRuntimeDeptDao = getRuntimeExceptionDao(Dept.class);  
  101.         }  
  102.         Log.i("test""simpleRuntimeDaodeptdept ======= "+simpleRuntimeDeptDao);  
  103.         return simpleRuntimeDeptDao;  
  104.     }  
  105.       
  106.     /** 
  107.      * 插入一條部門數據 
  108.      */  
  109.     public void insertDept(Dept dept){  
  110.         RuntimeExceptionDao<Dept, Integer> dao = getSimpleDataDeptDao();  
  111.         //通過實體對象創建在數據庫中創建一條數據,成功返回1,說明插入了一條數據  
  112.         Log.i("test""dao = " + dao+"  dept= "+dept.getDeptName());  
  113.         int returnValue = dao.create(dept);  
  114.         Log.i("test""插入數據后返回值:"+returnValue);  
  115.     }  
  116.       
  117.     /** 
  118.      * 查詢所有的部門信息 
  119.      * @return 
  120.      */  
  121.     public List<Dept> findAllDept(){  
  122.         RuntimeExceptionDao<Dept, Integer> dao = getSimpleDataDeptDao();  
  123.         return dao.queryForAll();  
  124.     }  
  125.       
  126.     public Dept findByDeptId(int deptId){  
  127.         RuntimeExceptionDao<Dept, Integer> dao = getSimpleDataDeptDao();  
  128.         return dao.queryForId(deptId);  
  129.     }  
  130.   
  131. }  
  132. </span>  

 

RegistActivity類:(這個類是模擬了員工錄入,輸入員工信息和所屬部門) 

  1. <span style="font-size:18px;">/** 
  2.  * 員工信息錄入 
  3.  * @author leox 
  4.  * 
  5.  */  
  6. public class RegistActivity  extends Activity {  
  7.     EditText userNameEdit;//用戶名編輯框  
  8.     EditText ageEdit;//年齡編輯框  
  9.     EditText hiredateEdit;//入職時間編輯框  
  10.     EditText deptEdit;//部門編輯框  
  11.     Button reButton;//提交按鈕  
  12.       
  13.     DatabaseHelper helper = new DatabaseHelper(this);  
  14.     @Override  
  15.     protected void onCreate(Bundle savedInstanceState) {  
  16.         super.onCreate(savedInstanceState);  
  17.         setContentView(R.layout.activity_main);  
  18.         userNameEdit = (EditText)this.findViewById(R.id.et_username);  
  19.         ageEdit = (EditText)this.findViewById(R.id.et_age);  
  20.         hiredateEdit = (EditText)this.findViewById(R.id.et_date);  
  21.         deptEdit = (EditText)this.findViewById(R.id.et_dept);  
  22.         reButton = (Button)this.findViewById(R.id.btn_regist);  
  23.         reButton.setOnClickListener(new myClickListener());  
  24.     }  
  25.   
  26.     @Override  
  27.     public boolean onCreateOptionsMenu(Menu menu) {  
  28.         getMenuInflater().inflate(R.menu.main, menu);  
  29.         return true;  
  30.     }  
  31.       
  32.     class myClickListener implements OnClickListener{  
  33.         @Override  
  34.         public void onClick(View v) {  
  35.             //用戶名  
  36.             String userName = userNameEdit.getText().toString();  
  37.             //年齡  
  38.             String age = ageEdit.getText().toString();  
  39.             String da = hiredateEdit.getText().toString();  
  40.             //入職時間  
  41.             DateFormat df = new SimpleDateFormat("yyyy-MM-dd");  
  42.             Date hiredate=null;  
  43.             try {  
  44.                 hiredate = df.parse(da);  
  45.             } catch (ParseException e) {  
  46.                 e.printStackTrace();  
  47.             }  
  48.             Log.i("test""date = "+hiredate);  
  49.             //部門信息  
  50.             String deptName = deptEdit.getText().toString();  
  51.             List<Dept> depts = helper.findAllDept();  
  52.             Dept dept = null;  
  53.             //查詢出所有的部門信息,如果輸入的部門名數據庫中不存在那就創建一條新的記錄,如果存在則采用原有  
  54.             if(depts.size()>0){  
  55.                 for(Dept d:depts){  
  56.                     if(d.getDeptName().equals(deptName)){  
  57.                         dept = d;  
  58.                     }else{  
  59.                         dept = new Dept();  
  60.                         dept.setDeptName(deptName);  
  61.                         //插入部門信息  
  62.                         helper.insertDept(dept);  
  63.                     }  
  64.                 }  
  65.             }else{  
  66.                 dept = new Dept();  
  67.                 dept.setDeptName(deptName);  
  68.                 //插入部門信息  
  69.                 helper.insertDept(dept);  
  70.             }  
  71.               
  72.             //用戶信息  
  73.             User user = new User();  
  74.             user.setUserName(userName);  
  75.             user.setAge(Integer.parseInt(age));  
  76.             user.setDate(hiredate);  
  77.             user.setDept(dept);  
  78.             //插入用戶信息  
  79.             helper.insert(user);  
  80.               
  81.             Intent intent = new Intent();  
  82.             intent.setClass(RegistActivity.this, MainActivity.class);  
  83.             startActivity(intent);  
  84.         }  
  85.           
  86.     }  
  87. }  
  88. </span>  

對應的布局文件:activity_main.xml 

  1. <span style="font-size:18px;"><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     xmlns:tools="http://schemas.android.com/tools"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:paddingBottom="@dimen/activity_vertical_margin"  
  6.     android:paddingLeft="@dimen/activity_horizontal_margin"  
  7.     android:paddingRight="@dimen/activity_horizontal_margin"  
  8.     android:paddingTop="@dimen/activity_vertical_margin"  
  9.     android:orientation="vertical"  
  10.     android:gravity="center"  
  11.     tools:context=".RegistActivity" >  
  12.   
  13.     <TextView  
  14.         android:layout_width="wrap_content"  
  15.         android:layout_height="wrap_content"  
  16.         android:textSize="20dp"  
  17.         android:text="員工信息錄入" />  
  18.       
  19.     <LinearLayout   
  20.         android:layout_width="fill_parent"  
  21.         android:layout_height="wrap_content"  
  22.         android:gravity="center"  
  23.         android:orientation="horizontal">  
  24.         <TextView   
  25.             android:layout_width="wrap_content"  
  26.             android:layout_height="wrap_content"  
  27.             android:text="用戶名:"/>  
  28.         <EditText  
  29.             android:id="@+id/et_username"  
  30.             android:layout_width="200px"  
  31.             android:layout_height="wrap_content" />  
  32.     </LinearLayout>  
  33.       
  34.     <LinearLayout   
  35.         android:layout_width="fill_parent"  
  36.         android:layout_height="wrap_content"  
  37.         android:gravity="center"  
  38.         android:orientation="horizontal">  
  39.         <TextView   
  40.             android:layout_width="wrap_content"  
  41.             android:layout_height="wrap_content"  
  42.             android:text="年齡:"/>  
  43.         <EditText  
  44.             android:id="@+id/et_age"  
  45.             android:layout_width="200px"  
  46.             android:layout_height="wrap_content"/>  
  47.     </LinearLayout>  
  48.       
  49.     <LinearLayout   
  50.         android:layout_width="fill_parent"  
  51.         android:layout_height="wrap_content"  
  52.         android:gravity="center"  
  53.         android:orientation="horizontal">  
  54.         <TextView   
  55.             android:layout_width="wrap_content"  
  56.             android:layout_height="wrap_content"  
  57.             android:text="入職時間:"/>  
  58.         <EditText  
  59.             android:id="@+id/et_date"  
  60.             android:layout_width="200px"  
  61.             android:layout_height="wrap_content"/>  
  62.     </LinearLayout>  
  63.       
  64.     <LinearLayout   
  65.         android:layout_width="fill_parent"  
  66.         android:layout_height="wrap_content"  
  67.         android:gravity="center"  
  68.         android:orientation="horizontal">  
  69.         <TextView   
  70.             android:layout_width="wrap_content"  
  71.             android:layout_height="wrap_content"  
  72.             android:text="部門:"/>  
  73.         <EditText  
  74.             android:id="@+id/et_dept"  
  75.             android:layout_width="200px"  
  76.             android:layout_height="wrap_content"/>  
  77.     </LinearLayout>  
  78.       
  79.     <Button   
  80.         android:id="@+id/btn_regist"  
  81.         android:layout_width="wrap_content"  
  82.         android:layout_height="wrap_content"  
  83.         android:text="提交"/>  
  84.   
  85. </LinearLayout>  
  86. </span>  

MainActivity.java類,這個類用來操作員工信息錄入按鈕,以及顯示員工信息按鈕的操作 

  1. <span style="font-size:18px;">public class MainActivity extends Activity {  
  2.   
  3.     Button button1;//員工信息錄入按鈕  
  4.     Button button2;//員工信息顯示按鈕  
  5.     TextView textView;//用來顯示查詢到的用戶信息  
  6.     DatabaseHelper helper = new DatabaseHelper(this);  
  7.     @Override  
  8.     protected void onCreate(Bundle savedInstanceState) {  
  9.         super.onCreate(savedInstanceState);  
  10.         setContentView(R.layout.main);  
  11.         button1 = (Button)this.findViewById(R.id.main_btn_inputinfo);  
  12.         button2 = (Button)this.findViewById(R.id.main_btn_show);  
  13.         textView = (TextView)this.findViewById(R.id.main_show_user);  
  14.         //點擊注冊按鈕跳轉到注冊頁面  
  15.         button1.setOnClickListener(new OnClickListener() {  
  16.             @Override  
  17.             public void onClick(View v) {  
  18.                 Intent intent = new Intent();  
  19.                 intent.setClass(MainActivity.this, RegistActivity.class);  
  20.                 startActivity(intent);  
  21.             }  
  22.         });  
  23.         //點擊“顯示”按鈕跳轉到用戶信息顯示頁面並將注冊用戶信息顯示出來  
  24.         button2.setOnClickListener(new OnClickListener() {  
  25.             @Override  
  26.             public void onClick(View v) {  
  27.                 List<Dept> list = helper.findAllDept();  
  28.                 Log.i("test""有沒有部門?----------------"+list.size());  
  29.                 Dept dept = null;  
  30.                 if(list.size()>0){  
  31.                     dept = helper.findByDeptId(list.get(0).getDeptId());  
  32.                     ForeignCollection<User> orders = dept.getUsers();  
  33.                     CloseableIterator<User> iterator = orders.closeableIterator();  
  34.                     String str = dept.getDeptName()+" 部門下有以下職員:";  
  35.                     try {  
  36.                         while(iterator.hasNext()){  
  37.                             User user = iterator.next();  
  38.                             str+=user.getUserId()+"號:"+user.getUserName()+" 年齡:"+user.getAge()+"  受雇日期: "+user.getDate()+"   ";  
  39.                         }  
  40.                     } finally {  
  41.                         try {  
  42.                             iterator.close();  
  43.                         } catch (SQLException e) {  
  44.                             e.printStackTrace();  
  45.                         }  
  46.                     }  
  47.                     textView.setText(str);  
  48.                 }else{  
  49.                     textView.setText("親!還沒有部門吧!");  
  50.                 }  
  51.             }  
  52.         });  
  53.           
  54.     }  
  55.   
  56.     @Override  
  57.     public boolean onCreateOptionsMenu(Menu menu) {  
  58.         // Inflate the menu; this adds items to the action bar if it is present.  
  59.         getMenuInflater().inflate(R.menu.main, menu);  
  60.         return true;  
  61.     }  
  62.   
  63. }  
  64. </span>  

對應的布局文件:main.xml 

  1. <span style="font-size:18px;"><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.     xmlns:tools="http://schemas.android.com/tools"  
  3.     android:layout_width="match_parent"  
  4.     android:layout_height="match_parent"  
  5.     android:paddingBottom="@dimen/activity_vertical_margin"  
  6.     android:paddingLeft="@dimen/activity_horizontal_margin"  
  7.     android:paddingRight="@dimen/activity_horizontal_margin"  
  8.     android:paddingTop="@dimen/activity_vertical_margin"  
  9.     android:orientation="vertical"  
  10.     android:gravity="center"  
  11.     tools:context=".MainActivity" >  
  12.   
  13.     <Button   
  14.         android:id="@+id/main_btn_inputinfo"  
  15.         android:layout_width="wrap_content"  
  16.         android:layout_height="wrap_content"  
  17.         android:text="員工信息錄入"/>  
  18.       
  19.     <Button   
  20.         android:id="@+id/main_btn_show"  
  21.         android:layout_width="wrap_content"  
  22.         android:layout_height="wrap_content"  
  23.         android:text="員工信息顯示"/>  
  24.       
  25.     <!-- <Button   
  26.         android:id="@+id/main_btn_delete"  
  27.         android:layout_width="wrap_content"  
  28.         android:layout_height="wrap_content"  
  29.         android:text="刪除"/>  
  30.       
  31.     <Button   
  32.         android:id="@+id/main_btn_deleteAll"  
  33.         android:layout_width="wrap_content"  
  34.         android:layout_height="wrap_content"  
  35.         android:text="批量刪除"/> -->  
  36.       
  37.     <TextView   
  38.         android:id="@+id/main_show_user"  
  39.         android:layout_width="wrap_content"  
  40.         android:layout_height="wrap_content"/>  
  41.   
  42. </LinearLayout>  
  43. </span>  



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM