Android LitePal 소개 및 사용 설명

26223 단어 androidlitepal
원문:https://github.com/LitePalFramework/LitePal/blob/master/README.md
LitePal for Android
        LitePal 은 개발 자 들 이 SQLite 데이터 베 이 스 를 쉽게 사용 할 수 있 도록 안 드 로 이 드 오픈 소스 라 이브 러 리 입 니 다.SQL 문 구 를 한 마디 쓰 지 않 아 도 대부분의 데이터 베 이 스 를 완성 할 수 있 습 니 다.생 성 표,업데이트 표,제약 작업,취 합 기능 등 을 포함 합 니 다.LitePal 의 설치 도 상당히 간단 해서 5 분 안에 그것 을 당신 의 공사 에 집적 할 수 있 습 니 다.
기능.
대상 관계 맵(ORM)모델 을 사용 합 니 다
거의 0 설정(하나의 프로필 만 있 고 이 프로필 의 속성 은 매우 적다)
모든 표를 자동 으로 유지 합 니 다(예 를 들 어 표를 만 들 거나 변경 하거나 삭제 합 니 다)
봉 인 된 API 를 제공 합 니 다.SQL 문 구 를 쓸 필요 가 없습니다
훌륭 한 클 러 스 터 조회 기능 입 니 다
SQL 을 선택 할 수 있 습 니 다.LitePal 은 원본 보다 더 쉽게 사용 할 수 있 는 API 인 터 페 이 스 를 제공 합 니 다
최신 다운로드
litepal-1.3.0.jar (라 이브 러 리 에*.class 파일 포함)litepal-1.3.0-src.jar (라 이브 러 리 는*.class 와*.자바 파일 포함)빠 른 설치
1.라 이브 러 리 가 져 오기
Eclipse 사용 하기
최신 jar 를 다운로드 하고 역사 다른 버 전 을 다운로드 할 수 있 습 니 다
jar 를 프로젝트 의 라 이브 러 리 폴 더 에 넣 습 니 다
Android Studio 사용
build.gradle 파일 을 편집 하고 다음 의존 설명 을 추가 합 니 다.
dependencies {
    compile 'org.litepal.android:core:1.3.0'
}

2.litepal.xml 설정
프로젝트 의 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 automaticly for you.
        For example:    
        <dbname value="demo" ></dbname>
    -->
    <dbname value="demo" ></dbname>

    <!--
        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 automaticly without concern.
            For example:    
        <version value="1" ></version>
    -->
    <version value="1" ></version>

    <!--
        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>
            <mapping class="com.test.model.Magazine"></mapping>
        </list>
    -->
    <list>
    </list>
</litepal>

이것 은 유일한 프로필 입 니 다.속성 은 간단 합 니 다.
dbname 은 프로젝트 의 데이터베이스 파일 이름 을 설정 하 는 데 사 용 됩 니 다
version 은 데이터베이스 의 버 전 정 보 를 설정 하 는 데 사 용 됩 니 다.데이터 베 이 스 를 업그레이드 할 때마다 이 버 전 번 호 는 1 을 추가 합 니 다
list 는 맵 클래스 를 설정 하 는 데 사 용 됩 니 다
3.LitePalApplication 설정
데이터 베 이 스 를 조작 할 때 Context 인 자 를 사용 해 야 합 니 다.매번 이 인 자 를 전달 하고 싶 지 않 습 니 다.그러면 AndroidManifest.xml 에 LitePalApplication 을 설정 하면 됩 니 다.다음 과 같 습 니 다.
<manifest>
    <application
        android:name="org.litepal.LitePalApplication"
        ...
    >
    ...
    </application>
</manifest>

물론,당신 은 자신의 응용 프로그램 이 있 고 이미 설정 되 어 있 을 수 있 습 니 다.다음 과 같 습 니 다.
<manifest>
    <application
        android:name="com.example.MyOwnApplication"
        ...
    >
    ...
    </application>
</manifest>

괜 찮 습 니 다.MyOwnApplication 을 원래 의 계승 Application 류 에서 LitePalApplication 류 로 바 꾸 면 됩 니 다.다음 과 같 습 니 다.
public class MyOwnApplication extends LitePalApplication {
    ...
}

만약 당신 의 MyOwnApplication 이 다른 Application 류,예 를 들 어 AnotherApplication 류 를 계승 해 야 한다 면 LitePalapplication.initialize(context)를 직접 호출 하여 LiteApplication 류 를 계승 하지 않 아 도 됩 니 다.다음 과 같 습 니 다.
public class MyOwnApplication extends AnotherApplication {

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

LitePalapplication.initialize(context)의 호출 원칙 은 가능 한 한 빨리 하 는 것 입 니 다.예 를 들 어 적당 한 호출 위 치 는 Application 의 onCreate()에서 호출 됩 니 다.호출 할 때 전달 하 는 매개 변 수 는 Application 의 context 입 니 다.activity 나 service 의 인 스 턴 스 를 매개 변수 로 사용 하지 마 십시오.그렇지 않 으 면 메모리 누 출 이 발생 할 수 있 습 니 다.
LitePal 체험 여행 시작
1.표 만 들 기
먼저 각종 model 을 정의 합 니 다.예 를 들 어 두 개의 model:Album 과 Song 이 있 습 니 다.정 의 는 다음 과 같 습 니 다.
public class Album extends DataSupport {

