您的位置:首页 > 移动开发 > Android开发

android对象关系映射框架ormlite之一对多(OneToMany)

2014-03-17 09:55 253 查看
前两天,用ormlite对单张表进行了基本的操作,但是,我们知道通常情况对于单张表格进行操作在实际情况中很前两天不现实,那么ormlite能否像Hibenate那样实现多张表之间的一对多,多对多(即OneToMany,ManyToMany)的关系映射呢?带着这个疑问,通过看了官方的文档,发现确实能够实现。先来看看One2Many这种情况的实现。

我在之前的demo基础上修改了一下,假设用户和部门之间的关系为多对一,即一个部门对应着多个用户,而一个用户只属于一个部门。同样先将运行效果图贴出来。





在我前面的文章中已经对中间的某些注解及类做了解释这里就不重复了,如有不懂的请先参考: android对象关系映射框架ormlite学习,这里就直接上代码了,说明就放到了代码中了。

用户类User.java

<span style="font-size:18px;">@DatabaseTable(tableName = "tb_user")

public class User {

//用户编号

@DatabaseField(generatedId=true)

private int userId;

//用户名

@DatabaseField

private String userName;

//密码

@DatabaseField

private int age;

//入职时间

@DatabaseField(format="DATE_STRING")

private Date date;

//用户所属部门

/**

* foreign = true:说明这是一个外部引用关系

* foreignAutoRefresh = true:当对象被查询时,外部属性自动刷新(暂时我也没看懂其作用)

*

*/

@DatabaseField(foreign = true,foreignAutoRefresh = true)

private Dept dept;

public User() {

//提供无参构造函数,这样查询的时候可以返回查询出来的对象

}

public User( int userId,String userName, int age) {

this.userId = userId;

this.userName = userName;

this.age = age;

}

get/set方法……

}

</span>

部门类Dept.java

<span style="font-size:18px;">/**

* 部门(这里假设一个用户只对应一个部门,而一个部门对应着多个用户,即一对多的关系)

* @author leox

*

*/

@DatabaseTable(tableName="tb_dept")

public class Dept {

//部门编号

@DatabaseField(generatedId=true)

private int deptId;

//部门名称

@DatabaseField

private String deptName;

//用户信息集合

@ForeignCollectionField

/**

* 这里需要注意的是:属性类型只能是ForeignCollection<T>或者Collection<T>

* 如果需要懒加载(延迟加载)可以在@ForeignCollectionField加上参数eager=false

* 这个属性也就说明一个部门对应着多个用户

*/

private ForeignCollection<User> users;

public Dept(){

}

public Dept(int deptId,String deptName){

this.deptId = deptId;

this.deptName = deptName;

}

Get()/set()方法……

}

</span>

SqlliteOpenHelper类:

