简体   繁体   中英

If Postgres sql query returns json, so how can access it in spring boot?

one db guy written following query on PostgreSQL. It's returning this json:

[{"id":8,"totalDays":429,"daysRemaining":-257,"absent":[3,3,2,3,3,3,3,3,3,3,3,3],"present":[0,0,1,0,0,0,0,0,0,0,0,0],"courseBatch":"java"}]

i need to create a model class with these id's and insert this json values to that model class, plz can somebody help... if it returns result set i can handle, but its returning json, so plz gimme a proper code to overcome friends and members. thanks in advance

Query:

@Query(value = "WITH coursedetails AS(
SELECT 
        csb.CourseId,
        csb.batchid,
        csb.startdate ,
        csb.EndDate,
        gs AS Month,
        uc.coursename
    FROM CourseScheduledBatches csb  
    cross join generate_series(1,12,1)gs
    JOIN UserCourses uc on 
        uc.courseid = csb.courseid
        AND uc.userid = 54 AND uc.coursename='java'
),
finaldata AS(
    SELECT 
        cd.CourseId,
        cd.EndDate::date - cd.StartDate::date AS totaldays,
        cd.EndDate::date - CURRENT_DATE AS daysRemaining,
        cd.Month,
        count(DISTINCT ca.TraineeId) AS TraineesPresent,
        count(DISTINCT tc.TraineeId) AS totalTrainees,
        cd.coursename
    FROM coursedetails cd 
    LEFT JOIN CourseAttendence ca on 
        ca.courseid = cd.courseid
        AND ca.batchid = cd.batchid
        AND cd.Month = extract(MONTH FROM ca.StartDate)
    LEFT JOIN TraineeCourses tc ON 
        tc.courseid = cd.courseid
        AND tc.batchid = cd.batchid
    GROUP BY 1, 2, 3, 4, 7
    ORDER BY 4
)
SELECT json_agg(row_to_json(q.*))
FROM(
    SELECT 
        courseid AS "id",
        totaldays AS "totalDays",
        daysRemaining AS "daysRemaining",
        ARRAY_AGG(totalTrainees - TraineesPresent) AS "absent",
        ARRAY_AGG(TraineesPresent) AS "present",
        coursename AS "courseBatch"
    FROM finaldata        
    group by 1, 2, 3, 6
)q;",nativeQuery = true)
    List<Object> getAttendanceAvgBasedOnUserIdAndRolename(BigInteger userId, String batchName);

You could do:

Gson gson = new Gson(); 
MyType target2 = gson.fromJson(json, MyType.class);

Write the class to have attributes that matches to the json string. Use arrays to absent and present

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM