2016-04-07 171 views
0

如何查询将另一个对象作为属性的对象?我也需要获得财产的价值。这里是我的模型:Android sqllite,查询属于另一个对象属性的对象

public class Department { 
public int DeptId; 
public string DeptName; 
} 

public class Employee { 
public int Id; 
public string Name; 
public int DeptId; 
public Department Department; 
} 

我来自c#背景,我可以用c#使用实体框架来做到这一点。现在看起来这个模型可以工作,但是当我为对象包含一个sqllite功能时,我不知道如何查询它。

这是我的第一次尝试,但我不知道这是最好的方式

public List<Employee> getAllEmployeesWithDepartments(){ 
    List<Employee> employees = new ArrayList<>(); 
    SQLiteDatabase db = this.getReadableDatabase(); 
    Cursor res = db.rawQuery("SELECT * FROM Employee e LEFT JOIN Department d on e.DeptId = d.Id" , null); 

    if(res.moveToFirst()){ 
     do{ 
      Employee emp = new Employee(); 
      emp.Id = res.getInt(res.getColumnIndex("Id")); 
      emp.Name = res.getString(res.getColumnIndex("Name")); 

      Department dep = new Department(); 
      dep.Id = res.getInt(res.getColumnIndex("Id")); 
      dep.Name = res.getString(res.getColumnIndex("Name")); 

      emp.Department = dep; 
      employees.add(emp); 
     }while (res.moveToNext()); 
    } 
    return employees; 
} 

回答

0

你困惑。 SQLite没有对象。它是基于表格的数据库(就像几乎所有的数据库一样)您可以将对象映射到表中,但您必须自己创建这些映射。由于SQLite没有对象,它绝对没有子对象。通常通过在主表上加入另一个具有外键约束的表来实现类似的效果,但它确实由您的模式定义。对你没有一般的答案。

相关问题