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

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

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

用户类User.java

@DatabaseTable(tableName = "tb_user")
public class User {//用户编号@DatabaseField(generatedId=true)private int userId;//用户名@DatabaseFieldprivate String userName;//密码@DatabaseFieldprivate 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方法……
}

部门类Dept.java

/*** 部门(这里假设一个用户只对应一个部门,而一个部门对应着多个用户,即一对多的关系)* @author leox**/
@DatabaseTable(tableName="tb_dept")
public class Dept {//部门编号@DatabaseField(generatedId=true)private int deptId;//部门名称@DatabaseFieldprivate 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()方法……
}

SqlliteOpenHelper类:

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);}@Overridepublic 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;}/*** 这个方法在你的应用升级以及它有一个更高的版本号时调用。所以需要你调整各种数据来适应新的版本*/@Overridepublic 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);}}

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

/*** 员工信息录入* @author leox**/
public class RegistActivity  extends Activity {EditText userNameEdit;//用户名编辑框EditText ageEdit;//年龄编辑框EditText hiredateEdit;//入职时间编辑框EditText deptEdit;//部门编辑框Button reButton;//提交按钮DatabaseHelper helper = new DatabaseHelper(this);@Overrideprotected 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());}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {getMenuInflater().inflate(R.menu.main, menu);return true;}class myClickListener implements OnClickListener{@Overridepublic 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);}}
}

对应的布局文件:activity_main.xml

<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" ><TextViewandroid: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="用户名:"/><EditTextandroid: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="年龄:"/><EditTextandroid: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="入职时间:"/><EditTextandroid: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="部门:"/><EditTextandroid: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>

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

public class MainActivity extends Activity {Button button1;//员工信息录入按钮Button button2;//员工信息显示按钮TextView textView;//用来显示查询到的用户信息DatabaseHelper helper = new DatabaseHelper(this);@Overrideprotected 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() {@Overridepublic void onClick(View v) {Intent intent = new Intent();intent.setClass(MainActivity.this, RegistActivity.class);startActivity(intent);}});//点击“显示”按钮跳转到用户信息显示页面并将注册用户信息显示出来button2.setOnClickListener(new OnClickListener() {@Overridepublic 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("亲!还没有部门吧!");}}});}@Overridepublic 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;}}

对应的布局文件:main.xml

<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>

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

  1. android对象关系映射框架ormlite学习之单表操作

    总感觉用原始的SQLLiteHelper操作数据库有点麻烦,上网找了些android数据库orm框架,对比了一下,现在使用ormlite的人貌似挺多的,在网上找了ormlite官方文档,根据官方文档, ...

  2. netsuite 数据集成_Java中带有NetSuite数据实体的对象关系映射(ORM)

    netsuite 数据集成 对象关系映射(ORM)技术使使用关系数据源更加容易,并且可以将逻辑业务模型与物理存储模型联系在一起. 遵循本教程,将NetSuite数据的连接集成到基于Java的ORM框架 ...

  3. Java中带有NetSuite数据实体的对象关系映射(ORM)

    对象关系映射(ORM)技术使使用关系数据源更容易,并且可以将逻辑业务模型与物理存储模型联系在一起. 遵循本教程,将与NetSuite数据的连接集成到基于Java的ORM框架Hibernate中. 您可 ...

  4. 【分享】关于对象关系映射的理解

    对象关系映射(Object Relational Mapping,简称ORM)是一种为了解决面向对象与关系数据库存在的互不匹配的现象的技术. 简单的说,ORM是通过使用描述对象和数据库之间映射的元数据 ...

  5. C++ 对象关系映射(ORM)介绍

    用过Java的都知道SSH框架,特别对于数据库开发,Java领域有无数的ORM框架,供数据持久层调用,如Hibernate,iBatis(现在改名叫MyBatis),TopLink,JDO,JPA-- ...

  6. ORM(Object Relational Mapping,对象/关系映射)

    ORM(Object Relational Mapping,对象/关系映射) 在考虑O/R Mapping的时候,有两个概念是经常会接触的,那就是VO和PO. 所谓的VO,就是Value Object ...

  7. 学习笔记之什么是持久化和对象关系映射ORM技术

    ----------------本文转自:http://www.cppblog.com/javenstudio/articles/541.html--------------------- 何谓&qu ...

  8. 鸿蒙对象关系映射数据库

    对象关系映射数据库 对象关系映射数据库简介 对象关系映射数据库存储开发步骤 1.添加配置 2.数据库的创建 3.数据表(实体对象类)的创建 4.使用对象数据操作接口OrmContext创建数据库 5. ...

  9. Hibernate对象关系映射详解之一对多关系映射

    Hibernate对象关系映射详解之"一对多"关系映射 之前学习Hibernate框架的时候,对这七大关系映射一直是云里雾里的,虽然可以仿照写出代码,但是不能独立编写出来.鉴于工作 ...

最新文章

  1. iOS:CALayer核心动画层
  2. python dlib学习(一):人脸检测
  3. 全国 省市 自治区的数据库sql生成
  4. 【C#公共帮助类】JsonHelper 操作帮助类, 以后再也不用满地找Json了,拿来直接用...
  5. mysql5.7主从同步与读写分离
  6. Visual Studio将原生支持WSL 2
  7. FileBeat + Pipeline 解析日志 保存至ElasticSearch(实战)
  8. node mysql查询回调_nodejs 数据库查询回调问题
  9. 初始化一个指针的方法
  10. 魔改部署自己专属的合成大西瓜(一:运行篇)
  11. 计算机无法安装新字体,怎么给电脑安装新字体
  12. VBA函数:int()函数
  13. 推荐一个在线视频学习、在线试题练习、在线同步考试开源系统
  14. 产品专利和方法专利对比分析
  15. php get defined,php中get_defined_constants函数用法实例分析
  16. 单相变压器的平衡方程式
  17. ubuntu 使用代理服务器 squid
  18. Inkcanvas 放大缩小变换
  19. java提供按摩比较复数大小_复数类实现 - kb
  20. 跃迁:从技术到管理的硅谷路径

热门文章

  1. Oracle收购Talari,第一家SD-WAN公有云提供商出现
  2. 视频AI对话杭州云栖:新一代视频智能生产的探索与实践
  3. 云搜索服务在APP搜索场景的应用
  4. Spark createDirectStream 维护 Kafka offset(Scala)
  5. php 简单日志搜索
  6. linux 下ip命令对比ifconfig命令
  7. class.sitemap.php
  8. 傻瓜神经网络入门指南
  9. day19-URL+视图+模板+ORM
  10. NBR100多IP出口解决方案的配置方法