LitePal

LitePal是一款Android ORM框架,简化了数据库操作。通过添加依赖、配置litepal.xml和 LitePalApplication,即可实现无SQL操作的建表、数据增删改查。文章介绍了如何定义数据模型,以及保存、修改、删除和查询数据的基本步骤。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、什么是LitePal

LitePal是一款开源的Android数据库框架,采用了对象关系映射(ORM)的模式,将平时开发时最常用的一些数据库功能进行了封装,使得开发者不用编写一行SQL语句就可以完成各种建表、増删改查的操作。

二、设置LitePal

1、包含库

编辑build.gradle文件并添加下面的依赖关系
dependencies {
compile ‘org.litepal.android:core:1.6.1’
}

2、配置litepal.xml

右击app/src/main目录,创建一个assets文件夹,然后在这个文件夹下创建一个litepal.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>
3、配置LitepalApplication
为了简化API,只需要在AndroidManifest中配置LitepalApplication
<manifest>
    <application
        android:name="org.litepal.LitePalApplication"
        ...
    >
        ...
    </application>
</manifest>

三、使用Litepal

1、创建表格
定义模型-Album和Song
public class Album extends DataSupport {
    @Column(unique = true, defaultValue = "unknown")
    private String name;

    private float price;

    private byte[] cover;

    private List<Song> songs = new ArrayList<Song>();

    public String getName() {
        return name;
    }

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

    public float getPrice() {
        return price;
    }

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

    public byte[] getCover() {
        return cover;
    }

    public void setCover(byte[] cover) {
        this.cover = cover;
    }

    public List<Song> getSongs() {
        return songs;
    }

    public void setSongs(List<Song> songs) {
        this.songs = songs;
    }
}
public class Song extends DataSupport {
    @Column(nullable = false)
    private String name;

    private int duration;

    @Column(ignore = true)
    private String uselessField;

    private Album album;

    public String getName() {
        return name;
    }

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

    public int getDuration() {
        return duration;
    }

    public void setDuration(int duration) {
        this.duration = duration;
    }

    public String getUselessField() {
        return uselessField;
    }

    public void setUselessField(String uselessField) {
        this.uselessField = uselessField;
    }

    public Album getAlbum() {
        return album;
    }

    public void setAlbum(Album album) {
        this.album = album;
    }
}

然后把这两个模型放到list中

 <list>
        <mapping class="com.example.litepal.Album" />
        <mapping class="com.example.litepal.Song" />
    </list>

这些表格会在你操作数据库时自动生成

举个例子:在Activity中写入以下代码
SQLiteDatabase db = LitePal.getDatabase();

注意点:

两个模型一定要继承DataSupport
2、保存数据
                String albumName = albumEt.getText().toString();
                float price = 109.9f;
                Album album = new Album();
                album.setName(albumName);
                album.setPrice(price);
                album.save();//保存至数据库
3、修改数据
                Album album1= DataSupport.find(Album.class,1);
                album1.setName("Fantasy");//设置修改后的名称
                album1.save();
4、删除数据
  //int row=DataSupport.delete(Album.class,2);
   int row=DataSupport.deleteAll(Album.class,"id>?","2");//第一个参数用于指定删除哪个表中的数据,后面的为约束条件
  Toast.makeText(this,"您删除了"+row+"行数据",Toast.LENGTH_SHORT).show();
5、查询数据
  List<Album> albumList = DataSupport.findAll(Album.class);//查询表中所有数据
                //List<Album> albumList=DataSupport.where("id<? and name like ?","6","a%").order("name").limit(5).find(Album.class);
                for (Album a:
                        albumList)//写个for循环
                    Log.e("MAIN ",a.getName()+"***");
6、完整代码如下:

布局文件中

<EditText
        android:id="@+id/main_album_et"
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:hint="专辑名" />

    <Button
        android:id="@+id/main_add_album_btn"
        android:layout_width="180dp"
        android:layout_height="60dp"
        android:layout_margin="20dp"
        android:text="添加专辑名" />
    <Button
        android:id="@+id/main_modify_album_btn"
        android:layout_width="180dp"
        android:layout_height="60dp"
        android:layout_margin="20dp"
        android:text="修改专辑名" />
    <Button
        android:id="@+id/main_delete_album_btn"
        android:layout_width="180dp"
        android:layout_height="60dp"
        android:layout_margin="20dp"
        android:text="删除专辑" />
    <Button
        android:id="@+id/main_query_album_btn"
        android:layout_width="180dp"
        android:layout_height="60dp"
        android:layout_margin="20dp"
        android:text="查询专辑" />

Activity中

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private EditText albumEt;
    private Button addAlbumBtn;
    private Button modifyAlbumBtn;
    private Button deleteAlbumBtn;
    private Button queryAlbumBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //SQLiteDatabase db = LitePal.getDatabase();
        bindId();
    }

    private void bindId() {
        albumEt = findViewById(R.id.main_album_et);
        addAlbumBtn = findViewById(R.id.main_add_album_btn);
        modifyAlbumBtn = findViewById(R.id.main_modify_album_btn);
        deleteAlbumBtn = findViewById(R.id.main_delete_album_btn);
        queryAlbumBtn=findViewById(R.id.main_query_album_btn);
        addAlbumBtn.setOnClickListener(this);
        modifyAlbumBtn.setOnClickListener(this);
        deleteAlbumBtn.setOnClickListener(this);
        queryAlbumBtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.main_add_album_btn:
                String albumName = albumEt.getText().toString();
                float price = 109.9f;
                Album album = new Album();
                album.setName(albumName);
                album.setPrice(price);
                album.save();//保存至数据库
                DebugDB.getAddressLog();
                break;
            case R.id.main_modify_album_btn:
                Album album1= DataSupport.find(Album.class,1);
                album1.setName("Fantasy");
                album1.save();
                break;
            case R.id.main_delete_album_btn:
                //int row=DataSupport.delete(Album.class,2);
                int row=DataSupport.deleteAll(Album.class,"id>?","2");
                Toast.makeText(this,"您删除了"+row+"行数据",Toast.LENGTH_SHORT).show();
                break;
            case R.id.main_query_album_btn:
                List<Album> albumList = DataSupport.findAll(Album.class);
                //List<Album> albumList=DataSupport.where("id<? and name like ?","6","a%").order("name").limit(5).find(Album.class);
                for (Album a:
                        albumList)
                    Log.e("MAIN ",a.getName()+"***");
                break;
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值