【Android】Room新手快速入门

Room是什么

Room是Google推出的一款android平台上的ORM数据库框架

它类似于GreenDao,但比GreenDao更加简洁高效,是官方推荐使用的数据库框架

引入Gradle依赖


    //Room
    api 'androidx.room:room-runtime:2.0.0'
    api 'androidx.room:room-rxjava2:2.0.0'
    annotationProcessor 'androidx.room:room-compiler:2.0.0'

定义表结构


	package com.android.code;
	
	import androidx.room.Entity;
	import androidx.room.Ignore;
	import androidx.room.PrimaryKey;
	
	@Entity
	public class User {
	
	    @PrimaryKey(autoGenerate = true)
	    public Long recordId;
	
	    public String account;
	
	    public String password;
	
	    public String name;
	
	    @Ignore
	    public transient Object extra;
	}

创建Dao


	package com.android.code;
	
	import androidx.room.Dao;
	import androidx.room.Delete;
	import androidx.room.Insert;
	import androidx.room.OnConflictStrategy;
	import androidx.room.Query;
	import androidx.room.Update;
	
	import java.util.List;
	
	@Dao
	public interface UserDao {
	
	    @Query("select count(*) from USER")
	    Long count();
	
	    @Query("select * from USER")
	    List<User> loadAll();
	
	    @Insert(onConflict = OnConflictStrategy.REPLACE)
	    void insert(User user);
	
	    @Insert(onConflict = OnConflictStrategy.REPLACE)
	    void insertAll(List<User> users);
	
	    @Update
	    void update(User user);
	
	    @Update
	    void updateAll(List<User> users);
	
	    @Delete
	    void delete(User user);
	
	    @Delete
	    void deleteAll(List<User> users);
	}

创建Database


	package com.android.code;
	
	import androidx.room.Database;
	import androidx.room.RoomDatabase;
	
	@Database(
	        entities = {User.class},
	        version = 1,
	        exportSchema = false
	)
	public abstract class UserDatabase extends RoomDatabase {
	
	    public abstract UserDao userDao();
	}

通过Room读写数据库


    //初始化工作
    new Thread(this::init).start();

    //初始化工作
    protected void init() {
        UserDatabase database = Room.databaseBuilder(getApplicationContext(), UserDatabase.class, "room-database").build();
        UserDao userDao = database.userDao();
        User user1 = new User();
        User user2 = new User();
        List<User> userList = Stream.of(user1, user2).collect(Collectors.toList());
        userDao.insertAll(userList);
        Log.e(TAG, userDao.count().toString());
    }

你可能感兴趣的:(android,android,room,orm)