Students who use Golang to manipulate the database will encounter a problem-creating a corresponding struct model from the data table structure. Because Golang uses the first letter to control the visible range, we often design the correspondence between the struct field name and the database field name. Over time, this is a very tedious process. Things get tedious, and we all wonder, is there a good way to generate model automatically? Today, a method--xorm tool that automatically generates code is recorded.
About Xorm
Xorm is a simple and powerful go language ORM library. It makes it easy to operate the database. I use it frequently in projects, and it features the following
- Supports flexible mapping between struct and database tables, and supports automatic synchronization of table structures
- Transaction support
- Supports mixed execution of raw SQL statements and ORM Operations
- Use ligatures to simplify calls
- Supports the use of IDs, in, Where, Limit, Join, have, Table, SQL, cols and other functions and structures as conditions
- Supports cascading load structs
- LRU Cache Support (memory, Memcache, LEVELDB, Redis cache store) and Redis cache
- Support inversion, that is, automatically generate Xorm structure according to the database
- Support Events
- Supports created, updated, deleted and version record versions (i.e. optimistic locks)
Xorm Tools
Xorm is a set of tools for database operations commands that contain the following commands:
- Reverse Reverse a database structure, generate code
- shell -Generic database operations client for database structure and data manipulation
- Dump All structures and data in the DUMP database to standard output
- source executes the SQL file from the callout input
- driver List all supported database drivers
So how do we use the reverse command to generate go code based on the data table structure?
get github.com/go-xorm/cmd/get github.com/go-xorm/xorm
To the Gopath\src\github.com\go-xorm\cmd\xorm directory, execute the
Go Build
The Xorm.exe file is generated under this directory
Next, start the execution
./xorm reverse MySQL root:[email protected]?charset=utf8 templates/goxorm
Next, generate the following files in the current directory models:
Golang Xorm tool, automatically generate go code based on database