当前位置:   article > 正文

数据库room简单使用_dataroom 使用教程

dataroom 使用教程
数据库room简单使用(参考官网)
三步走
1、建立实体类
2、建立Dao
3、继承虚基类RoomDatabase
引入数据库:
 defaultConfig {
        javaCompileOptions {
            annotationProcessorOptions {
                arguments += [
                        "room.schemaLocation":"$projectDir/schemas".toString(),
                        "room.incremental":"true",
                        "room.expandProjection":"true"]
            }
        }
    }    
dependencies {
    def room_version = "2.4.2"
    implementation "androidx.room:room-runtime:$room_version"
    annotationProcessor "androidx.room:room-compiler:$room_version"
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15

1、建立实体类

@Entity 注解必须加

这个注释将类标记为数据库行。对于每个实体,将创建一个数据库表来保存项目。Entity类必须在database# entities数组中被引用。实体(及其超类)的每个字段都持久化在数据库中,除非另有说明(详见实体文档)。

@PrimaryKey 主键,autoGenerate 指明是否自增长;@ColumnInfo 列的信息,有名称 、数据类型等等

import androidx.room.ColumnInfo;
import androidx.room.Entity;
import androidx.room.PrimaryKey;

@Entity
public class Song {

    @PrimaryKey(autoGenerate = true)
    private int id;
    private String name;
    @ColumnInfo(name = "release_year")
    private int releaseYear;

    public Song(String name, int releaseYear) {
        this.name = name;
        this.releaseYear = releaseYear;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getReleaseYear() {
        return releaseYear;
    }

    public void setReleaseYear(int releaseYear) {
        this.releaseYear = releaseYear;
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
2、建立Dao

增删改查语句,也是采用注解方式,同样@Dao一定不可少

import androidx.room.Dao;
import androidx.room.Delete;
import androidx.room.Insert;
import androidx.room.Query;

import java.util.List;

@Dao
public interface SongDao {

    @Query("SELECT * FROM song")
    List<Song> loadAll();

    @Query("SELECT * FROM song WHERE id IN (:songIds)")
    List<Song> loadAllBySongId(int... songIds);

    @Query("SELECT * FROM song WHERE name LIKE :name AND release_year = :year LIMIT 1")
    Song loadOneByNameAndReleaseYear(String name, int year);

    @Insert
    void insertAll(Song... songs);

    @Insert
    void insert(Song song);

    @Delete
    void delete(Song song);
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
3、继承虚基类RoomDatabase

@Database(entities = {Song.class}, version = 1) ,指明注解entitie和版本

import androidx.room.Database;
import androidx.room.RoomDatabase;

@Database(entities = {Song.class}, version = 1)
public abstract class MusicDatabase extends RoomDatabase {
    public abstract SongDao songDao();
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

最后使用:

需要注意的是数据库操作要在子线程中进行,可以使用线程池或者别的调用子线程方式。
import android.os.Bundle;
import android.util.Log;

import androidx.appcompat.app.AppCompatActivity;
import androidx.room.Room;

import com.deviser.room.db.MusicDatabase;
import com.deviser.room.db.Song;

import java.util.List;

public class MainActivity extends AppCompatActivity {

    MusicDatabase mDB;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mDB = Room.databaseBuilder(getApplicationContext(), MusicDatabase.class, "xx-db").build();

        findViewById(R.id.insert).setOnClickListener(v -> {
            new Thread(() -> {
                Song s1 = new Song("潇洒走一回", 1991);
                mDB.songDao().insert(s1);
            }).start();
        });
        findViewById(R.id.search).setOnClickListener(v -> {
            new Thread(() -> {
                List<Song> list = mDB.songDao().loadAll();
                for (Song s : list) {
                    Log.i("TAG", "当前项在库中的id:" + s.getId() + ",歌曲名:" + s.getName() + ",发行年代:" + s.getReleaseYear());
                }
            }).start();
        });
    }

}

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Li_阴宅/article/detail/743048
推荐阅读
相关标签
  

闽ICP备14008679号