Quickly Start

ORM examples

Beego’s ORM is designed as two:

  • Normal Orm instances: These instances are stateless, so you should keep a database with only one instance if possible. Of course, even if you create a new instance every time, it’s not a big deal, it’s just not necessary;
  • TxOrm: This is the Orm object obtained after starting a transaction, it can only be used within the transaction, and will be discarded after commit or rollback, and cannot be reused. A new instance needs to be created for each transaction.

Quickly Start

Exmaple:

  1. import (
  2. "github.com/beego/beego/v2/client/orm"
  3. // don't forget this
  4. _ "github.com/go-sql-driver/mysql"
  5. )
  6. // User -
  7. type User struct {
  8. ID int `orm:"column(id)"`
  9. Name string `orm:"column(name)"`
  10. }
  11. func init() {
  12. // need to register models in init
  13. orm.RegisterModel(new(User))
  14. // need to register default database
  15. orm.RegisterDataBase("default", "mysql", "root:123456@tcp(127.0.0.1:3306)/beego?charset=utf8")
  16. }
  17. func main() {
  18. // automatically build table
  19. orm.RunSyncdb("default", false, true)
  20. // create orm object
  21. o := orm.NewOrm()
  22. // data
  23. user := new(User)
  24. user.Name = "mike"
  25. // insert data
  26. o.Insert(user)
  27. }

In general, it can be divided into the following steps:

It is important to note that you must introduce the driver anonymously according to the database you are using. i.e. "github.com/go-sql-driver/mysql"

Debug log

In the development environment, you can output the SQL:

  1. func main() {
  2. orm.Debug = true

When turned on, all query statements will be output, including execution, preparation, transactions, etc. Note that this option should not be turned on in production environments, as outputting logs can seriously impact performance.