通过id查询用户,但是只返回指定的字段

本文详细介绍了如何利用Hibernate和SpringMVC框架,通过数据库ID查询用户并仅返回指定字段的方法。包括两种实现方式:拼接HQL和使用投影。适用于场景中只需获取特定字段的情况,避免了不必要的资源消耗。

使用hibernate和spring MVC
通过id查询到一个用户,但是只返回指定的字段
方式一: 拼接hql

/***
     * 通过数据库ID查询用户,但是只返回指定的字段
     * @param id
     * @param propertyNames : 指定的多个成员变量
     * @return
     */
    public Object[] getPropertiesById(int id,String[] propertyNames){
        if(ValueWidget.isNullOrEmpty(propertyNames)){
            return null;
        }
        String hql="select "+propertyNames[0];
        for (int i = 1; i < propertyNames.length; i++) {
            String string = propertyNames[i];
            hql+=","+string;
        }
        String parameterId="id22";
        hql+=" from "+clz.getCanonicalName()+" c where c.id=:"+parameterId;

        Query q= this.sessionFactory.getCurrentSession().createQuery(hql);
        Object result=q.setInteger(parameterId, id).uniqueResult();
        Object[]objs=null;
        if(result instanceof Object[]){
            objs=(Object[])result;
        }else{//当只返回一个成员变量的时候
            objs=new Object[]{result};
        }
        return objs;
    }

 /***
     * 通过id,查询到一条记录,但是只返回指定的两个字段
     * @param id
     * @param propertyName1 : 类的成员变量
     * @param propertyName2 : 类的成员变量
     * @return
     */
    public Object[] getPropertiesById(int id,String propertyName1,String propertyName2){
        String hql="select "+propertyName1;
        if(!ValueWidget.isNullOrEmpty(propertyName2)){
            hql+=","+propertyName2;
        }
        String parameterId="id22";
        hql+=" from "+clz.getCanonicalName()+" c where c.id=:"+parameterId;

        Query q= this.sessionFactory.getCurrentSession().createQuery(hql);
        Object result=q.setInteger(parameterId, id).uniqueResult();
        Object[]objs=null;
        if(result instanceof Object[]){
            objs=(Object[])result;
        }else{//当只返回一个成员变量的时候
            objs=new Object[]{result};
        }
        return objs;

    }

方式二:使用投影

/***
     * 通过数据库ID查询用户,但是只返回指定的字段
     * @param id
     * @param propertyNames : 指定的多个成员变量
     * @return
     */
    public Object[] getPropertiesById2(int id,String[] propertyNames){
        Criteria c=this.sessionFactory.getCurrentSession().createCriteria(clz);
        ProjectionList projectionList=Projections.projectionList();
        if(!ValueWidget.isNullOrEmpty(propertyNames)){
            for (int i = 0; i < propertyNames.length; i++) {
                String string = propertyNames[i];
                projectionList.add(Projections.property(string));
            }
        }
        Object result=c.add(Restrictions.idEq(id)).setProjection(projectionList).uniqueResult();
        Object[]objs=null;
        if(result instanceof Object[]){
            objs=(Object[])result;
        }else{//当只返回一个成员变量的时候
            objs=new Object[]{result};
        }
        return objs;

    }
/***
     * 通过id,查询到一条记录,但是只返回指定的两个字段
     * @param id
     * @param propertyName1 : 类的成员变量
     * @param propertyName2 : 类的成员变量
     * @return
     */
    public Object[] getPropertiesById2(int id,String propertyName1,String propertyName2){
        Criteria c=this.sessionFactory.getCurrentSession().createCriteria(clz);
        ProjectionList projectionList=Projections.projectionList()
                .add(Projections.property(propertyName1));
        if(!ValueWidget.isNullOrEmpty(propertyName2)){
            projectionList.add(Projections.property(propertyName2));
        }
        Object result=c.add(Restrictions.idEq(id)).setProjection(projectionList).uniqueResult();
        Object[]objs=null;
        if(result instanceof Object[]){
            objs=(Object[])result;
        }else{//当只返回一个成员变量的时候
            objs=new Object[]{result};
        }
        return objs;

    }

使用场景:知道id,但是没必要获取整条记录,只需要获取其中的两三个字段而已.

### 查询当天插入记录的实现 在 Go 语言中,可以通过 GORM 框架结合 `oper_ip` 字段查询某 IP 地址在当天插入的记录。为了实现“查询当天插入记录”的功能,需要在查询时对时间进行范围限定,通常包括当天的 00:00:00 到 23:59:59。 以下是基于 `TContact` 模型的完整实现示例: ```go package main import ( "time" "gorm.io/gorm" ) // TContact 是数据库模型,包含 oper_ip 字段用于记录操作IP type TContact struct { ID uint `gorm:"primaryKey"` Name string Email string OperIp string `gorm:"column:oper_ip"` // 操作IP字段 CreatedAt time.Time // GORM 默认的创建时间字段 UpdatedAt time.Time DeletedAt gorm.DeletedAt `gorm:"index"` } // GetRecordsByIpAndToday 通过 oper_ip 查询当天的插入记录 func GetRecordsByIpAndToday(db *gorm.DB, ip string) ([]TContact, error) { var contacts []TContact // 获取当前时间并计算当天的起始和结束时间 now := time.Now() startOfDay := time.Date(now.Year(), now.Month(), now.Day(), 0, 0, 0, 0, now.Location()) endOfDay := startOfDay.AddDate(0, 0, 1).Add(-time.Nanosecond) // 构建查询条件:oper_ip = ? AND created_at BETWEEN startOfDay AND endOfDay err := db.Where("oper_ip = ? AND created_at BETWEEN ? AND ?", ip, startOfDay, endOfDay).Find(&contacts).Error if err != nil { return nil, err } return contacts, nil } ``` ### 查询逻辑说明 1. **获取当前时间**:使用 `time.Now()` 获取当前时间,并基于当前日期构造当天的起始时间和结束时间。 2. **时间范围构造**:通过 `time.Date` 构造当天的起始时间(00:00:00),并通过 `AddDate` 构造次日的 00:00:00 时间,再减去 1 纳秒以获得当天的结束时间(23:59:59)。 3. **数据库查询**:使用 GORM 的 `Where` 方法,查询 `oper_ip` 等于指定 IP 且 `created_at` 在当天时间范围内的记录。 4. **返回结果**:将符合条件的记录存入 `contacts` 切片并返回。 ### 使用示例 ```go func main() { // 假设已经建立数据库连接 dsn := "root:123456@tcp(127.0.0.1:3306)/database_name?charset=utf8mb4&parseTime=True&loc=Local" db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{}) if err != nil { panic(err) } // 查询 IP 为 "192.168.1.1" 的当天记录 records, err := GetRecordsByIpAndToday(db, "192.168.1.1") if err != nil { panic(err) } // 打印结果 for _, record := range records { println("Name:", record.Name) println("Email:", record.Email) println("OperIp:", record.OperIp) } } ``` ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值