I am using Gorp for database access, Gorp has a standard DbMap
type, as well as a Transaction
type for when you want to be able to roll back. Both types implement the SqlExecutor
interface.
I am therefore programming against the SqlExecutor
interface, so I can use transactions if I want without needing to change my code.
I then initialise a Gorp DbMap
or Transaction
and pass it in as a field property. The problem is that I need a pointer to the Gorp "object", else how will I be able to roll back if I use a Transaction
if the Gorp "object" is passed by value instead of reference.
I then get a message such as
r.Gorp.Get undefined (type *gorp.SqlExecutor has no field or method Get)
when I try use my code. How do I call the methods?
A code sample is below.
package repositories
import (
"github.com/coopernurse/gorp"
)
type Repository struct {
Gorp *gorp.SqlExecutor // <<<< Need pointer so I can rollback
}
func (r *Repository) GetById(i interface{}, key interface{}) interface{} {
obj, err := r.Gorp.Get(i, key)
if err != nil {
panic(err)
}
return obj
}
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…