Road to Android Learning (16) Android Database Litepal

1. Introduction to LitePal

Litepal is an open source Android database framework created by Android master Guo Lin. It adopts the object-relational mapping (ORM) model. This is a database that we can understand very well. An entity class corresponds to a table in our database. This library also encapsulates many methods. Even if you know little about SQL statements, you can still set up a database and perform various operations of adding, deleting, modifying and searching. Litepal official link.

2. Litepal configuration

1. Add dependencies

First, go to the official address to find the latest dependencies, and add them under the dependencies of our project: My latest version is currently 3.2.3

dependencies {
    implementation 'org.litepal.guolindev:core:3.2.3'
}

2. Configure Litepal

We must first configure our database under our project AndroidManifest.xml so that our Litepal can work normally, add android:name="org.litepal.LitePalApplication":

<manifest>
    <application
       android:name="org.litepal.LitePalApplication"
        ...
    >
        ...
    </application>
</manifest>

If you already have your own Application configure here, for example:

<manifest>
    <application
        android:name="com.example.MyApplication"
        ...
    >
        ...
    </application>
</manifest>

Then you can add LitePal.initialize(this); to your Myapplication to initialize the configuration.

public class MyApplication extends Application {

    @Override
    public void onCreate() {
        super.onCreate();
        LitePal.initialize(this);
    }
    ...
}

3. Create litepal.xml file

Right-click the app/src/main directory->new Directory, create an assets directory, then new File a litepal.xml file in the directory, and then edit the content inside:

<?xml version="1.0" encoding="utf-8"?>
<litepal>
    <dbname value="NewsDemo" />
    <version value="1" />
    <list>
    </list>
   
</litepal>

The dbname tag is used to specify the name of the database. The version tag is to specify the database version. When updating the table, you need to increase the value. The list tag is used to specify our mapping model, that is, mapping the path of our entity class. Put the tag in
So far our litepal configuration work has been completed, let’s use it officially

3. Use of Litepal

1.Create database

First define our entity class. I will simplify it here and first define a News class and a content class Content:
Before we perform database operations on the entity class, we must We need to first let our database know which are our entity classes and can operate on them, so we need to let our entity classes inherit the LitepalSupport class first! ! !

public class News extends LitepalSupport{

	private int id;
	
	@Column(unique = true, defaultValue = "unknown")
	private String title;
	
	private String Content;
	
	//getter , setter 方法
	//...
}
public class Comment extends LitepalSupport{

	private int id;
	
	@Column(nullable = false)
	private String content;

	//getter , setter 方法
	//...
}

Here are two typical javaBean classes, which define the id, title, content of the news, the id and content of the comment class, and their getter and setter methods. There are also some annotations for limited classes. Do you feel the most intuitive experience of relationship mapping here?

After defining the entity class, be sure to add it to the list of mapping models and modify the litepal.xml file.

<?xml version="1.0" encoding="utf-8"?>
<litepal>
    <dbname value="NewsDemo" />
    <version value="1" />
    <list>
    <mapping ></mapping>
    <mapping ></mapping>
    </list>
   
</litepal>

In this way, we only need to perform one operation on the database to initialize the database. We can generally call the Litepal.getDatabase() method.
How to check whether it is successful?
We can use Android Studio's View ->ToolsWindows -> Device File Explorer
and then enter data/data/< package name> / databases Two files will be generated, one of which ends with db. This is our database file. If you want to see the contents, you need to check the creation of the database through the db shell. I will not expand on this. I think Friends who are interested in watching it, please check it out for yourself.

2.Upgrade database

For example, now our News class needs to establish a relationship mapping with Comment, which is a one-to-many relationship. That is, a News class can have multiple Comment classes corresponding to it, so we can modify the class:

public class News{

	private int id;
	
	@Column(unique = true, defaultValue = "unknown")
	private String title;
	
	private String Content;
	
	private List<Comment> commentList = new ArrayList<>();
	
	//getter , setter 方法
	//...
}
public class Comment{

	private int id;
	
	@Column(nullable = false)
	private String content;
	
	private News news;
	
	//getter , setter 方法
	//...
}

In this way, we added private List commentList = new ArrayList<>(); to the News class. Here we pay special attention to the fact that commentList must be instantiated by itself first, so that we can store comments later, and the corresponding Comment only corresponds to us. A News, so private News news is added to it;

After modifying the entity class, how do we notify the database to update it? It's very simple, we just need to add 1 to the version number in litepal.xml! value=1 -> value=2

<?xml version="1.0" encoding="utf-8"?>
<litepal>
    <dbname value="NewsDemo" />
    <version value="2" />
    <list>
    <mapping ></mapping>
    <mapping ></mapping>
    </list>
   
</litepal>

3. Litepal’s CRUD

①Add data

Comment comment1 = new Comment();
comment1.setContent("太不道德了吧!");
comment1.save();

Comment comment2 = new Comment();
comment2.setContent("这新闻真让人汗颜!");
comment2.save();

News new = new News();
new.setTitle("日本核污水");
new.setContent("日本决定把核污水排入海洋");
new.getCommentList().add(comment1);
new.getCommentList().add(comment2);
new.save();

Precautions

First of all, call the save() method to save our entity class object to the Litepal database. Then, we do not need to specify the ids in the News class and the Comment class. The framework will automatically generate and specify the two classes for us. After the mapping relationship, here refers to the one-to-many relationship. The news object in the class (Comment) does not need to be set by us. It will automatically be converted into a news_id field in the database, which indicates that it is Corresponding to the comments in that News, when calling new.getCommentList().add(comment1), the Litepal framework will automatically set up the mapping relationship between these two classes for us. When we want to query what comments there are in a specific News object, we can check it like this. According to the id of your object, we can match the news_id of all comments:

List<Comment> commentList = LitePal
					.where("news_,String.valueOf(news.getId()))
					.find(Comment.Class);

② Query data

//查询所有的new
List<News> newList  = LitePal.findAll(News.class);

//根据指定条件查询
//
List<News> newList1  = LitePal
		.where("title=? and content=?","日本核污水","日本决定把核污水排入海洋")
		.find(News.class);

③Update data

//第一种方式:
News news = new News();
news.setContent("排污水进海洋太可恶了!!");
news.upDateAll("title=?","日本核污水").find(News.class);

//第二种方式:
News news = LitePal.find(News.class,1); //1指id号
news.setContent("排污水进海洋太可恶了!!");
news.save();

//第三种方式
News news = new News();
news.setContent("排污水进海洋太可恶了!!");
news.update(id);

④Delete data

//第一种
LitePal.deleteAll(News.class,"title=?","日本核污水");

//第二种
LitePal.delete(News.class,id);

4. Use multiple databases:

The first method: create in code

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

Second type: Create with something like litepal.xml, here is otherDataBase.xml:

LitePalDB litePalDB = LitePalDB.fromDefault("otherDataBase");
LitePal.use(litePalDB);

Switch back to the default database at any time: LitePal.useDefault();
Delete the database: LitePal.deleteDatabase(“otherDataBase”);

4. Summary

LitePal relational database is very simple and clear to use. If you have any questions or corrections about the article, please leave a message in the comment area! If you think the article is helpful to you, giving it a like or collecting it is the greatest support for the author! grateful!

Guess you like

Origin blog.csdn.net/qq_32907491/article/details/133465687