Home > Software design >  Named Query with map values in Spring Data JPA
Named Query with map values in Spring Data JPA

Time:08-09

i have a hashmap like which has key value pair such as :

testMap = new HashMap(){{
                        put(iD, sID);
                        put(lEVEL, sLevel);
                        put(tYPE, sType);
                        put(vALUE, sValue);

Now i have my entity Class which has fields like

@Column(name = "ID")
private String id;

@Column(name = "LEVEL")
private String level;

 
@Column(name = "PROGRAM")
private String program;

   
@Column(name = "TYPE")
private String type;

  
@Column(name = "VALUE")
private String value;

@Column(name = "STARTDATE")
private Date start;

Now i need to form a named query where for each column i have to set values by extracting them from map key value pair (something like this :tesMap.get(iD) and setting in ID column) and also comparing the start date with the current date and setting the largest date in startdate column . Tried the following using Named query but didn't work .

@Query(value = "SELECT * FROM OVERRIDES s "  
            "WHERE s.ID =?1 AND s.LEVEL=?2 AND s.TYPE=?3 AND s.VALUE=?4", nativeQuery = true)

Also ,unable to decide how to compare dates in this select query .

CodePudding user response:

Comparing the dates can be easily done with Date.after() method.

E.g.

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date1 = sdf.parse("2022-07-01");
Date date2 = sdf.parse("2022-08-31");

if(date1.after(date2)) {
    //set largest date in date column
}

As for the rest question, please provide the whole Entity, or maybe more infos about the query

CodePudding user response:

In SQL, you can compare dates/timestamps with relational operators >, <, >=, <= i.e.

@Query(value = "SELECT * FROM OVERRIDES s "  
        "WHERE s.ID =?1 AND s.LEVEL=?2 AND s.TYPE=?3 AND s.VALUE>=?4", nativeQuery = true)
  • Related