Skip to main content

DAO Auto Generation and Usage

Database operations and data structures are typically organized into dao and model. In GoFrame, content for dao and model can be automatically generated. Here are the steps to generate them:

  1. Configure dao

Modify hack/comfig.yaml

gfcli:
gen:
dao:
link: "mysql:root:root@tcp(127.0.0.1:3306)/goframe"
tables: "book, user, dept, emp, hobby"
jsonCase: "Snake"
  • link: Database connection URL.
  • tables: Comma-separated list of tables for which dao and model need to be generated.
  • jsonCase: Conversion method for entity members when converting to JSON. "Snake" converts camel case to snake case.

The above is a basic configuration. For more configurations, refer to the official documentation on Code Generation/Data Specification gen dao.

  1. Execute the following command in the command line:
gf gen dao

This command generates structures and code for each table under dao and model.

When using the Model object corresponding to each table afterward, instead of using g.Model to obtain it, use the following approach:

md := dao.Book.Ctx(ctx)
books, err := md.All()

You can stack multiple query conditions with this Model object:

md := dao.Book.Ctx(ctx)
md = md.WhereGT("id", 3)
md = md.WhereLT("id", 6)
books, err := md.All()

// The above code is equivalent to:
books, err := dao.Book.Ctx(ctx).WhereGT("id", 3).WhereLT("id", 6).All()