├── .gitignore ├── .idea ├── compiler.xml ├── copyright │ └── profiles_settings.xml ├── gradle.xml ├── misc.xml ├── modules.xml └── runConfigurations.xml ├── README.md ├── app ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── heima │ │ └── ormlitedemo │ │ └── ExampleInstrumentedTest.java │ ├── main │ ├── AndroidManifest.xml │ ├── java │ │ └── com │ │ │ └── heima │ │ │ └── ormlitedemo │ │ │ ├── MainActivity.java │ │ │ ├── TestOpenHelper.java │ │ │ └── User.java │ └── res │ │ ├── layout │ │ └── activity_main.xml │ │ ├── mipmap-hdpi │ │ └── ic_launcher.png │ │ ├── mipmap-mdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xhdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xxhdpi │ │ └── ic_launcher.png │ │ ├── mipmap-xxxhdpi │ │ └── ic_launcher.png │ │ ├── values-w820dp │ │ └── dimens.xml │ │ └── values │ │ ├── colors.xml │ │ ├── dimens.xml │ │ ├── strings.xml │ │ └── styles.xml │ └── test │ └── java │ └── com │ └── heima │ └── ormlitedemo │ └── ExampleUnitTest.java ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | *.iml 2 | .gradle 3 | /local.properties 4 | /.idea/workspace.xml 5 | /.idea/libraries 6 | .DS_Store 7 | /build 8 | /captures 9 | .externalNativeBuild 10 | -------------------------------------------------------------------------------- /.idea/compiler.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /.idea/copyright/profiles_settings.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | -------------------------------------------------------------------------------- /.idea/gradle.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 18 | 19 | -------------------------------------------------------------------------------- /.idea/misc.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 19 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 46 | -------------------------------------------------------------------------------- /.idea/modules.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /.idea/runConfigurations.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 11 | 12 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | OrmLiteDemo 2 | 3 | * Orm是对象与数据的映射,简单说就是让javabean和数据库表建立绑定关系。 4 | OrmLite是对android原生SQLite的封装,OrmLiteDemo是Orm快速实现的示例工程。 5 | 6 | 7 | * [配套视频](https://www.boxuegu.com/web/html/video.html?courseId=172§ionId=8a9bdf305a3a4c00015a500ad0490141&chapterId=8a9bdf305a3a4c00015a500afc6c0142&vId=8a9bdf305a3a4c00015a500b24cf0143&videoId=471D4682107323DF9C33DC5901307461) 8 | 9 | * 爱生活,爱学习,更爱做代码的搬运工,分类查找更方便请下载黑马助手app 10 | 11 | 12 | ![黑马助手.png](http://upload-images.jianshu.io/upload_images/4037105-f777f1214328dcc4.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 13 | 14 | 15 | * 开始在build.gradle添加依赖 16 | 17 | compile 'com.j256.ormlite:ormlite-android:5.0' 18 | 19 | * 需要的权限 20 | 21 | 22 | 23 | 24 | ### 第一步:建立Orm关系。以User.class为例,对应数据库的t_user表。 25 | @DatabaseField(id = true) 26 | private int id; 27 | @DatabaseField(columnName = "name") 28 | private String name; 29 | @DatabaseField(columnName = "balance") 30 | private float balance; 31 | @DatabaseField(columnName = "discount") 32 | private int discount; 33 | @DatabaseField(columnName = "integral") 34 | private int integral; 35 | @DatabaseField(columnName = "phone") 36 | private String phone; 37 | > 注意事项: 38 | 39 | 1.必须要添加无参构造方法; 40 | 2.id=true时id可以由我们自己赋值,如果使用generateId=true,则id由数据库自己维护,自动增长效果,auto increment。 41 | 42 | ### 第二步:创建OpenHelper继承OrmLiteOpenHelper,OrmLiteOpenHelper是SQLiteOpenHelper的子类。 43 | 44 | * 在初始化数据库的oncreate中创建数据库。由于做了Orm,则指定User.class就可以创建t_user表。 45 | TableUtils.createTable(connectionSource, User.class); 46 | 47 | ### 第三步:由于OrmLite封装了SQLite,所以不用再拼装SQL语句字段了,直接获取DAO层插入User对象即可。 48 | 49 | 1.先获取数据库连接: 50 | AndroidDatabaseConnection connection = new AndroidDatabaseConnection(takeoutOpenHelper.getWritableDatabase(), true); 51 | 2.开启事务: 52 | SavePoint savepoint = connection.setSavePoint("start"); //事务的保存点 53 | connection.setAutoCommit(false); //事务处理需要手动提交 54 | 3.获取DAO层: 55 | Dao userDao = takeoutOpenHelper.getDao(User.class); 56 | 4.执行增删改插。插入前要判断是否已经有该用户,做防重复处理,所以有两个步骤。 57 | User oldUser = userDao.queryForId(001); 58 | if(oldUser!=null){ 59 | userDao.update(user); 60 | // TecentTjSdk.submitUserInfo(false); //老用户登录 61 | Log.e("login","老用户登录"); 62 | }else{ 63 | userDao.create(user); 64 | // TecentTjSdk.submitUserInfo(true); //新用户登录 65 | Log.e("login","新用户登录"); 66 | } 67 | 5.提交事务。connection.commit(savepoint); 68 | 6.如果出现异常,回滚事务即可。connection.rollback(savepoint); 69 | 70 | * 最后说明:可以使用userDao.createIfNotExists(user);代替上面两个步骤,这样就可以不用开启事务了,因为这个API本身封装了事务, 71 | 而手动事务可以更灵活,比如步骤内部增加新的逻辑(代码统计,其他业务逻辑等等,如上方注释)。 72 | 73 | * 详细的使用方法在DEMO里面都演示啦,如果你觉得这个库还不错,请赏我一颗star吧~~~ 74 | 75 | * 欢迎关注微信公众号 76 | 77 | ![](http://upload-images.jianshu.io/upload_images/4037105-8f737b5104dd0b5d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240) 78 | -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build 2 | -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | apply plugin: 'com.android.application' 2 | 3 | android { 4 | compileSdkVersion 25 5 | buildToolsVersion "25.0.2" 6 | defaultConfig { 7 | applicationId "com.heima.ormlitedemo" 8 | minSdkVersion 15 9 | targetSdkVersion 25 10 | versionCode 1 11 | versionName "1.0" 12 | testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" 13 | } 14 | buildTypes { 15 | release { 16 | minifyEnabled false 17 | proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' 18 | } 19 | } 20 | } 21 | 22 | dependencies { 23 | compile fileTree(include: ['*.jar'], dir: 'libs') 24 | androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', { 25 | exclude group: 'com.android.support', module: 'support-annotations' 26 | }) 27 | compile 'com.android.support:appcompat-v7:25.1.0' 28 | testCompile 'junit:junit:4.12' 29 | compile 'com.j256.ormlite:ormlite-android:5.0' 30 | compile 'com.google.code.gson:gson:2.8.0' 31 | } 32 | -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # By default, the flags in this file are appended to flags specified 3 | # in C:\Android\sdk/tools/proguard/proguard-android.txt 4 | # You can edit the include path and order by changing the proguardFiles 5 | # directive in build.gradle. 6 | # 7 | # For more details, see 8 | # http://developer.android.com/guide/developing/tools/proguard.html 9 | 10 | # Add any project specific keep options here: 11 | 12 | # If your project uses WebView with JS, uncomment the following 13 | # and specify the fully qualified class name to the JavaScript interface 14 | # class: 15 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 16 | # public *; 17 | #} 18 | -------------------------------------------------------------------------------- /app/src/androidTest/java/com/heima/ormlitedemo/ExampleInstrumentedTest.java: -------------------------------------------------------------------------------- 1 | package com.heima.ormlitedemo; 2 | 3 | import android.content.Context; 4 | import android.support.test.InstrumentationRegistry; 5 | import android.support.test.runner.AndroidJUnit4; 6 | 7 | import org.junit.Test; 8 | import org.junit.runner.RunWith; 9 | 10 | import static org.junit.Assert.*; 11 | 12 | /** 13 | * Instrumentation test, which will execute on an Android device. 14 | * 15 | * @see Testing documentation 16 | */ 17 | @RunWith(AndroidJUnit4.class) 18 | public class ExampleInstrumentedTest { 19 | @Test 20 | public void useAppContext() throws Exception { 21 | // Context of the app under test. 22 | Context appContext = InstrumentationRegistry.getTargetContext(); 23 | 24 | assertEquals("com.heima.ormlitedemo", appContext.getPackageName()); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 8 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /app/src/main/java/com/heima/ormlitedemo/MainActivity.java: -------------------------------------------------------------------------------- 1 | package com.heima.ormlitedemo; 2 | 3 | import android.os.Bundle; 4 | import android.support.v7.app.AppCompatActivity; 5 | import android.util.Log; 6 | import android.view.View; 7 | import android.widget.Toast; 8 | 9 | import com.j256.ormlite.android.AndroidDatabaseConnection; 10 | import com.j256.ormlite.dao.Dao; 11 | 12 | import java.sql.SQLException; 13 | import java.sql.Savepoint; 14 | 15 | public class MainActivity extends AppCompatActivity { 16 | 17 | @Override 18 | protected void onCreate(Bundle savedInstanceState) { 19 | super.onCreate(savedInstanceState); 20 | setContentView(R.layout.activity_main); 21 | } 22 | 23 | public void testAddUser(View view) { 24 | boolean isLoginOk = false; 25 | // User(int id, String name, float balance, int discount, int integral, String phone) 26 | User user = new User(001, "zhaoliying", 0.01f, 900, 5, "13812345678"); 27 | //2.保存到sdcard或者rom中,使用sp/文件、sqlite 28 | //OrmLite,Orm是指javabean的对象和表的每一行对应,如User的name和表中的username一个属性 29 | TestOpenHelper takeoutOpenHelper = new TestOpenHelper(this); 30 | //事务属于一个数据库连接的会话中内部处理 31 | AndroidDatabaseConnection connection = new AndroidDatabaseConnection(takeoutOpenHelper.getWritableDatabase(), true); 32 | Savepoint savepoint = null; 33 | try { 34 | savepoint = connection.setSavePoint("start"); //事务的保存点 35 | connection.setAutoCommit(false); //事务处理需要手动提交 36 | 37 | Dao userDao = takeoutOpenHelper.getDao(User.class); 38 | // userDao.createIfNotExists(user); //如果之前已经有该用户,不再创建,更新用户信息 39 | //TODO:产品说当日登录用户有多少是新用户,多少是老用户 40 | User oldUser = userDao.queryForId(001); 41 | if(oldUser!=null){ 42 | userDao.update(user); 43 | // TecentTjSdk.submitUserInfo(false); //老用户登录 44 | Log.e("login","老用户登录"); 45 | }else{ 46 | userDao.create(user); 47 | // TecentTjSdk.submitUserInfo(false); //新用户登录 48 | Log.e("login","新用户登录"); 49 | } 50 | connection.commit(savepoint); 51 | isLoginOk = true; 52 | } catch (SQLException e) { 53 | e.printStackTrace(); 54 | 55 | try { 56 | connection.rollback(savepoint); 57 | Log.e("login","保存用户信息失败"); 58 | isLoginOk = false; 59 | } catch (SQLException e1) { 60 | e1.printStackTrace(); 61 | } 62 | } 63 | 64 | if(isLoginOk){ 65 | onLogin(true); 66 | }else{ 67 | onLogin(false); 68 | } 69 | } 70 | 71 | public void onLogin(boolean isOk) { 72 | if(isOk){ 73 | Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show(); 74 | }else{ 75 | Toast.makeText(this, "请仔细检查用户信息", Toast.LENGTH_SHORT).show(); 76 | } 77 | } 78 | } 79 | -------------------------------------------------------------------------------- /app/src/main/java/com/heima/ormlitedemo/TestOpenHelper.java: -------------------------------------------------------------------------------- 1 | package com.heima.ormlitedemo; 2 | 3 | import android.content.Context; 4 | import android.database.sqlite.SQLiteDatabase; 5 | 6 | import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper; 7 | import com.j256.ormlite.support.ConnectionSource; 8 | import com.j256.ormlite.table.TableUtils; 9 | 10 | import java.sql.SQLException; 11 | 12 | /** 13 | * 1.1版本 1 14 | * 1.3版本 1 15 | * 2.1版本 2 16 | */ 17 | 18 | public class TestOpenHelper extends OrmLiteSqliteOpenHelper { 19 | public TestOpenHelper(Context context) { 20 | super(context, "user.db", null, 1); 21 | } 22 | 23 | @Override 24 | public void onCreate(SQLiteDatabase database, ConnectionSource connectionSource) { 25 | //创建User表 26 | try { 27 | TableUtils.createTable(connectionSource, User.class); 28 | // TableUtils.createTable(connectionSource, RecepitAddressBean.class); //卸载重装,新用户 29 | } catch (SQLException e) { 30 | e.printStackTrace(); 31 | } 32 | } 33 | 34 | @Override 35 | public void onUpgrade(SQLiteDatabase database, ConnectionSource connectionSource, int oldVersion, int newVersion) { 36 | //数据库版本变大时执行这里 37 | // try { 38 | // TableUtils.createTable(connectionSource, RecepitAddressBean.class);//覆盖安装 adb istall -r ,老用户 39 | // } catch (SQLException e) { 40 | // e.printStackTrace(); 41 | // } 42 | } 43 | } 44 | -------------------------------------------------------------------------------- /app/src/main/java/com/heima/ormlitedemo/User.java: -------------------------------------------------------------------------------- 1 | package com.heima.ormlitedemo; 2 | 3 | import com.j256.ormlite.field.DatabaseField; 4 | import com.j256.ormlite.table.DatabaseTable; 5 | 6 | @DatabaseTable(tableName = "t_user") 7 | public class User { 8 | @DatabaseField(id = true) 9 | private int id; 10 | @DatabaseField(columnName = "name") 11 | private String name; 12 | @DatabaseField(columnName = "balance") 13 | private float balance; 14 | @DatabaseField(columnName = "discount") 15 | private int discount; 16 | @DatabaseField(columnName = "integral") 17 | private int integral; 18 | @DatabaseField(columnName = "phone") 19 | private String phone; 20 | 21 | public int getId() { 22 | return id; 23 | } 24 | 25 | public void setId(int id) { 26 | this.id = id; 27 | } 28 | 29 | public String getName() { 30 | return name; 31 | } 32 | 33 | public void setName(String name) { 34 | this.name = name; 35 | } 36 | 37 | public float getBalance() { 38 | return balance; 39 | } 40 | 41 | public void setBalance(float balance) { 42 | this.balance = balance; 43 | } 44 | 45 | public int getDiscount() { 46 | return discount; 47 | } 48 | 49 | public void setDiscount(int discount) { 50 | this.discount = discount; 51 | } 52 | 53 | public int getIntegral() { 54 | return integral; 55 | } 56 | 57 | public void setIntegral(int integral) { 58 | this.integral = integral; 59 | } 60 | 61 | public String getPhone() { 62 | return phone; 63 | } 64 | 65 | public void setPhone(String phone) { 66 | this.phone = phone; 67 | } 68 | 69 | public User() { 70 | } 71 | 72 | public User(int id, String name, float balance, int discount, int integral, String phone) { 73 | this.id = id; 74 | this.name = name; 75 | this.balance = balance; 76 | this.discount = discount; 77 | this.integral = integral; 78 | this.phone = phone; 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 12 | 13 |