Install Libraries
Make sure Git is installed on your machine and in your system’s PATH. Install the package to your $GOPATH with the go tool from shell:
$ go get github.com/go-sql-driver/mysql
$ go get -u github.com/jinzhu/gorm
Create Database
Create a database with the name is learngorm. This database have 1 tables: Product table.
--
-- Table structure for table `product`
--
CREATE TABLE `product` (
`id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
`name` varchar(250) NOT NULL,
`price` double NOT NULL,
`quantity` int(11) NOT NULL,
`status` tinyint(1) NOT NULL,
`created` date DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;
--
-- Dumping data for table `product`
--
INSERT INTO `product` (`name`, `price`, `quantity`, `status`, `created`) VALUES
('Tivi 1', 4, 2, 1, '2019-07-10'),
('Tivi 2', 7, 22, 0, '2019-11-08'),
('Mobile 1', 11, 7, 1, '2019-07-11'),
('Mobile 2', 26, 8, 1, '2018-05-04'),
('Computer 1', 8, 2, 0, '2018-07-26');
Structure of Product Table
Data of Product Table
Create Entity
Create new folder named src. In src folder, create new folder named entities. In this folder, create new file named product.entity.go as below:
package entities
import (
"fmt"
"time"
)
type Product struct {
Id int `gorm:"primary_key, AUTO_INCREMENT"`
Name string
Price float64
Quantity int
Status bool
Created time.Time
}
func (product *Product) TableName() string {
return "product"
}
func (product Product) ToString() string {
return fmt.Sprintf("id: %d\nname: %s\nprice: %0.1f\nquantity: %d\nstatus: %t\ncreated: %s", product.Id, product.Name, product.Price, product.Quantity, product.Status, product.Created.Format("02/01/2006"))
}
Create Config
In src folder, create new folder named config. In this folder, create new file named config.go, this file is used to connect mysql database:
package config
import (
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
)
func GetDB() (*gorm.DB, error) {
dbDriver := "mysql"
dbName := "learngorm"
dbUser := "root"
dbPassword := "123456"
db, err := gorm.Open(dbDriver, dbUser+":"+dbPassword+"@/"+dbName+"?charset=utf8&parseTime=True")
if err != nil {
return nil, err
}
return db, nil
}
Create Model
In src folder, create new folder named models. In models folder, create new file named product.model.go. This file contains methods to interact with the database.
package models
import (
"config"
"entities"
)
type ProductModel struct {
}
func (productModel ProductModel) StartsWith(keyword string) ([]entities.Product, error) {
db, err := config.GetDB()
if err != nil {
return nil, err
} else {
var products []entities.Product
db.Where("name like ?", keyword+"%").Find(&products)
return products, nil
}
}
func (productModel ProductModel) EndsWith(keyword string) ([]entities.Product, error) {
db, err := config.GetDB()
if err != nil {
return nil, err
} else {
var products []entities.Product
db.Where("name like ?", "%"+keyword).Find(&products)
return products, nil
}
}
func (productModel ProductModel) Contains(keyword string) ([]entities.Product, error) {
db, err := config.GetDB()
if err != nil {
return nil, err
} else {
var products []entities.Product
db.Where("name like ?", "%"+keyword+"%").Find(&products)
return products, nil
}
}
Structure of Project
Run Application
In src folder, create new file named main.go as below and use go run main.go command to run program:
package main
import (
"fmt"
"models"
)
func main() {
var productModel models.ProductModel
fmt.Println("Start with mob string")
result1, _ := productModel.StartsWith("mo")
for _, product := range result1 {
fmt.Println(product.ToString())
fmt.Println("--------------------")
}
fmt.Println("Ends with vi 1 string")
result2, _ := productModel.EndsWith("vi 1")
for _, product := range result2 {
fmt.Println(product.ToString())
fmt.Println("--------------------")
}
fmt.Println("Contains bi string")
result3, _ := productModel.Contains("bi")
for _, product := range result3 {
fmt.Println(product.ToString())
fmt.Println("--------------------")
}
}
Output
Start with mob string
id: 3
name: Mobile 1
price: 11.0
quantity: 7
status: true
created: 11/07/2019
--------------------
id: 4
name: Mobile 2
price: 26.0
quantity: 8
status: true
created: 04/05/2018
--------------------
Ends with vi 1 string
id: 1
name: Tivi 1
price: 4.0
quantity: 2
status: true
created: 10/07/2019
--------------------
Contains bi string
id: 3
name: Mobile 1
price: 11.0
quantity: 7
status: true
created: 11/07/2019
--------------------
id: 4
name: Mobile 2
price: 26.0
quantity: 8
status: true
created: 04/05/2018
--------------------