LitePal For Android(替代SQLite传统操作)

Github地址

LitePal配置

  1. 引用

    jar包引用

    Gradle引用(非GitHub项目最新版本)

    dependencies {
        compile 'org.litepal.android:core:1.6.0'
    }
    
  2. xml文件设置

    <?xml version="1.0" encoding="utf-8"?>
    <litepal>
        <!--
           Define the database name of your application. 
           By default each database name should be end with .db. 
           If you didn't name your database end with .db, 
           LitePal would plus the suffix automatically for you.
           For example:    
           <dbname value="demo" />
        -->
        <dbname value="demo" />
    
        <!--
           Define the version of your database. Each time you want 
           to upgrade your database, the version tag would helps.
           Modify the models you defined in the mapping tag, and just 
           make the version value plus one, the upgrade of database
           will be processed automatically without concern.
               For example:    
           <version value="1" />
        -->
        <version value="1" />
    
        <!--
           Define your models in the list with mapping tag, LitePal will
           create tables for each mapping class. The supported fields
           defined in models will be mapped into columns.
           For example:    
           <list>
               <mapping class="com.test.model.Reader" />
               <mapping class="com.test.model.Magazine" />
           </list>
        -->
        <list>
        </list>
        
        <!--
            Define where the .db file should be. "internal" means the .db file
            will be stored in the database folder of internal storage which no
            one can access. "external" means the .db file will be stored in the
            path to the directory on the primary external storage device where
            the application can place persistent files it owns which everyone
            can access. "internal" will act as default.
            For example:
            <storage value="external" />
        -->
        
    </litepal>
    <!-- 
       dbname:数据库名字
       version:数据库版本号
       list:映射模型
       storage:配置数据库存储位置,只有internal(内部)和external(外部)两种配置
    -->
    
  1. 配置litepalApplication

    • 直接在AndroidManifest文件中设置

      <manifest>
          <application
              android:name="org.litepal.LitePalApplication"
              ...
          >
              ...
          </application>
      </manifest>
      
    • 自定义MyApplication

      • 首先在AndroidManifest中指定自定义class
      <manifest>
          <application
              android:name="com.example.MyOwnApplication"
              ...
          >
              ...
          </application>
      </manifest>
      
      • 在代码中自定义MyApplication
      public class MyOwnApplication extends AnotherApplication {
      
          @Override
          public void onCreate() {
              super.onCreate();
              LitePal.initialize(this);
          }
          ...
      }
      

使用

  1. 建表

    public class Album extends DataSupport {
       //id主键可以不写,默认生成
        @Column(unique = true, defaultValue = "unknown")//不允许重复,默认值位unknown
        private String name;
       
        private float price;
       
        private byte[] cover;
       
        private List<Song> songs = new ArrayList<Song>();
    
        // generated getters and setters.
        ...
    }
    public class Song extends DataSupport {
       
        @Column(nullable = false)//允许为null
        private String name;
       
        private int duration;
       
        @Column(ignore = true)//允许忽略
        private String uselessField;
       
        private Album album;
    
        // generated getters and setters.
        ...
    }
    

    修改litepal.xml文件中的映射

    <list>
        <mapping class="org.litepal.litepalsample.model.Album" />
        <mapping class="org.litepal.litepalsample.model.Song" />
    </list>
    
  2. 更改表属性

    在继承DataSupport的类中修改相关属性后,在xml文件中将数据库版本+1

  3. 数据保存

    Album album = new Album();
    album.setName("album");
    album.setPrice(10.99f);
    album.setCover(getCoverImageBytes());
    album.save();
    Song song1 = new Song();
    song1.setName("song1");
    song1.setDuration(320);
    song1.setAlbum(album);
    song1.save();
    Song song2 = new Song();
    song2.setName("song2");
    song2.setDuration(356);
    song2.setAlbum(album);
    song2.save();
    
  4. 数据修改

    Album albumToUpdate = DataSupport.find(Album.class, 1);
    albumToUpdate.setPrice(20.99f); // raise the price
    albumToUpdate.save();
    

    或者

    Album albumToUpdate = new Album();
    albumToUpdate.setPrice(20.99f); // raise the price
    albumToUpdate.update(id);
    

    或者

    Album albumToUpdate = new Album();
    albumToUpdate.setPrice(20.99f); // raise the price
    albumToUpdate.updateAll("name = ?", "album");
    
  5. 删除数据

    DataSupport.delete(Song.class, id);
    

    或者

    DataSupport.deleteAll(Song.class, "duration > ?" , "350");
    
  6. 查找数据

    Song song = DataSupport.find(Song.class, id);
    

    或者

    List<Song> allSongs = DataSupport.findAll(Song.class);
    

    或者

    List<Song> songs = DataSupport.where("name like ?", "song%").order("duration").find(Song.class);
    
  7. 异步查询

    DataSupport.findAllAsync(Song.class).listen(new FindMultiCallback() {
        @Override
        public <T> void onFinish(List<T> t) {
            List<Song> allSongs = (List<Song>) t;
        }
    });
    
  8. 支持代码生成数据库

    LitePalDB litePalDB = new LitePalDB("demo2", 1);
    litePalDB.addClassName(Singer.class.getName());
    litePalDB.addClassName(Album.class.getName());
    litePalDB.addClassName(Song.class.getName());
    LitePal.use(litePalDB);
    

后记

以上总结并不完全,还有很多其他操作没有总结,作者个人CSDN博客更全——作者CSDN

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,886评论 18 139
  • pyspark.sql模块 模块上下文 Spark SQL和DataFrames的重要类: pyspark.sql...
    mpro阅读 9,504评论 0 13
  • 若干年前,你是著名不良少女,其实你真正做过些什么坏事呢? 你伤害的,只有自己。 那些珍藏一生的至交,与那些分道扬镳...
    青诉离殇阅读 162评论 0 1
  • 很多想要申请英国的同学都对各大院校的学费情况一无所知,询问能否推出英国院校学费排名。本期简简就实现大家这个愿望,对...
    简简mumu阅读 949评论 0 1
  • 思乡乡不见, 终日夜难眠, 夜半几多愁, 梦中故乡显, 抬头望明月, 千里一线牵, 问君无人语, 痛彻肝肠断, 问...
    海浪低吟浅唱阅读 234评论 0 0