golang xorm mysql代码生成器(java,go)

EasyNetCN · · 408 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

基于go,go template的数据层代码生成器,支持生成基于xorm go,spring jpa的数据层代码生成

main.go

package main

import (
    "fmt"
    "io/ioutil"
    "os"
    "strings"
    "text/template"
    "unsafe"

    _ "github.com/go-sql-driver/mysql"
    "gopkg.in/yaml.v2"
    "xorm.io/xorm"
)

const (
    selectCurrentDbSql = "SELECT DATABASE()"
    allColumnInfoSql   = "SELECT * FROM information_schema.columns WHERE table_schema =? ORDER BY table_schema ASC,table_name ASC,ordinal_position ASC"
)

func main() {
    config, err := NewConfiguration()

    if err != nil {
        fmt.Println("can not read configuration file,err:", err)

        return
    }
    engine, err := xorm.NewEngine("mysql", config.Datasource)

    if err != nil {
        fmt.Println("can not create database engine,err:", err)

        return
    }

    currentDb := ""

    if _, err := engine.SQL(selectCurrentDbSql).Get(&currentDb); err != nil {
        fmt.Println("can not get current database,err:", err)

        return
    }

    columns := make([]DataColumn, 0)

    if err := engine.SQL(allColumnInfoSql, currentDb).Find(&columns); err != nil {
        fmt.Println("can not get column information,err:", err)

        return
    }

    tableMap := make(map[string][]DataColumn)

    for _, column := range columns {
        tableName := column.TableName

        if _, ok := tableMap[tableName]; !ok {
            tableMap[tableName] = make([]DataColumn, 0)
        }

        tableMap[tableName] = append(tableMap[tableName], column)
    }

    funcMap := template.FuncMap{"upperCamelCase": UpperCamelCase, "lowerCamelCase": LowerCamelCase}

    t, err := template.New(config.TplName).Funcs(funcMap).ParseFiles(config.TplFile)

    if err != nil {
        fmt.Println("parse file err:", err)
        return
    }

    os.RemoveAll(config.Output)

    for table, columns := range tableMap {
        if _, err := os.Stat(config.Output); os.IsNotExist(err) {
            os.Mkdir(config.Output, 0777)
            os.Chmod(config.Output, 0777)
        }

        fileSb := new(strings.Builder)

        fileSb.WriteString(config.Output)
        fileSb.WriteString("/")

        if config.Lang == "go" {
            fileSb.WriteString(table)

            if config.TargetType == "repository" {
                fileSb.WriteString("_repository")
            }
        } else if config.Lang == "java" {
            if config.TargetType == "entity" {
                fileSb.WriteString(UpperCamelCase(table))
                fileSb.WriteString("Entity")
            } else if config.TargetType == "model" {
                fileSb.WriteString(UpperCamelCase(table))
            } else if config.TargetType == "repository" {
                fileSb.WriteString(UpperCamelCase(table))
                fileSb.WriteString("EntityRepository")
            }
        }

        fileSb.WriteString(".")
        fileSb.WriteString(config.Lang)

        f, err := os.OpenFile(fileSb.String(), os.O_CREATE|os.O_WRONLY, 0666)

        defer f.Close()

        if err != nil {
            fmt.Println("can not create output file,err:", err)

            return
        }

        if err := t.Execute(f, &Config{TableName: table, Readonly: config.Readonly, PackageName: config.PackageName, Columns: columns}); err != nil {
            fmt.Println("There was an error:", err.Error())
        }
    }

}

type Configuration struct {
    Datasource  string            `yaml:"datasource"`
    Lang        string            `yaml:"lang"`
    TargetType  string            `yaml:"target-type"`
    TplName     string            `yaml:"tpl-name"`
    TplFile     string            `yaml:"tpl-file"`
    Readonly    bool              `yaml:"readonly"`
    Output      string            `yaml:"output"`
    SkipTables  []string          `yaml:"skip-tables"`
    SkipColumns []SkipColumn      `yaml:"skip-columns"`
    TypeMap     map[string]string `yaml:"type-map"`
    PackageName string            `yaml:"package-name"`
}

type SkipColumn struct {
    Table  string `yaml:"table"`
    Column string `yaml:"column"`
}

