Ecosyste.ms: Awesome
An open API service indexing awesome lists of open source software.
https://github.com/cheerego/gorm-generics
gorm generics
https://github.com/cheerego/gorm-generics
generics go golang gorm
Last synced: 3 days ago
JSON representation
gorm generics
- Host: GitHub
- URL: https://github.com/cheerego/gorm-generics
- Owner: cheerego
- Created: 2022-05-16T08:43:32.000Z (over 2 years ago)
- Default Branch: master
- Last Pushed: 2022-05-16T08:47:56.000Z (over 2 years ago)
- Last Synced: 2025-01-01T11:02:45.134Z (7 days ago)
- Topics: generics, go, golang, gorm
- Language: Go
- Homepage:
- Size: 3.91 KB
- Stars: 4
- Watchers: 2
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
## gorm-generics
go generics use in gorm demo
### example
```go
package mainimport (
"context"
gorm_generic "github.com/cheerego/gorm-generics"
"gorm.io/gorm"
"log"
)type Student struct {
gorm.Model
Name string
Age int
}type StudentRepository struct {
gorm_generic.BaseRepository[Student]
db *gorm.DB
}func NewStudentRepository(db *gorm.DB) *StudentRepository {
return &StudentRepository{
BaseRepository: gorm_generic.NewBaseRepository[Student](db),
db: db,
}
}
func (s *StudentRepository) CustomQuery(ctx context.Context) (*Student, error) {
var m Student
err := gorm_generic.FromContext(ctx, s.db).First(&m, 1).Error
if err != nil {
return nil, err
}
return &m, nil
}func main() {
db, err := gorm.Open(nil)
if err != nil {
log.Fatalln(err)
}r := NewStudentRepository(db)
students := []*Student{
{
Name: "test1",
Age: 18,
},
{
Name: "test2",
Age: 18,
},
}r.BatchInsert(context.TODO(), students)
r.FindById(context.TODO(), 1)
r.FindByIdsWithDeleted(context.TODO(), 1)
r.CustomQuery(context.TODO())}
```