<span style="font-size:18px;">public class DatabaseHelper extends OrmLiteSqliteOpenHelper{

// 数据库名称

private static final String DATABASE_NAME = "helloAndroid.db";

// 数据库version

private static final int DATABASE_VERSION = 1;

/**

* 包含两个泛型:

* 第一个泛型表DAO操作的类

* 第二个表示操作类的主键类型

*/

private Dao<User, Integer> userDao = null;

private Dao<Dept,Integer> deptDao = null;

private RuntimeExceptionDao<User, Integer> simpleRuntimeUserDao = null;

private RuntimeExceptionDao<Dept, Integer> simpleRuntimeDeptDao = null;

public DatabaseHelper(Context context) {

super(context, DATABASE_NAME, null, DATABASE_VERSION);

}

@Override

public void onCreate(SQLiteDatabase sqliteDatabase, ConnectionSource connectionSource) {

try {

Log.i(DatabaseHelper.class.getName(), "onCreate");

Log.i("test", "name = "+DatabaseHelper.class.getName());

TableUtils.createTable(connectionSource, Dept.class);

TableUtils.createTable(connectionSource, User.class);

} catch (SQLException e) {

Log.e(DatabaseHelper.class.getName(), "Can't create database", e);

throw new RuntimeException(e);

}

}

/**

* 插入一条用户数据

*/

public void insert(User user){

RuntimeExceptionDao<User, Integer> dao = getSimpleDataUserDao();

//通过实体对象创建在数据库中创建一条数据,成功返回1,说明插入了一条数据

Log.i("test", "dao = " + dao+" user= "+user);

int returnValue = dao.create(user);

Log.i("test", "插入数据后返回值:"+returnValue);

}

/**

* 查询所有的用户信息

* @return

*/

public List<User> findAllUser(){

RuntimeExceptionDao<User, Integer> dao = getSimpleDataUserDao();

return dao.queryForAll();

}

public RuntimeExceptionDao<User, Integer> getSimpleDataUserDao() {

if (simpleRuntimeUserDao == null) {

simpleRuntimeUserDao = getRuntimeExceptionDao(User.class);

}

Log.i("test", "simpleRuntimeDao ======= "+simpleRuntimeUserDao);

return simpleRuntimeUserDao;

}

/**

* 这个方法在你的应用升级以及它有一个更高的版本号时调用。所以需要你调整各种数据来适应新的版本

*/

@Override

public void onUpgrade(SQLiteDatabase sqliteDatabase, ConnectionSource connectionSource, int oldVersion,

int newVersion) {

Log.i("test", "更新....");

try {

Log.i(DatabaseHelper.class.getName(), "onUpgrade");

//删掉旧版本的数据

TableUtils.dropTable(connectionSource, User.class, true);

TableUtils.dropTable(connectionSource, Dept.class, true);

//创建一个新的版本

onCreate(sqliteDatabase, connectionSource);

} catch (SQLException e) {

Log.e(DatabaseHelper.class.getName(), "Can't drop databases", e);

throw new RuntimeException(e);

}

}

public Dao<User, Integer> getDao() throws SQLException {

if (userDao == null) {

userDao = getDao(User.class);

}

return userDao;

}

/***************************************以下为部门操作******************************************/

public Dao<Dept, Integer> getDeptDao() throws SQLException {

if (deptDao == null) {

deptDao = getDao(Dept.class);

}

return deptDao;

}

public RuntimeExceptionDao<Dept, Integer> getSimpleDataDeptDao() {

if (simpleRuntimeDeptDao == null) {

simpleRuntimeDeptDao = getRuntimeExceptionDao(Dept.class);

}

Log.i("test", "simpleRuntimeDaodeptdept ======= "+simpleRuntimeDeptDao);

return simpleRuntimeDeptDao;

}

/**

* 插入一条部门数据

*/

public void insertDept(Dept dept){

RuntimeExceptionDao<Dept, Integer> dao = getSimpleDataDeptDao();

//通过实体对象创建在数据库中创建一条数据,成功返回1,说明插入了一条数据

Log.i("test", "dao = " + dao+" dept= "+dept.getDeptName());

int returnValue = dao.create(dept);

Log.i("test", "插入数据后返回值:"+returnValue);

}

/**

* 查询所有的部门信息

* @return

*/

public List<Dept> findAllDept(){

RuntimeExceptionDao<Dept, Integer> dao = getSimpleDataDeptDao();

return dao.queryForAll();

}

public Dept findByDeptId(int deptId){

RuntimeExceptionDao<Dept, Integer> dao = getSimpleDataDeptDao();

return dao.queryForId(deptId);

}

}

</span>

RegistActivity类:(这个类是模拟了员工录入,输入员工信息和所属部门)

<span style="font-size:18px;">/**

* 员工信息录入

* @author leox

*

*/

public class RegistActivity extends Activity {

EditText userNameEdit;//用户名编辑框

EditText ageEdit;//年龄编辑框

EditText hiredateEdit;//入职时间编辑框

EditText deptEdit;//部门编辑框

Button reButton;//提交按钮

DatabaseHelper helper = new DatabaseHelper(this);

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

userNameEdit = (EditText)this.findViewById(R.id.et_username);

ageEdit = (EditText)this.findViewById(R.id.et_age);

hiredateEdit = (EditText)this.findViewById(R.id.et_date);

deptEdit = (EditText)this.findViewById(R.id.et_dept);

reButton = (Button)this.findViewById(R.id.btn_regist);

reButton.setOnClickListener(new myClickListener());

}

@Override

public boolean onCreateOptionsMenu(Menu menu) {

getMenuInflater().inflate(R.menu.main, menu);

return true;

}

class myClickListener implements OnClickListener{

@Override

public void onClick(View v) {

//用户名

String userName = userNameEdit.getText().toString();

//年龄

String age = ageEdit.getText().toString();

String da = hiredateEdit.getText().toString();

//入职时间

DateFormat df = new SimpleDateFormat("yyyy-MM-dd");

Date hiredate=null;

try {

hiredate = df.parse(da);

} catch (ParseException e) {

e.printStackTrace();

}

Log.i("test", "date = "+hiredate);

//部门信息

String deptName = deptEdit.getText().toString();

List<Dept> depts = helper.findAllDept();

Dept dept = null;

//查询出所有的部门信息,如果输入的部门名数据库中不存在那就创建一条新的记录,如果存在则采用原有

if(depts.size()>0){

for(Dept d:depts){

if(d.getDeptName().equals(deptName)){

dept = d;

}else{

dept = new Dept();

dept.setDeptName(deptName);

//插入部门信息

helper.insertDept(dept);

}

}

}else{

dept = new Dept();

dept.setDeptName(deptName);

//插入部门信息

helper.insertDept(dept);

}

//用户信息

User user = new User();

user.setUserName(userName);

user.setAge(Integer.parseInt(age));

user.setDate(hiredate);

user.setDept(dept);

//插入用户信息

helper.insert(user);

Intent intent = new Intent();

intent.setClass(RegistActivity.this, MainActivity.class);

startActivity(intent);

}

}

}