func NewConfiguration() (*Configuration, error) {
    conf := new(Configuration)

    data, err := ioutil.ReadFile("config.yml")

    if err != nil {
        return conf, err
    }

    err = yaml.Unmarshal(data, &conf)

    return conf, err
}

type Config struct {
    TableName   string
    Readonly    bool
    PackageName string
    Columns     []DataColumn
}

func (c *Config) PrimaryColumnDataType() string {
    for _, column := range c.Columns {
        if column.IsPrimary() {
            return column.JavaType()
        }
    }

    return ""
}

func (c *Config) HasDelStatus() bool {
    for _, column := range c.Columns {
        if column.IsDelStatus() {
            return true
        }
    }

    return false
}

func (c *Config) HasDecimalType() bool {
    for _, column := range c.Columns {
        if column.IsDecimalType() {
            return true
        }
    }

    return false
}

func (c *Config) HasDateType() bool {
    for _, column := range c.Columns {
        if column.IsDateType() {
            return true
        }
    }

    return false
}

func (c *Config) HasEnterpriseId() bool {
    return c.HasColumn("enterprise_id")
}

func (c *Config) HasCode() bool {
    return c.HasColumn("code")
}

func (c *Config) HasStatus() bool {
    return c.HasColumn("status")
}

func (c *Config) HasColumn(name string) bool {
    for _, column := range c.Columns {
        if column.ColumnName == name {
            return true
        }
    }

    return false
}

type DataColumn struct {
    TableSchema            string
    TableName              string
    ColumnName             string
    OrdinalPosition        int
    ColumnDefault          string
    IsNullable             string
    DataType               string
    CharacterMaximumLength string
    CharacterOctetLength   string
    NumericPrecision       string
    NumbericScale          string
    DatetimePrecision      string
    ColumnType             string
    ColumnKey              string
    Extra                  string
    ColumnComment          string
}

func (c *DataColumn) IsIdentity() bool {
    return strings.ToLower(c.Extra) == "auto_increment"
}

func (c *DataColumn) IsPrimary() bool {
    return strings.ToLower(c.ColumnKey) == "pri"
}

func (c *DataColumn) GoLangType() string {
    dataType := strings.ToLower(c.DataType)
    nullable := strings.ToLower(c.IsNullable) == "yes"

    if dataType == "int" {
        if nullable {
            return "*int"
        }

        return "int"
    }

    if dataType == "varchar" || dataType == "text" || dataType == "longtext" {
        if nullable {
            return "*string"
        }

        return "string"
    }

    if dataType == "long" || dataType == "bigint" {
        if nullable {
            return "*int64"
        }

        return "int64"
    }

    if dataType == "decimal" {
        if nullable {
            return "*float64"
        }

        return "ifloat64"
    }

    if dataType == "datetime" {
        if nullable {
            return "*core.LocalDateTime"
        }

        return "core.LocalDateTime"
    }

    return dataType
}

func (c *DataColumn) JavaType() string {
    dataType := strings.ToLower(c.DataType)

    if dataType == "int" {
        return "Integer"
    } else if dataType == "varchar" || dataType == "text" || dataType == "longtext" {
        return "String"
    } else if dataType == "long" || dataType == "bigint" {
        return "Long"
    } else if dataType == "decimal" {
        return "BigDecimal"
    } else if dataType == "datetime" {
        return "LocalDateTime"
    } else {
        return c.DataType
    }

}

func (c *DataColumn) IsDateType() bool {
    return strings.ToLower(c.DataType) == "datetime"
}

func (c *DataColumn) IsDecimalType() bool {
    return strings.ToLower(c.DataType) == "decimal"
}

func (c *DataColumn) IsDelStatus() bool {
    return c.ColumnName == "del_status"
}

