Android OrmLite and androidormlite

Source: Internet
Author: User

Android OrmLite and androidormlite

Recently, I am using the ormlite framework for database operations. Here is a simple demo to learn.

1. Download the jar package

Here ormlite-core-5.0.jar and ormlite-android-5.0.jar are used

Place the downloaded jar package in the libs folder of our project.

2. Create an object class Object

Each object class corresponds to a table, and a Student class is created under the bean directory in our project.

Package com. item. jiejie. lite. db; import com. j256.ormlite. field. databaseField; import com. j256.ormlite. table. databaseTable;/*** defines the object class Bean, which represents a table * class to be persisted to the database. Before the class name, add @ DatabaseTable, to generate the corresponding table class members, add @ DatabaseField to generate the fields in the previous table * Note: the constructor * Created by jiejie on must have no parameters in the class to be persisted. */@ DatabaseTable (tableName = "tb_hello") public class Hello {@ DatabaseField (generatedId = true) private int id; @ DatabaseField (columnName = "name") private String name; @ DatabaseField (columnName = "sex") private String sex; @ DatabaseField (columnName = "age") private int age;/** common parameter * generatedId = true primary key, automatically Generated id the field under this annotation must be an integer (int long) * id = true primary key * unique = true unique constraint default false * columnName = "name" Table field name, the default variable name * canBeNull = false is a non-empty constraint. The default value is true. It can be null. If it is set to false, it cannot be null * foreign = true foreign key reference, the field cannot be of the original type. An object should be defined as a foreign key reference. In the class of the foreign key object, there must be an ID field (ID, generatedId, generatedIdSequence) * foreignAutoRefersh = true when using a foreign key reference, because the foreign key reference of ormlite uses an object, if you add this field, it will be queried, the * foreign key object data will be queried back. Otherwise, the foreign key data will only have a value for the primary key of the object, the remaining values are null * defaultValue = "James" default * index = true index creation default * uniqueIndex = true unique index default is false * // empty constructor must be required yes, otherwise, the database fails to be created. public Hello () {} public Hello (String name, String sex, int age) {this. name = name; this. sex = sex; this. age = age;} public String getName () {return name;} public void setName (String name) {this. name = name;} public String getSex () {return sex;} public void setSex (String sex) {this. sex = sex;} public int getAge () {return age;} public void setAge (int age) {this. age = age ;}@ Override public String toString () {return "Hello {" + "name = '" + name +' \ ''+ ", sex = '"+ sex +' \'' + ", age =" + age + '}';}}

3. compile our data helper class

Package com. item. jiejie. lite. db; import android. content. context; import android. database. sqlite. SQLiteDatabase; import android. util. log; import com. j256.ormlite. android. apptools. ormLiteSqliteOpenHelper; import com. j256.ormlite. dao. dao; import com. j256.ormlite. support. connectionSource; import com. j256.ormlite. table. tableUtils; import java. SQL. SQLException;/*** write DAO class * Created by jiejie on. */public class DataHelper extends OrmLiteSqliteOpenHelper {private static final String TABLE_NAME = "Hellotext. db ";/*** no helloDao table corresponds to a */private Dao <Hello, Integer> helloDao = null;/** constructor */public DataHelper (Context context) {super (context, TABLE_NAME, null, 1) ;}// create a data Table @ Override public void onCreate (SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource) {try {TableUtils. createTable (connectionSource, Hello. class); Log. d ("jiejie", "database created successfully");} catch (SQLException e) {e. printStackTrace (); Log. d ("jiejie", "database updated successfully") ;}// database update @ Override public void onUpgrade (SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource, int I, int i1) {try {TableUtils. dropTable (connectionSource, Hello. class, true); onCreate (sqLiteDatabase, connectionSource);} catch (SQLException e) {e. printStackTrace () ;}}/*** obtain the Helper * 1 for a single instance. privatize constructors first * 2. provide external static method * 3. in the method, it is determined that if the method already exists, it will not be created. If it does not exist, then it will always have only one DataHelper object * 4. to ensure thread security, you need to provide another thread security keyword synchronized */private static DataHelper instance; public static synchronized DataHelper getHeper (Context context) {if (instance = null) {synchronized (DataHelper. class) {if (instance = null) {instance = new DataHelper (context) ;}}return instance;} public Dao <Hello, Integer> getHelloDao () throws SQLException {if (helloDao = null) {helloDao = getDao (Hello. class);} return helloDao;} public synchronized void clearData (Class <Hello> clase) {try {TableUtils. clearTable (connectionSource, clase);} catch (SQLException e) {e. printStackTrace () ;}/ *** release resource */@ Override public void close () {super. close (); helloDao = null ;}}

4. Write our Dao class for addition, deletion, modification, and query operations

Package com. item. jiejie. lite. db; import android. content. context; import com. j256.ormlite. dao. dao; import com. j256.ormlite. support. databaseConnection; import java. SQL. SQLException; import java. SQL. savepoint; import java. util. arrayList; import java. util. list;/*** defines the data access object and adds, deletes, modifies, and queries the specified table * Created by jiejie on. */public class HelloDao {private Dao <Hello, Integer> helloDao; private DataHelper dataHelper;/*** constructor to obtain Database Help class instances, get the corresponding Dao * @ param context */public HelloDao (Context context) {try {dataHelper = DataHelper. getHeper (context); helloDao = dataHelper. getHelloDao ();} catch (SQLException e) {e. printStackTrace () ;}}/*** add a record * @ param hello */public void add (Hello hello) {try {helloDao. create (hello);} catch (SQLException e) {e. printStackTrace () ;}}/*** insert a large amount of data * enable transaction * disable automatic commit * @ param hellos */public void addList (List <Hello> hellos) {try {DatabaseConnection conn = helloDao. startThreadConnection (); Savepoint savepoint = conn. setSavePoint (null); helloDao. setAutoCommit (conn, false); for (Hello hello: hellos) {helloDao. createOrUpdate (hello);} conn. commit (savepoint); helloDao. endThreadConnection (conn);} catch (SQLException e) {e. printStackTrace () ;}}/*** delete a record * @ param hello */public void delete (Hello hello) {try {helloDao. delete (hello);} catch (SQLException e) {e. printStackTrace () ;}}/*** update a record * @ param hello */public void update (Hello hello) {try {helloDao. update (hello);} catch (SQLException e) {e. printStackTrace () ;}}/*** query a record * @ param id * @ return */public Hello queryForId (int id) {Hello hello = null; try {hello = helloDao. queryForId (id);} catch (SQLException e) {e. printStackTrace ();} return hello;}/*** query all records * @ return */public List <Hello> queryForAll () {List <Hello> hellos = new ArrayList <> (); try {hellos = helloDao. queryForAll ();} catch (SQLException e) {e. printStackTrace () ;}return hellos ;}}

5. Test

During the test, when I simulate inserting 3 W pieces of data, I found that different simulators have different insertion times, and some 9 s have to be nearly 10 s,

Maybe I still have some problems when writing and inserting big data.

Private class TaskDb extends AsyncTask <Integer, Void, Long >{@ Override protected void onPreExecute () {super. onPreExecute () ;}@ Override protected Long doInBackground (Integer... params) {long start = System. currentTimeMillis (); List <Hello> hList = new ArrayList <Hello> (); for (int I = 0; I <10000; I ++) {Hello hello = new Hello ("Hello" + I, "nan", I); hList. add (hello);} helloDao. addList (hList); long endTime = System. currentTimeMillis (); return endTime-start;} @ Override protected void onPostExecute (Long aLong) {super. onPostExecute (aLong); Log. d ("jiejie", "data loaded successfully" + aLong); Toast. makeText (MainActivity. this, "when data is loaded successfully" + aLong, Toast. LENGTH_SHORT ). show ();}}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.