Translation Ormlite Document--How to use part (ii)

Source: Internet
Author: User

Objective

This document is translated into the first learning Ormlite framework, please correct me if there is something wrong in it. If the translation is inconsistent with the original document, please refer to the original document. In principle, it is recommended to learn the original English documents.

----------------------------------------------------------------------------------------------

Second, how to use the 2.7 table creation

Ormlite provides some tool classes to create table and schema for the classes you store in your database.

2.7.1 Tableutils Class

TableUtilsclass provides a number of static methods to help create and delete a table, and to provide schema declarations. See Tableutils Class

    • CreateTable (Connectionsource, Class)
    • Createtableifnotexists (Connectionsource, Class)
    • CreateTable (Connectionsource, Databasetableconfig)
    • Createtableifnotexists (Connectionsource, Databasetableconfig)
    • Droptable (Connectionsource, Class, Boolean ignoreerrors)
    • Droptable (Connectionsource, Databasetableconfig, Boolean ignoreerrors)
    • Getcreatetablestatements (Connectionsource, Class)
    • ClearTable (Connectionsource, Class)
    • ClearTable (Connectionsource, Databasetableconfig)
2.7.2 Tablecreator Class

Tablecreator This class is designed for use with the spring framework, but is useful in other configurations. It configures the Connectionsource and the DAO list that is used by the program.

If the system property Ormlite.auto.create.tables is set to a true value, he will automatically create the tables associated with these DAO. If the system property Ormlite.auto.drop.tables is set to a true value, it also automatically deletes the created table. This is especially useful when testing: you start using a test database that gets the latest schema, but you need to manually change a specific schame in the actual production process. You can set the system properties when you run the test script, but close it when you run the actual script

list<dao<?,? >> daolist = new arraylist<dao<?,? >>();d aolist.add (Accountdao); Tablecreator Creator =   new tablecreator (Connectionsource, daolist);//Create the tables if the right system proper Ty is setcreator.maybecreatetables () ...//later, we may want to drop the tables that were created CREATOR.MAYBEDROPTABL Es ();  
2.8 Unique identification

Database rows can be defined by specific columns as identities of identity columns. rows do not need to have an identity column, but many DAO operations (update, delete, refresh) require an identity column. This identity can be provided by the user, or it can be generated automatically by the database. if you want to query the ID, delete, refresh, or update a particular line that uses DAO, there must be a unique value for each row of the table. to configure a field as a standard literate segment, you should use one (and only one) from @DatabaseField  the following three settings: id , generatedId  or generatedIdSequence。

2.8.1 Id

In the example account of our door, the string name field is already indicated id = true . This means name  the identity field for the object. each account stored in the database must have a unique value of name field-you cannot have two lines of the name "John Smith".

public class account {    @DatabaseField (id = True)    private String name;    ...}  

When you use DAO to find an account with a specific name, you will use the Identity field to find the object in the database Account :