    @Column(unique = true, defaultValue = "unknown")
    private String name;

    private float price;

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

    // generated getters and setters.
    ...
}
public class Song extends DataSupport {

    @Column(nullable = false)
    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>
    <mapping class="org.litepal.litepalsample.model.Song"></mapping>
</list>

데이터 베 이 스 를 조작 하면 데이터베이스 표 가 자동 으로 생 성 된다.예 를 들 어 아래 코드 를 사용 하여 SQLiteDatabase 를 가 져 올 때,
SQLiteDatabase db = Connector.getDatabase();

album 과 song 두 장의 데이터베이스 표를 자동 으로 생 성 합 니 다.다음 과 같 습 니 다.
CREATE TABLE album (
    id integer primary key autoincrement,
    name text unique default 'unknown',
    price real 
);

CREATE TABLE song (
    id integer primary key autoincrement,
    name text not null,
    duration integer,
    album_id integer
);

2.승급 표
LitePal 에서 업그레이드 표를 실현 하 는 것 은 매우 쉽다.
public class Album extends DataSupport {

    @Column(unique = true, defaultValue = "unknown")
    private String name;

    @Column(ignore = true)
    private float price;

    private Date releaseDate;

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

    // generated getters and setters.
    ...
}

위 코드 에 releaseDate 를 추가 하고 price 는 ignore 로 표 시 됩 니 다.
<!--
    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 automaticly without concern.
    For example:    
    <version value="1" ></version>
-->
<version value="2" ></version>

litepal.xml 에서 버 전 번 호 를 업그레이드 하면 다음 에 데이터 베 이 스 를 조작 할 때 표 는 자동 으로 업 그 레이 드 됩 니 다.ablum 표 에 releasedate 열 을 추가 하고 price 열 을 삭 제 했 으 며 다른 열의 데 이 터 는 그대로 있 습 니 다.
다음 업그레이드 상황 은 LitePal 에서 처리 할 수 없 으 며 업그레이드 표 의 모든 데이터 가 삭 제 됩 니 다.
레이 블 을 추가 하 였 습 니 다.  unique = true ;
어떤 속성의 레이 블 을 변경 합 니 다.  unique = true;
어떤 속성의 레이 블 을 변경 합 니 다.  nullable = false;
이상 의 상황 은 데이터 손실 을 초래 할 수 있 으 니 각별히 주의해 야 한다.
3.데이터 저장
DataSupport 클래스 를 계승 하 는 모델 마다 save()방법 이 있 습 니 다.
Album album = new Album();
album.setName("album");
album.setPrice(10.99f);
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();

이상 코드 는 album,song 1,song 2 를 데이터베이스 에 삽입 하고 연결 을 권장 합 니 다.
4.데이터 업데이트
DataSupport 클래스 를 계승 하 는 모든 model 에는 update()와 updateAll()방법 이 있 습 니 다.update()는 지정 한 id 의 단일 기록 을 업데이트 할 수 있 습 니 다.다음 과 같 습 니 다.
Album albumToUpdate = new Album();
albumToUpdate.setPrice(20.99f); // raise the price
albumToUpdate.update(id);

updateAll()은 일정한 조건 을 만족 시 키 는 여러 개의 기록 을 동시에 업데이트 할 수 있 습 니 다.다음 과 같 습 니 다.
Album albumToUpdate = new Album();
albumToUpdate.setPrice(20.99f); // raise the price
albumToUpdate.updateAll("name = ?", "album");

5.데이터 삭제
DataSupport 의 정적 방법 delete()를 호출 하면 지정 한 id 의 단일 기록 을 삭제 할 수 있 습 니 다.
DataSupport.delete(Song.class, id);

정적 방법 deleteAll()을 호출 하여 여러 개의 기록 을 삭제 할 수 있 습 니 다.
DataSupport.deleteAll(Song.class, "duration > ?" , "350");

6.조회 데이터
song 표 에서 지정 한 id 의 단일 기록 조회:
Song song = DataSupport.find(Song.class, id);

song 표 의 모든 기록 조회:
List<Song> allSongs = DataSupport.findAll(Song.class);

복잡 한 클 러 스 터 조회 구축:
List<Song> songs = DataSupport.where("name like ?", "song%").order("duration").find(Song.class);

좋은 웹페이지 즐겨찾기