Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Room: How to use @Transaction in DAO Interface

Regarding this question's answer: How to use setBalance method in my entity to set the actual balance value of a member?

The answer suggests to use a @Transaction method. I don't understand how to use this method. Also, my DAO is an interface, the answer's DAO is a abstract.

How do I implement the method suggested in the answers into my interface DAO and then in the repository?

enter image description here

enter image description here

like image 892
LordGash Avatar asked Jul 21 '18 12:07

LordGash


People also ask

What is transaction in Android Dao?

androidx.room.Transaction Marks a method in a Dao class as a transaction method. When used on a non-abstract method of an abstract Dao class, the derived implementation of the method will execute the super method in a database transaction. All the parameters and return types are preserved.

Is it possible to have @transaction methods in room interface?

Transaction methods in room are methods marked with @Transaction annotation. Since you can not have non-abstract methods in interfaces, you need to use an abstract class instead of interface for DAO. Thanks for contributing an answer to Stack Overflow! Please be sure to answer the question. Provide details and share your research! But avoid …

What is a DAO in room?

When you use the Room persistence library to store your app's data, you interact with the stored data by defining data access objects, or DAOs. Each DAO includes methods that offer abstract access to your app's database. At compile time, Room automatically generates implementations of the DAOs that you define.

What is a Data Access Object (DAO)?

In this article, we going to discuss Data Access Objects or DAOs in detail. In Room, Data Access Objects or DAOs are used to access your application’s persisted data. They are a better and modular way to access your database as compared to query builders or direct queries. A DAO can be either an interface or an abstract class.


1 Answers

Transaction methods in room are methods marked with @Transaction annotation.

Since you can not have non-abstract methods in interfaces, you need to use an abstract class instead of interface for DAO.

For example,

@android.arch.persistence.room.Dao
public abstract class AppDao {
    @Transaction
     public void insertAndDeleteInTransaction(Product newProduct, Product oldProduct) {
         // Anything inside this method runs in a single transaction.
         insert(newProduct);
         delete(oldProduct);
     }
}
like image 54
Bertram Gilfoyle Avatar answered Nov 14 '22 21:11

Bertram Gilfoyle