Account account = Accountdao.queryforid ("John Smith"), if (account = = null) {    //The name "John Smith" does Not match any rows} 

Note: If you need to change the value of an Object identity field, you must use the Dao.updateId()  method. Ormlite first finds the object by its old ID, and then updates it to the new ID. See UpdateID.

2.8.2 Generatedid

You can configure a long or integer field as the identity column, which will be generated by the Automatic database field.

public class Order {    @DatabaseField (Generatedid = True)    private int ID;    ...}  

When an Order object is passed to the Create method and stored in the database, the value of this identity field is returned by the database and set to object by Ormlite. In most databases, this value generates a value starting at 1, each time +1.

Build our Order object without an idorder order = New Order ("Jim Sanders", 12.34); .... orderdao.create (order); SYSTEM.OUT.PRINTLN ("Order id" + order.getid () +   "is persisted to the database");//query for the Order with an ID of 1372order = Orderdao.queryforid (1372), if (order = = null) {   //None of the order rows has an ID of 137 2}   

In the preceding code example, the command construct has name and amount (for example). When it is passed to the DAO create  method, the ID field is not set. After it has been saved to the database, the build ID will be ormlite on the ID field and create  will be available when called on the order object returned by the method getId()  .

Note: you can also generate other special field types such as UUID . See UUID.

Note: You can use the allowGeneratedIdInsert field settings to allow inserting an object into a table or without an ID already set. See Allowgeneratedidinsert.

2.8.2 Generatedidsequence

Some databases use a sequence generator to provide the generated ID value. If you use generatedId = true, those database sequence names will be automatically generated by Ormlite. If you need to set the name to exist in the existing schema, you can use the generatedIdSequence  string name of the sequence of values.

public class Order {    @DatabaseField (generatedidsequence = "Order_id_seq")    private int ID;    ...}  

In the example above, the id  values are automatically regenerated but use order_id_seq a sequence of names. If you are using a database that does not support sequences, this throws an exception.

2.9 Use of DAO

The following is a simple way to complete a database operation by using the DAO method

  1. Create and persist objects to the database.
    Inserts a record into the database with the object.
    Account Account = new Account (), Account.name = "Jim Coakley"; accountdao.create (account)  ;
  2. Querying by ID
    If the object has an ID member variable defined by the annotation, we can find the object in the database by its ID.
    Account account = Accountdao.queryforid (name), if (account = = null) {Account not  found handling ...} 
  3. Update the data associated with the object
    If you change the member variable of an object in memory, you must call update to persist it to the database. This requires an ID field
    Account.password = "_secret"; accountdao.update (account);
  4. Refresh the database with changed objects
    If some database entities related to in-memory objects have changed, you need to refresh to get the latest storage objects. This requires an ID field.
    Accountdao.refresh (account);
  5. Delete data from the database
    Deletes the records associated with the object from the database. Once the object is deleted from the database, you can continue to use objects in memory, but any updates or refreshes are likely to fail. This requires an ID field.
    Accountdao.delete (account);
  6. traverse all records in a table
    DAO also has iterators, so you can simply execute all the records in the database.
    //page through all of the accounts in the Databasefor  (account Account:accountdao) {System.out.print ln (account.getname ());}  

    Note: You must traverse all the entries in the iterator to close the underlying SQL object. If you do not loop through all the paths, then Ormlite does not know to close the underlying object, and a connection to the database may be compromised, and if later the garbage collector gets it, it will be forced to shut down, which will yield holes in your code. Use the following try ... finally template to wrap the iterator.
    For example, the following for Loop is a very bad pattern.

     for  (account Account:accountdao) {if (Account.getname (). Equals ("Bob Smith" )) {//CA    N ' t return, break, or throw from this return  account; }}    

    If exiting the loop throws an exception, you should not use the for loop in these cases, which can also occur. This is also the case of lazy loading collections. See lazy collection iterator.

  7. Using iterators directly
    You can also use iterators directly because loops are for not optimal. This allows you to use try ... finally this as a lot better mode.
    Closeableiterator<account> iterator =    accountdao.closeableiterator (); try {    while ( Iterator.hasnext ()) {account Account        = iterator.next ();        System.out.println (Account.getname ());}    } Finally {    //close it at the end to close underlying SQL statement iterator.close ();}   
  8. Get an iterator for a wrapper
    You can also use "Wrapped iterable", which allows you to use close in finally and always use loops.
    closeablewrappediterable<account> wrappediterable =    accountdao.getwrappediterable (); try {    for (account account:wrappediterable) {        ...    }} finally {    wrappediterable.close ();} 
2.10 Index Fields

Ormlite provides some limited support for indexing multiple fields in the POJO. First, it highlights that any member property that is flagged as an ID is indexed. member properties tagged by ID no longer need to create additional indexes, and some databases may have errors if specified.

To add an index to a non-primary key field you need to add an annotation @DatabaseField (index=true), see Index. This will create a non-unique index to the member variable when the table is created and will delete the index if the table is deleted. Indexes are used to help optimize queries and to significantly optimize query time when querying a table with large amounts of data in the media.

 public  class   account {@DatabaseField (id  = true  )  private   String name;  //  This indexes the City field so queries on City  //  would go faster for large tables
     @DatabaseField (index = true   private   String City; ...}  

This example creates an index on the account table account_city_idx . If you want to use a different name, you can use the indexName = "othername",  name of the index that allows you to specify.

If you often need to query both City and state on an SQL statement, you might want to create an index on both fields. Ormlite supports multiple fields to create an index by specifying the same indexName value for each member property that you want on the index.

@DatabaseField (IndexName = "Account_citystate_idx")private= "Account_citystate_idx" )private String state;

This example creates the same index for the city and State member outputs. Note that the city query alone is not optimized for queries, and is optimized only if you are querying the city and state two fields in a long keyword. On some databases, it may be better to have a separate index for each field when querying city and state, allowing the database to use two indexes at the same time . For other databases, it is recommended to create an index on multiple member variables. You may need to try using the SQL explain command to find out how your database is using your index.

Create a unique index, Uniqueindex = true and Uniqueindexname = "Othername" are valid in @DatabaseField annotations. These actions, like the above settings, simply create a unique index to ensure that no two records have the same value for the index.

-----------------------------------------------------------------------------

Since this document is too long, please refer to [Translate] ormlite document-How to use part (iii)

Translation Ormlite Document--How to use part (ii)

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.