func (c *DataColumn) Tag() string {
    name := strings.ToLower(c.ColumnName)
    dataType := strings.ToLower(c.DataType)
    identity := strings.ToLower(c.Extra) == "auto_increment"
    primary := strings.ToLower(c.ColumnKey) == "pri"
    nullable := strings.ToLower(c.IsNullable) == "yes"

    sb := new(strings.Builder)

    sb.WriteString("`xorm:\"")
    sb.WriteString(dataType)
    sb.WriteString(" '")
    sb.WriteString(name)
    sb.WriteString("'")

    if identity {
        sb.WriteString(" autoincr")
    }

    if primary {
        sb.WriteString(" pk")
    }

    if nullable {
        sb.WriteString(" null")
    } else {
        sb.WriteString(" notnull")
    }

    sb.WriteString(" default(")

    if dataType == "varchar" || dataType == "text" || dataType == "longtext" {
        sb.WriteString("'")
    }

    sb.WriteString(c.ColumnDefault)

    if dataType == "varchar" || dataType == "text" || dataType == "longtext" {
        sb.WriteString("'")
    }

    sb.WriteString(")")

    sb.WriteString(" comment('")
    sb.WriteString(c.ColumnComment)
    sb.WriteString("')")

    sb.WriteString("\" json:\"")

    if name == "del_status" {
        sb.WriteString("-")
    } else {
        sb.WriteString(LowerCamelCase(c.ColumnName))
    }

    sb.WriteString("\"`")

    return sb.String()
}

func UpperCamelCase(txt string) string {
    sb := new(strings.Builder)

    strs := strings.Split(txt, "_")

    for _, str := range strs {
        sb.WriteString(strings.ToUpper(string(str[0])))
        sb.WriteString(str[1:])
    }

    return sb.String()
}

func LowerCamelCase(txt string) string {
    sb := new(strings.Builder)

    strs := strings.Split(txt, "_")

    for i, str := range strs {
        if i == 0 {
            sb.WriteString(strings.ToLower(string(str[0])))
        } else {
            sb.WriteString(strings.ToUpper(string(str[0])))
        }

        sb.WriteString(str[1:])
    }

    return sb.String()
}

func BytesToString(b []byte) string {
    return *(*string)(unsafe.Pointer(&b))
}

config.yml

datasource: ""
lang: java
target-type: repository
tpl-name: repository.tpl
tpl-file: tpl/java/repository.tpl
readonly: false
output: ""
skip-tables:
skip-columns:
type-map:
package-name: 

go/model.tpl

package model

type {{upperCamelCase .TableName}} struct{
    {{- range $column := .Columns}}
    {{- if not .IsDelStatus}}
    // {{.ColumnComment}} 
    {{upperCamelCase .ColumnName}} {{.GoLangType}}
    {{- end -}}
    {{end}}
}

go/repository.tpl

package repository

type {{upperCamelCase .TableName}} struct{
    {{range $column := .Columns -}}
    {{upperCamelCase .ColumnName }} {{.GoLangType}} {{.Tag}} 
    {{end -}}
}

func (entity *{{upperCamelCase .TableName}}) Copy(target *{{upperCamelCase .TableName}},columns []string) ([]string,[]utility.BeanUpdateLogItem){
    updateColumns:=make([]string,0,len({{lowerCamelCase .TableName}}Columns))
    updateLogItems:=make([]utility.BeanUpdateLogItem,0,len({{lowerCamelCase .TableName}}Columns))

    columnMap := make(map[string]string)

    for _,column := range columns {
        columnMap[column]=column
    }

    {{range $column := .Columns -}}
    if _,ok:=columnMap["{{upperCamelCase .ColumnName}}"];!ok && entity.{{upperCamelCase .ColumnName}} != target.{{upperCamelCase .ColumnName}}{
         updateColumns = append(updateColumns,"{{.ColumnName}}")
         updateLogItems = append(updateLogItems,utility.BeanUpdateLogItem{PropertyName:"{{upperCamelCase .ColumnName}}",OldProperyValue:entity.{{upperCamelCase .ColumnName}},NewPropertyValue:target.{{upperCamelCase .ColumnName}}})

         target.{{upperCamelCase .ColumnName}} = entity.{{upperCamelCase .ColumnName}}
    }
    {{end -}}
}

