Jetpack Room

本文详细介绍了如何使用AndroidRoom进行数据库操作,包括创建实体类、定义Dao接口、数据库抽象类、迁移数据库、以及在Activity中实现增删改查功能。
摘要由CSDN通过智能技术生成

增删改查实战代码

1.先导入依赖

 

   val roomVersion ="2.6.1"
    implementation("androidx.room:room-runtime:$roomVersion")
    annotationProcessor("androidx.room:room-compiler:$roomVersion")

2.创建实体类

package com.tiger.chapter06.entity;

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

@Entity//标注实体类 自动生成一些代码
public class BookInfo {
    @PrimaryKey(autoGenerate = true) //
    private Integer id;


    private String name; // 书籍名称
    private String author; // 作者
    private String press; // 出版社
    private Double price; // 价格

    public BookInfo() {
    }

    public BookInfo(Integer id, String name, String author, String press, Double price) {
        this.id = id;
        this.name = name;
        this.author = author;
        this.press = press;
        this.price = price;
    }

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

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

    public String getAuthor() {
        return author;
    }

    public void setAuthor(String author) {
        this.author = author;
    }

    public String getPress() {
        return press;
    }

    public void setPress(String press) {
        this.press = press;
    }

    public Double getPrice() {
        return price;
    }

    public void setPrice(Double price) {
        this.price = price;
    }

    @Override
    public String toString() {
        return "BookInfo{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", author='" + author + '\'' +
                ", press='" + press + '\'' +
                ", price=" + price +
                '}';
    }
}

3.创建Dao层接口

package com.tiger.chapter06.dao;

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

import com.tiger.chapter06.entity.BookInfo;

import java.util.List;

@Dao
public interface BookInfoDao {

    @Insert
    void  insert(BookInfo...book);


    @Query("delete from BookInfo")
    void  deleteAll();
    @Delete
    void  delete(BookInfo...book);


    @Update
    int update(BookInfo...book);

    @Query("select * from BookInfo")
    List<BookInfo> queryAll();

    @Query("select * from BookInfo where name = :name order by id desc limit 1")
    BookInfo queryByName(String name);

}

4.创建抽象数据库类

package com.tiger.chapter06.database;

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

import com.tiger.chapter06.dao.BookInfoDao;
import com.tiger.chapter06.entity.BookInfo;

//entities 表示该数据库有哪些表,version表示数据库的版本号
//exportSchema 表示是否导出数据库信息的json串,建议设为false,若设为true 还需指定json文件的保存路径
@Database(entities = {BookInfo.class},version = 1,exportSchema = true)
public abstract class BookDataBase  extends RoomDatabase {

    //获取该数据库中某张表的持久化对象
    public abstract BookInfoDao bookInfoDao();

}

5.buile.gradle.kts 开启 exportSchema存储位置

  javaCompileOptions {
            annotationProcessorOptions {
                argument("room.schemaLocation","$projectDir/schemas".toString())//指定数据库导出的位置
            }
        }

6. 在Application里声明 单例实例

package com.tiger.chapter06;

import android.app.Application;
import android.content.res.Configuration;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.room.Room;

import com.tiger.chapter06.dao.BookInfoDao;
import com.tiger.chapter06.database.BookDataBase;

import java.util.HashMap;

public class MyApplication extends Application {
    private static MyApplication mApp;

    public static MyApplication getInstance(){
        return mApp;
    }

    public HashMap<String,String> infoMap = new HashMap<>();

    //声明一个书籍数据库对象
    private BookDataBase bookDataBase;

    //在App启动时调用
    @Override
    public void onCreate() {
        super.onCreate();
        mApp=this;
        Log.d("ning"," MyApplication onCreate");
        // 构建书籍数据库的实例
        bookDataBase = Room.databaseBuilder(this,BookDataBase.class,"book")
                //允许迁移数据库(发生数据库变更时,Room默认删除原数据库再创建新数据库。如此一来原来的记录会丢失,故而要改为迁移方式以便保存原有记录)
                .addMigrations()
                //允许在主线程中操作数据库(Room默认不能在主线程中操作数据库)
                .allowMainThreadQueries()
                .build();


    }

    //在App终止时调用
    @Override
    public void onTerminate() {
        super.onTerminate();
        Log.d("ning","onTerminate");



    }

    //在配置改变时调用,例如从竖屏变为横屏
    @Override
    public void onConfigurationChanged(@NonNull Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        Log.d("ning","onConfigurationChanged");
    }


    //获取书籍数据库的实例
    public BookDataBase getBookDB(){
        return bookDataBase;
    }



}

7.在Activity执行onCreate方法 将 Application的实例对象 放入此对象中, 实现增删改查

package com.tiger.chapter06;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

