Hello friends! In this post, I will discuss about ORM in Beego Application. Before moving to the implementation part, we have to understand what exactly ORM is. ORM, i.e., Object Relational Mapping is like a bridge between a programming language and relational database. We don't need to write SQL queries if we use ORM. It reduces the code complexity and makes the code more clearer and readable. It also speeds up the development process of an application. So, that's said, let us move to the implementation part.
Even though, Golang has package for ORM in its standard library, Beego Framework also has its own package for the ORM. In this tutorial, I will show you the use of package that is available in the Beego Framework.
If you want to download the package separately, simply run below command:
go get "github.com/astaxie/beego/orm"
But, if you don't want to download it separately, just import this
package, and run below command:
go mod tidy
But before running this command, make sure you have initialised
the module using below command:
go mod init <module_name>
You also have to import the package for sql driver. In this
tutorial, I will be using mysql.
log has been imported to log the data.
Now, you have to define the structure of the table. To do that,
simply define a structure. Here, I want to create a table named Product,
So, I have defined below struct:
Here, table Product will have fore columns: Id, Name, Price and Weight.
Mapping between data type of the fields in Golang and data type in MySQL will be discussed
in a separate post. For now, I have defined a very simple structure which will create a table
with the columns same as fields defined in the structure with default options.
Now, We have to define the structure of the table and the database:
orm.RegisterModel(new(Product))
It is generally considered a good practice to call these methods in the init() function.
Here, I have called RunSyncdb() method also. It will make changes in
the table according to the structure defined for the table Product.
Now, you can insert data in the table:
Below is the fully implemented code:
package main