{{if not .Readonly}}
    var(
        {{lowerCamelCase .TableName}}Columns=[]string{
            {{range $column := .Columns -}}
            "{{.ColumnName}}",
            {{end -}}
        }
        {{lowerCamelCase .TableName}}ColumnMap=map[string]string{
            {{range $column := .Columns -}}
            "{{.ColumnName }}":"{{.ColumnName}}",
            {{end -}}
        }
    )
{{end}}
type {{upperCamelCase .TableName}}Repository interface {
    {{- if not .Readonly}}
    Create(entity {{upperCamelCase .TableName}}) ({{upperCamelCase .TableName}}, error)
    {{- end -}}
    {{- if not .Readonly}}
    CreateBySession(session *xorm.Session, entity {{upperCamelCase .TableName}}) ({{upperCamelCase .TableName}}, error)
    {{- end -}}
    {{- if not .Readonly}}
    DeleteById(id int64) (int64, error)
    {{- end -}}
    {{- if not .Readonly}}
    DeleteBySessionAndId(session *xorm.Session, id int64) (int64, error)
    {{- end -}}
    {{- if not .Readonly}}
    Update(entity {{upperCamelCase .TableName}}, columns []string) ({{upperCamelCase .TableName}}, error)
    {{- end -}}
    {{- if not .Readonly}}
    UpdateBySession(session *xorm.Session, entity {{upperCamelCase .TableName}}, columns []string) ({{upperCamelCase .TableName}}, error)
    {{- end}}
    FindById(id int64) ({{upperCamelCase .TableName}}, error)
    FindBySessionAndId(session *xorm.Session, id int64) ({{upperCamelCase .TableName}}, error)
}

type {{lowerCamelCase .TableName}}Repository  struct {
    engine *xorm.Engine
}

func New{{upperCamelCase .TableName}}Repository(engine *xorm.Engine) {{upperCamelCase .TableName}}Repository {
    return &{{lowerCamelCase .TableName}}Repository{
        engine: engine,
    }
}

{{if not .Readonly}}
func (r *{{lowerCamelCase .TableName}}Repository) Create(entity {{upperCamelCase .TableName}}) ({{upperCamelCase .TableName}}, error) {
    _, err := r.engine.Insert(&entity)

    return entity, err
}
{{end -}}

{{if not .Readonly}}
func (r *{{lowerCamelCase .TableName}}Repository) CreateBySession(session *xorm.Session, entity {{upperCamelCase .TableName}}) ({{upperCamelCase .TableName}}, error) {
    _, err := session.Insert(&entity)

    return entity, err
}
{{end -}}

{{if not .Readonly}}
func (r *{{lowerCamelCase .TableName}}Repository) DeleteById(id int64) (int64, error) {
    {{- if .HasDelStatus}}
    return r.engine.ID(id).Cols("del_status", "update_time").Update(&{{upperCamelCase .TableName}}{DelStatus: 1, UpdateTime: core.LocalDateTime(time.Now())})
    {{- else}}
    return r.engine.ID(id).Delete(&{{upperCamelCase .TableName}}{})
    {{- end}}
}
{{end -}}

{{if not .Readonly}}
func (r *{{lowerCamelCase .TableName}}Repository) DeleteBySessionAndId(session *xorm.Session, id int64) (int64, error) {
    {{- if .HasDelStatus}}
    return session.ID(id).Cols("del_status", "update_time").Update(&{{upperCamelCase .TableName}}{DelStatus: 1, UpdateTime: core.LocalDateTime(time.Now())})
    {{- else}}
    return session.ID(id).Delete(&{{upperCamelCase .TableName}}{})
    {{- end}}
}
{{end -}}

{{if not .Readonly}}
func (r *{{lowerCamelCase .TableName}}Repository) Update(entity {{upperCamelCase .TableName}},columns []string) ({{upperCamelCase .TableName}}, error) {
    _, err := r.engine.ID(entity.Id).Cols(columns...).Update(&entity)

    return entity, err
}
{{end -}}

{{if not .Readonly}}
func (r *{{lowerCamelCase .TableName}}Repository) UpdateBySession(session *xorm.Session, entity {{upperCamelCase .TableName}},columns []string) ({{upperCamelCase .TableName}}, error) {
    _, err := session.ID(entity.Id).Cols(columns...).Update(&entity)

    return entity, err
}
{{end}}

func (r *{{lowerCamelCase .TableName}}Repository) FindById(id int64) ({{upperCamelCase .TableName}}, error) {
    entity := new({{upperCamelCase .TableName}})

    _, err := r.engine.ID(id){{if .HasDelStatus}}.Where("del_status=0"){{end}}.Get(entity)

    return *entity, err
}

