标签:support 解决 xtend date zhang content 方案 detail rri
Android Room支持数据库表Java对象通过注解符@Embedded内嵌一个Java对象。这样就像过去的ORM数据库一样,比如构造一个名为Info的Java对象,作为一个成员变量添加到User里面:
package zhangphil.demo; import android.arch.persistence.room.ColumnInfo; import android.arch.persistence.room.Embedded; import android.arch.persistence.room.Entity; import android.arch.persistence.room.PrimaryKey; /** * Created by Phil on 2017/11/22. */ @Entity(tableName = "user_table") public class User { @PrimaryKey(autoGenerate = true) public int userId; @ColumnInfo(name = "userName") public String name; @ColumnInfo(name = "userAge") public int age; @ColumnInfo(name = "updateTime") public long updateTime; @Embedded public Info info; }
package zhangphil.demo; import android.arch.persistence.room.ColumnInfo; import android.arch.persistence.room.Entity; import android.arch.persistence.room.PrimaryKey; /** * Created by Phil on 2017/11/23. */ @Entity(tableName = "info_table") public class Info { @PrimaryKey(autoGenerate = true) public int infoId; @ColumnInfo(name = "blog") public String blog; @ColumnInfo(name = "content") public String content; }
package zhangphil.demo; import android.arch.persistence.room.Room; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import java.util.List; public class MainActivity extends AppCompatActivity { private String TAG = "输出"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); new Thread(new Runnable() { @Override public void run() { databaseOperation(); } }).start(); } private void databaseOperation() { UserDatabase mUserDatabase = Room.databaseBuilder(getApplicationContext(), UserDatabase.class, "users").build(); UserDao mUserDao = mUserDatabase.getUserDao(); //写数据库 writeUserDatabase(mUserDao, "zhangphil", 18); readDatabase(mUserDao); //关闭数据库 mUserDatabase.close(); } private void readDatabase(UserDao dao) { Log.d(TAG, "读数据库..."); List<User> users = dao.getAllUsers(); for (User u : users) { Log.d(TAG, u.userId + "," + u.name + "," + u.age + ","+u.info.blog+","+u.info.content); } Log.d(TAG, "读数据库完毕."); } private void writeUserDatabase(UserDao dao, String name, int age) { Info info = new Info(); info.blog = "http://blog.csdn.net/zhangphil"; info.content = "Android"; User user = new User(); user.name = name; user.age = age; user.updateTime = System.currentTimeMillis(); user.info = info; dao.insertUser(user); } }
代码运行结果,logcat输出:
11-24 09:20:00.716 30805-30851/zhangphil.demo D/输出: 读数据库... 11-24 09:20:00.723 30805-30851/zhangphil.demo D/输出: 1,zhangphil,18,http://blog.csdn.net/zhangphil,Android 11-24 09:20:00.723 30805-30851/zhangphil.demo D/输出: 读数据库完毕.
Android官方ORM数据库Room技术解决方案:@Embedded内嵌对象(二)
标签:support 解决 xtend date zhang content 方案 detail rri
原文地址:http://blog.csdn.net/zhangphil/article/details/78621009