import com.tiger.chapter06.dao.BookInfoDao;
import com.tiger.chapter06.entity.BookInfo;
import com.tiger.chapter06.utils.ToastUtlis;

import java.util.List;

public class RoomWriteActivity extends AppCompatActivity implements View.OnClickListener {
    private EditText et_name;
    private EditText et_author;
    private EditText et_press;
    private EditText et_price;
    private BookInfoDao bookInfoDao;

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

        et_name = findViewById(R.id.et_name);
        et_author = findViewById(R.id.et_author);
        et_press = findViewById(R.id.et_press);
        et_price = findViewById(R.id.et_price);

        findViewById(R.id.btn_save).setOnClickListener(this);
        findViewById(R.id.btn_delete).setOnClickListener(this);
        findViewById(R.id.btn_update).setOnClickListener(this);
        findViewById(R.id.btn_query).setOnClickListener(this);

        //从App实例中获取唯一的书籍持久化对象
        bookInfoDao = MyApplication.getInstance().getBookDB().bookInfoDao();

    }

    @Override
    public void onClick(View v) {
        String name = et_name.getText().toString();
        String author = et_author.getText().toString();
        String press = et_press.getText().toString();
        String price = et_price.getText().toString();

        if (v.getId() == R.id.btn_save){
            BookInfo bookInfo = new BookInfo(null, name, author, press, Double.valueOf(price));
            bookInfoDao.insert(bookInfo);
            ToastUtlis.show(this,"保存成功");
        }else if (v.getId() == R.id.btn_query){
            List<BookInfo> list = bookInfoDao.queryAll();
            list.forEach(b-> Log.d("ning",b.toString()));
            ToastUtlis.show(this,"查询成功");
        }else if (v.getId()==R.id.btn_delete){
            BookInfo bookInfo = new BookInfo();
            bookInfo.setId(1);
            bookInfoDao.delete(bookInfo);
            ToastUtlis.show(this,"删除成功");
        }else {
            BookInfo bookInfo = bookInfoDao.queryByName(name);
            bookInfo.setAuthor(author);
            bookInfo.setPress(press);
            bookInfo.setPrice(Double.valueOf(price));
            bookInfoDao.update(bookInfo);
            ToastUtlis.show(this,"修改成功");

        }



    }
}

8.页面xml layout

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="5dp">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/tv_name"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:gravity="center"
            android:text=" 书名:"
            android:textColor="@color/black"
            android:textSize="17sp" />

        <EditText
            android:id="@+id/et_name"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_marginTop="3dp"
            android:layout_marginBottom="3dp"
            android:layout_weight="1"
            android:background="@drawable/edit_select"
            android:hint="请输入书籍名称"
            android:inputType="text"
            android:textColor="@color/black"
            android:textSize="17sp" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/tv_author"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:gravity="center"
            android:text=" 作者:"
            android:textColor="@color/black"
            android:textSize="17sp" />

        <EditText
            android:id="@+id/et_author"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_marginTop="3dp"
            android:layout_marginBottom="3dp"
            android:layout_weight="1"
            android:background="@drawable/edit_select"
            android:hint="请输入作者姓名"
            android:textColor="@color/black"
            android:textSize="17sp" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/tv_press"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:gravity="center"
            android:text="出版社:"
            android:textColor="@color/black"
            android:textSize="17sp" />

        <EditText
            android:id="@+id/et_press"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_marginTop="3dp"
            android:layout_marginBottom="3dp"
            android:layout_weight="1"
            android:background="@drawable/edit_select"
            android:hint="请输入出版社名称"
            android:textColor="@color/black"
            android:textSize="17sp" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:orientation="horizontal">

        <TextView
            android:id="@+id/tv_price"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:gravity="center"
            android:text=" 价格:"
            android:textColor="@color/black"
            android:textSize="17sp" />

        <EditText
            android:id="@+id/et_price"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_marginTop="3dp"
            android:layout_marginBottom="3dp"
            android:layout_weight="1"
            android:background="@drawable/edit_select"
            android:hint="请输入书籍价格"
            android:inputType="numberDecimal"
            android:textColor="@color/black"
            android:textSize="17sp" />
    </LinearLayout>

    <Button
        android:id="@+id/btn_save"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="添加"
        android:textColor="@color/black"
        android:textSize="17sp" />

    <Button
        android:id="@+id/btn_delete"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="删除"
        android:textColor="@color/black"
        android:textSize="17sp" />

    <Button
        android:id="@+id/btn_update"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="修改"
        android:textColor="@color/black"
        android:textSize="17sp" />

    <Button
        android:id="@+id/btn_query"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="查询"
        android:textColor="@color/black"
        android:textSize="17sp" />

</LinearLayout>

  • 6
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值