func (r *{{lowerCamelCase .TableName}}Repository) FindBySessionAndId(session *xorm.Session, id int64) ({{upperCamelCase .TableName}}, error) {
    entity := new({{upperCamelCase .TableName}})

    _, err := session.ID(id){{if .HasDelStatus}}.Where("del_status=0"){{end}}.Get(entity)

    return *entity, err
}

java/entity.tpl

package {{.PackageName}}.data.entity;

import java.io.Serializable;
{{- if .HasDecimalType}}
import java.math.BigDecimal;
{{- end -}}
{{if .HasDateType}}
import java.time.LocalDateTime;
{{- end}}

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "{{.TableName}}")
public class {{upperCamelCase .TableName}}Entity implements Serializable {
    private static final long serialVersionUID = 1L;

    {{- range $column := .Columns}}

    /*
     * {{.ColumnComment}}
     */
    {{if .IsPrimary -}}
    @Id
    {{- end -}}
    {{if .IsIdentity}}
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    {{- end -}}
    @Column(name = "{{.ColumnName}}")
    private {{.JavaType}} {{lowerCamelCase .ColumnName}};
    {{end}}

    {{- range $column := .Columns}}
    public {{.JavaType}} get{{upperCamelCase .ColumnName}}() {
        return {{lowerCamelCase .ColumnName}};
    }

    public void set{{upperCamelCase .ColumnName}}({{.JavaType}} {{lowerCamelCase .ColumnName}}) {
        this.{{lowerCamelCase .ColumnName}} = {{lowerCamelCase .ColumnName}};
    }
    {{end}}
}

java/model.tpl

package {{.PackageName}}.model;
{{if .HasDecimalType}}
import java.math.BigDecimal;
{{- end -}}
{{if .HasDateType}}
import java.time.LocalDateTime;
{{- end}}

@Entity
@Table(name = "{{.TableName}}")
public class {{upperCamelCase .TableName}} {

    {{- range $column := .Columns}}

    /*
     * {{.ColumnComment}}
     */
    private {{.JavaType}} {{lowerCamelCase .ColumnName}};
    {{- end}}

    {{range $column := .Columns}}
    public {{.JavaType}} get{{upperCamelCase .ColumnName}}() {
        return {{lowerCamelCase .ColumnName}};
    }

    public void set{{upperCamelCase .ColumnName}}({{.JavaType}} {{lowerCamelCase .ColumnName}}) {
        this.{{lowerCamelCase .ColumnName}} = {{lowerCamelCase .ColumnName}};
    }
    {{end}}
}

java/repository.tpl

package {{.PackageName}}.data.repository;

import java.time.LocalDateTime;
import java.util.Collection;
import java.util.List;
import java.util.Optional;

import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Slice;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;

import {{.PackageName}}.entity.{{upperCamelCase .TableName}}Entity;

