Android Room: Insert relation entities using Room

前端 未结 6 1604
鱼传尺愫
鱼传尺愫 2020-11-27 10:41

I\'ve added one to many relationship in Room using Relation. I referred to this post to write the following code for relation in Room.

The post tells how to read th

6条回答
  •  醉酒成梦
    2020-11-27 11:18

    As Room does not manage the Relations of the entities, you have to set the userId on each pet yourself and save them. As long as there are not too many pets at once, I'd use an insertAll method to keep it short.

    @Dao
    public interface PetDao {
        @Insert
        void insertAll(List pets);
    }
    

    I don't think there's any better way at the moment.

    To make the handling easier, I'd use an abstraction in the layer above the DAOs:

    public void insertPetsForUser(User user, List pets){
    
        for(Pet pet : pets){
            pet.setUserId(user.getId());
        }
    
        petDao.insertAll(pets);
    }
    

提交回复
热议问题