0

I have the following DTO:

@Data @NoArgsConstructor @AllArgsConstructor public class EmployeeHierarchyDto { private Integer id; private Integer supervisorId; private Integer level; private String branch; private Integer position; } 

And then later I have this native query:

 public List<EmployeeDto> getAllSubordinateSubordinates(Integer employeeId) { if (employeeId == null) { employeeId = getCeo().getId(); } EntityManager em = getEntityManager(); String sqlString = "select t.id, " + "t.supervisor_id, " + "t.level, " + "t.branch, " + "t.pos " + "FROM connectby('public.employee'::text, 'id'::text, 'supervisor_id'::text, 'last_name'::text, " + "'" + employeeId + "'::text, 0, '~'::text) t(id int, supervisor_id int, level integer, branch text, pos integer);"; Query q = em.createNativeQuery(sqlString); List hierarchyList = q.getResultList(); List<EmployeeDto> employeeDtoList = new ArrayList<>(); return employeeDtoList; } 

When I debug the code and copy the sql string generated into a db console, this is what I get if for instance the frontend passed the id of 93:

select t.id, t.supervisor_id, t.level, t.branch, t.pos FROM connectby('public.employee'::text, 'id'::text, 'supervisor_id'::text, 'last_name'::text, '93'::text, 0, '~'::text) t(id int, supervisor_id int, level integer, branch text, pos integer); 

The above query executes 100% correct in the db console.

EDIT: The exact error is:

11:39:50,711 WARN [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (default task-3) SQL Error: 0, SQLState: 42601 11:39:50,714 ERROR [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (default task-3) ERROR: syntax error at or near ":" Position: 88 

The 42601 points to a PostgreSQL syntax error, however if the string that will become the native query is copied from the debugger and pasted into a db console it works without problem.

Why would this be? And secondly, how can I map the result set to a list of EmployeeHierarchyDto's

2
  • 1
    I get a weird error. Should we guess it? Commented May 6, 2020 at 9:40
  • @NikolaiShevchenko Sorry friend, no need to guess. I updated the question. Commented May 6, 2020 at 9:43

1 Answer 1

1

It seems releated to the syntax used by postgres' cast operator. That’s because of the :: type cast operator conflicts with the JPA : named parameter syntax.

There are a bunch of workaround to that, see cast-operator-issue-with-jpa

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, escaping the :: symbols with \\:\\: worked perfectly!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.