</span>

对应的布局文件:activity_main.xml

<span style="font-size:18px;"><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:paddingBottom="@dimen/activity_vertical_margin"

android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"

android:orientation="vertical"

android:gravity="center"

tools:context=".RegistActivity" >

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:textSize="20dp"

android:text="员工信息录入" />

<LinearLayout

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:gravity="center"

android:orientation="horizontal">

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="用户名:"/>

<EditText

android:id="@+id/et_username"

android:layout_width="200px"

android:layout_height="wrap_content" />

</LinearLayout>

<LinearLayout

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:gravity="center"

android:orientation="horizontal">

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="年龄:"/>

<EditText

android:id="@+id/et_age"

android:layout_width="200px"

android:layout_height="wrap_content"/>

</LinearLayout>

<LinearLayout

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:gravity="center"

android:orientation="horizontal">

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="入职时间:"/>

<EditText

android:id="@+id/et_date"

android:layout_width="200px"

android:layout_height="wrap_content"/>

</LinearLayout>

<LinearLayout

android:layout_width="fill_parent"

android:layout_height="wrap_content"

android:gravity="center"

android:orientation="horizontal">

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="部门:"/>

<EditText

android:id="@+id/et_dept"

android:layout_width="200px"

android:layout_height="wrap_content"/>

</LinearLayout>

<Button

android:id="@+id/btn_regist"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="提交"/>

</LinearLayout>

</span>

MainActivity.java类,这个类用来操作员工信息录入按钮,以及显示员工信息按钮的操作

<span style="font-size:18px;">public class MainActivity extends Activity {

Button button1;//员工信息录入按钮

Button button2;//员工信息显示按钮

TextView textView;//用来显示查询到的用户信息

DatabaseHelper helper = new DatabaseHelper(this);

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

button1 = (Button)this.findViewById(R.id.main_btn_inputinfo);

button2 = (Button)this.findViewById(R.id.main_btn_show);

textView = (TextView)this.findViewById(R.id.main_show_user);

//点击注册按钮跳转到注册页面

button1.setOnClickListener(new OnClickListener() {

@Override

public void onClick(View v) {

Intent intent = new Intent();

intent.setClass(MainActivity.this, RegistActivity.class);

startActivity(intent);

}

});

//点击“显示”按钮跳转到用户信息显示页面并将注册用户信息显示出来

button2.setOnClickListener(new OnClickListener() {

@Override

public void onClick(View v) {

List<Dept> list = helper.findAllDept();

Log.i("test", "有没有部门?----------------"+list.size());

Dept dept = null;

if(list.size()>0){

dept = helper.findByDeptId(list.get(0).getDeptId());

ForeignCollection<User> orders = dept.getUsers();

CloseableIterator<User> iterator = orders.closeableIterator();

String str = dept.getDeptName()+" 部门下有以下职员:";

try {

while(iterator.hasNext()){

User user = iterator.next();

str+=user.getUserId()+"号:"+user.getUserName()+" 年龄:"+user.getAge()+" 受雇日期: "+user.getDate()+" ";

}

} finally {

try {

iterator.close();

} catch (SQLException e) {

e.printStackTrace();

}

}

textView.setText(str);

}else{

textView.setText("亲!还没有部门吧!");

}

}

});

}

@Override

public boolean onCreateOptionsMenu(Menu menu) {

// Inflate the menu; this adds items to the action bar if it is present.

getMenuInflater().inflate(R.menu.main, menu);

return true;

}

}

</span>

对应的布局文件:main.xml

<span style="font-size:18px;"><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:paddingBottom="@dimen/activity_vertical_margin"

android:paddingLeft="@dimen/activity_horizontal_margin"

android:paddingRight="@dimen/activity_horizontal_margin"

android:paddingTop="@dimen/activity_vertical_margin"

android:orientation="vertical"

android:gravity="center"

tools:context=".MainActivity" >

<Button

android:id="@+id/main_btn_inputinfo"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="员工信息录入"/>

<Button

android:id="@+id/main_btn_show"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="员工信息显示"/>

<!-- <Button

android:id="@+id/main_btn_delete"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="删除"/>

<Button

android:id="@+id/main_btn_deleteAll"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="批量删除"/> -->

<TextView

android:id="@+id/main_show_user"

android:layout_width="wrap_content"

android:layout_height="wrap_content"/>

</LinearLayout>

</span>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: