Xorm-Lesson 1: Common usage guidance

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

Precautions

This blog belongs to Xorm-Lesson 1: Common usage Guidance Please note the use of the companion.

This blog post is a companion blog for the Xorm-go language ORM, which is designed to explain the use and case of the library through text-to-code examples, making it easier for your classmates to use and learn more.

Library Introduction

Xorm is an ORM third-party library for the Go language, featuring simple yet rich, practical APIs to perform various operations on the database. The library supports mainstream databases, including MySQL, PostgreSQL, SQLite3, and MsSQL, and allows mixed processing with SQL statements, based on support for chained operations. In addition, supporting session transactions and rollback and optimistic locking is one of the reasons why the library is becoming popular.

Download installation

There are two ways you can download the installation xorm:

gopm get github.com/go-xorm/xorm

Or

go get github.com/go-xorm/xorm

API Documentation

Go Walker, please.

Basic Use Method

Sample code

Defining the Model

Before you can use the Go language ORM, you need to define the model. For the Go language, the definition of the model is accomplished by defining a struct (struct) and the type and tag of the field of the struct. For example, in this lesson example, we define a model for a bank account by using the following code:

type Account struct {    Id      int64    Name    string `xorm:"unique"`    Balance float64    Version int `xorm:"version"` // 乐观锁}

Because the relational database involves the primary key problem, in order to make it easier for the user to use, int64 any field with a field name that Id does not have any tag defined will automatically be considered a primary key. If you want to use a different name as the primary key, you can set it in tag pk to tell Xorm.

The tag of the field Name is used to indicate that the unique value of the field record is unique across the data table and that duplicate user names cannot occur.

The last line of optimistic lock is not in-depth, the text will be described later.

When defining a model, it is important to note that the first letter of all fields must be uppercase (the Go language export rule), otherwise ORM is unable to get the name and type of the field through reflection, and may throw panic.

Because the example is relatively simple, it is not possible to enumerate all the tag definitions supported by Xorm, and the complete list can be viewed here.

Creating an ORM engine

After the model definition is complete, we need to create an ORM engine. When you create this step of the ORM engine, you need to determine the database driver you are using and the associated link information (database HOST, user, password, and so on). This example uses SQLite3, so you only need to specify the path where the database files are located:

x, err = xorm.NewEngine("sqlite3", "./bank.db")

The Go language requires that the database driver used must be registered before it can be used, so all the driver libraries register themselves in the Init function so that we do not have errors when we use them. Similarly, using ORM also requires registering the database driver that we use, so how do I register it?

Because of the wide variety of database drivers, it is common for each ORM to select only one driver for a database, so before registering the driver, you need to confirm whether the ORM you are using supports the driver you have chosen. For example, Xorm supports up to 5 database drivers.

Here's how to register a database driver:

import (    _ "github.com/mattn/go-sqlite3")

Many students see the import path in front of the _ underline to understand, this is not good to learn the production of "Go programming fundamentals" of the consequences. Adding an underscore before the path is imported means that only the INIT function of the library is executed and no other exported objects are actually imported. Because the Go Language database driver registers itself in the INIT function, we only need to do this, otherwise the Go language compiler will prompt you to import the package without using the error.

Automatic synchronization of Table structures

Xorm has a great feature that supports automatic incremental synchronization of data table structures. What do you mean? That is, after you have finished creating the database, ORM automatically creates the data table based on the defined model, which is why we need to use tag to make some special designations to the fields (for example, unique). Incremental synchronization means that only new fields or tag definitions are synchronized, including the newly defined model, field, and tag rules, and if you delete or modify a field, the columns you have created are not deleted or modified for security reasons, but are ignored or newly modified columns.

The ability to automatically synchronize the data table structure provided by Xorm is called by the following method:

err = x.Sync(new(Account))

Method Sync needs to pass in all the models that you will use, in this case only Account . A method is used new() to create an object one time because the work of the ORM parsing struct is done through reflection, and only passing an instance object allows the ORM to get the corresponding fields and tags.

increase, delete, change the operation

First, let's look at how to use Xorm to achieve the most basic increase, delete, change operation.

New record

Insert a new record that must be non-existent or return an error:

_, err := x.Insert(&Account{Name: name, Balance: balance})

Deleting records

Delete a record:

_, err := x.Delete(&Account{Id: id})

Deletewhen the method accepts the parameter, it is automatically searched based on the value passed in and then deleted. For example, the ID field we specify here Account will delete the record with the same ID field value as we assigned, and if you only assign a value to the Name field, then Xorm will look for a record that matches the Name field value. If multiple fields are assigned at the same time, the records that are met by multiple criteria are deleted.

There are no restrictions on the objects that are targeted by the delete operation, which are deleted (individually and in bulk) if the condition is found.

Get and modify Records

According to the requirements of xorm, if you want to update a record, the record must already exist, so we need to get the corresponding information of the record, then make the modification, and then update it:

a := &Account{}has, err := x.Id(id).Get(a)

Method Get returns only a single record, similar to a delete operation, any assignment to the variable A will become a lookup condition. But the flexibility of the xorm is that you can also easily achieve the same needs with chain-operated operations. As in this example, the Id method is used directly to get the record of the specified ID.

The method returns two values, the first of which is the bool type, indicates whether the record is found, and the second is the error type, which indicates whether another error occurred.

After we get to the record, we need to make some changes and then update to the database:

a.Balance += deposit// 对已有记录进行更新_, err = x.Update(a)

Updatethe first parameter that the method accepts must be a pointer address, pointing to the content that needs to be updated. In addition, it allows you to receive the second parameter, which is the same as the conditional query mentioned earlier in the delete and get operation, and if you pass in the second parameter, the criteria are filtered according to the parameters and the corresponding fields are updated.

Get information in bulk

In addition to obtaining a single record, in order to be able to better view the content, sometimes we will need to remove more than one record at a time, and a certain sort.

Therefore, the method for obtaining Get all eligible records is corresponding to the methodology for obtaining a single record Find :

err = x.Desc("balance").Find(&as)

Here, we also call the Desc method to sort the accounts from large to small according to the deposit amount.

The Find first argument that the method accepts must be a pointer address for a type of slice, in this case the pointer address of a slice of the type of the element, and Account its second parameter is also the condition parameter, which is described in detail earlier in this article.

Optimistic lock

Optimistic locking is a more practical feature provided by Xorm, which is opened by specifying it in tag version . Once turned on, the value of the field is automatically incremented by 1 each time the record is updated. As a result, you can determine if there are other places that have modified the record at the same time, and if so, you should re-operate it, otherwise the wrong data will appear (and the amount that you have withdrawn from an account is deducted only once).

Summary

This class is only for the first lesson of Xorm, in the code implementation of the pursuit of basic, intuitive, does not involve a lot of content, so as not to let novice appear confused. Therefore, the code in this example is actually flawed, for example, when a transaction should be used in order to roll back when an error occurs, so that neither side returns to the original amount when the transfer fails.

Related Article

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.