public interface {{upperCamelCase .TableName}}EntityRepository
        extends JpaRepository<{{upperCamelCase .TableName}}Entity, {{.PrimaryColumnDataType}}>, JpaSpecificationExecutor<{{upperCamelCase .TableName}}Entity> {
    {{if .HasEnterpriseId}}
    @Query("select count(e.id) from #{#entityName} e where e.enterpriseId=0 or e.enterpriseId=:enterpriseId")   
    long countByEnterpriseId(@Param("enterpriseId")Long enterpriseId);

    @Query("select count(e.id) from #{#entityName} e where (e.enterpriseId=0 or e.enterpriseId=:enterpriseId) and e.updateTime>:updateTime")
    long countByEnterpriseIdAndUpdateTimeGreaterThan(@Param("enterpriseId")Long enterpriseId, @Param("updateTime")LocalDateTime updateTime);

    @Query("select e from #{#entityName} e where e.enterpriseId=0 or e.enterpriseId=:enterpriseId")
    List<{{upperCamelCase .TableName}}Entity> findByEnterpriseId(@Param("enterpriseId")Long enterpriseId);

    @Query("select e from #{#entityName} e where (e.enterpriseId=0 or e.enterpriseId=:enterpriseId) and e.id>:id")
    Slice<{{upperCamelCase .TableName}}Entity> findByEnterpriseIdAndIdGreaterThanOrderByIdAsc(@Param("enterpriseId")Long enterpriseId, @Param("id")Long id, Pageable pageable);

    @Query("select e from #{#entityName} e where (e.enterpriseId=0 or e.enterpriseId=:enterpriseId) and e.id>:id and e.updateTime>:updateTime")
    Slice<{{upperCamelCase .TableName}}Entity> findByEnterpriseIdAndIdGreaterThanAndUpdateTimeGreaterThanOrderByIdAsc(@Param("enterpriseId")Long enterpriseId,
            @Param("id")Long id, @Param("updateTime")LocalDateTime updateTime, Pageable pageable);

    long countByEnterpriseIdIn(Collection<Long> enterpriseIds);

    long countByEnterpriseIdInAndUpdateTimeGreaterThan(Collection<Long> enterpriseIds, LocalDateTime updateTime);

    List<{{upperCamelCase .TableName}}Entity> findByEnterpriseIdIn(Collection<Long> enterpriseIds);

    Slice<{{upperCamelCase .TableName}}Entity> findByEnterpriseIdInAndIdGreaterThanOrderByIdAsc(Collection<Long> enterpriseIds, Long id,
            Pageable pageable);

    Slice<{{upperCamelCase .TableName}}Entity> findByEnterpriseIdInAndIdGreaterThanAndUpdateTimeGreaterThanOrderByIdAsc(
            Collection<Long> enterpriseIds, Long id, LocalDateTime updateTime, Pageable pageable);
    {{if .HasCode}}
    
    boolean existsByEnterpriseIdAndCode(Long enterpriseId, String code);
    
    Optional<{{upperCamelCase .TableName}}Entity> findByEnterpriseIdAndCode(Long enterpriseId, String code);
    
    List<{{upperCamelCase .TableName}}Entity> findByEnterpriseIdAndCodeIn(Long enterpriseId, Collection<String> codes);
    
    List<{{upperCamelCase .TableName}}Entity> findByEnterpriseIdInAndCodeIn(Collection<Long> enterpriseIds, Collection<String> codes);
    {{if .HasDelStatus}}
    
    boolean existsByEnterpriseIdAndCodeAndDelStatus(Long enterpriseId, String code, Integer delStatus);
    
    Optional<{{upperCamelCase .TableName}}Entity> findByEnterpriseIdAndCodeAndDelStatus(Long enterpriseId, String code, Integer delStatus);
    
    List<{{upperCamelCase .TableName}}Entity> findByEnterpriseIdAndCodeInAndDelStatus(Long enterpriseId, Collection<String> codes, Integer delStatus);
    
    List<{{upperCamelCase .TableName}}Entity> findByEnterpriseIdInAndCodeInAndDelStatus(Collection<Long> enterpriseIds, Collection<String> codes, Integer delStatus);
    {{end}}
    {{- end -}}
    {{if .HasDelStatus}}
    @Query("select e from #{#entityName} e where e.delStatus=0")
    List<{{upperCamelCase .TableName}}Entity> findAvailable();
    
    @Query("select e from #{#entityName} e where e.id=:id and e.delStatus=0")
    Optional<{{upperCamelCase .TableName}}Entity> findAvailableById(@Param("id") Long id);
    
    @Query("select e from #{#entityName} e where e.id in (:ids) and e.delStatus=0")
    List<{{upperCamelCase .TableName}}Entity> findAvailableByIdIn(@Param("ids") Collection<Long> ids);
    
    @Query("select e from #{#entityName} e where (e.enterpriseId=0 or e.enterpriseId=:enterpriseId) and e.delStatus=0")
    List<{{upperCamelCase .TableName}}Entity> findAvailableByEnterpriseId(@Param("enterpriseId") Long enterpriseId);

    @Query("select e from #{#entityName} e where e.enterpriseId in (:enterpriseIds) and e.delStatus=0")
    List<{{upperCamelCase .TableName}}Entity> findAvailableByEnterpriseIdIn(@Param("enterpriseIds") Collection<Long> enterpriseIds);
    {{end -}}
    {{if .HasStatus}}
    @Modifying
    {{- if .HasDelStatus}}
    @Query("update #{#entityName} e set e.status=:status,e.updateTime=:updateTime where e.enterpriseId=:enterpriseId and e.delStatus=0")
    {{else -}}
    @Query("update #{#entityName} e set e.status=:status,e.updateTime=:updateTime where e.enterpriseId=:enterpriseId")
    {{- end -}}
    int updateStatusByEnterpriseId(@Param("enterpriseId") Long enterpriseId, @Param("status") Integer status,
            @Param("updateTime") LocalDateTime updateTime);

    @Modifying
    {{- if .HasDelStatus}}
    @Query("update #{#entityName} e set e.status=:status,e.updateTime=:updateTime where e.enterpriseId in (:enterpriseIds) and e.delStatus=0")
    {{else -}}
    @Query("update #{#entityName} e set e.status=:status,e.updateTime=:updateTime where e.enterpriseId in (:enterpriseIds)")
    {{- end -}}
    int updateStatusByEnterpriseIdIn(@Param("enterpriseIds") Collection<Long> enterpriseIds,
            @Param("status") Integer status, @Param("updateTime") LocalDateTime updateTime);

    @Modifying
    {{- if .HasDelStatus}}
    @Query("update #{#entityName} e set e.status=:status,e.updateTime=:updateTime where e.enterpriseId=:enterpriseId and e.id in (:ids) and e.delStatus=0")
    {{else -}}
    @Query("update #{#entityName} e set e.status=:status,e.updateTime=:updateTime where e.enterpriseId=:enterpriseId and e.id in (:ids)")
    {{- end -}}
    int updateStatusByEnterpriseIdAndIdIn(@Param("enterpriseId") Long enterpriseId, @Param("ids") Collection<Long> ids,
            @Param("status") Integer status, @Param("updateTime") LocalDateTime updateTime);

    @Modifying
    {{- if .HasDelStatus}}
    @Query("update #{#entityName} e set e.status=:status,e.updateTime=:updateTime where e.id in (:ids) and e.delStatus=0")
    {{else -}}
    @Query("update #{#entityName} e set e.status=:status,e.updateTime=:updateTime where e.id in (:ids)")
    {{- end -}}
    int updateStatusByIdIn(@Param("ids") Collection<Long> ids, @Param("status") Integer status,
            @Param("updateTime") LocalDateTime updateTime);
    {{end}}
    {{- if .HasDelStatus}}
    @Modifying
    @Query("update #{#entityName} e set e.delStatus=:delStatus,e.updateTime=:updateTime where e.enterpriseId=:enterpriseId and e.id=:id")
    int updateDelStatusByEnterpriseIdAndId(@Param("enterpriseId") Long enterpriseId,
            @Param("id") Long id, @Param("delStatus") Integer delStatus,
            @Param("updateTime") LocalDateTime updateTime);
    
    @Modifying      
    @Query("update #{#entityName} e set e.delStatus=:delStatus,e.updateTime=:updateTime where e.enterpriseId=:enterpriseId and e.id in (:ids)")
    int updateDelStatusByEnterpriseIdAndIdIn(@Param("enterpriseId") Long enterpriseId,
            @Param("ids") Collection<Long> ids, @Param("delStatus") Integer delStatus,
            @Param("updateTime") LocalDateTime updateTime);
            
    @Modifying
    @Query("update #{#entityName} e set e.delStatus=:delStatus,e.updateTime=:updateTime where e.id=:id")
    int updateDelStatusById(@Param("id") Long id, @Param("delStatus") Integer delStatus,
            @Param("updateTime") LocalDateTime updateTime);

    @Modifying
    @Query("update #{#entityName} e set e.delStatus=:delStatus,e.updateTime=:updateTime where e.id in (:ids)")
    int updateDelStatusByIdIn(@Param("ids") Collection<Long> ids, @Param("delStatus") Integer delStatus,
            @Param("updateTime") LocalDateTime updateTime);
    {{end}}
    {{- end}}
}

有疑问加站长微信联系(非本文作者)

本文来自:简书

感谢作者:EasyNetCN

查看原文:golang xorm mysql代码生成器(java,go)

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

408 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传