How to implement the simplest alien in a REST webservice?

后端 未结 2 796
梦谈多话
梦谈多话 2020-12-18 03:00

I need a JSON endpoint that return data directally from a stored procedure. Example:

@Procedure(\"complex\"         


        
2条回答
  •  被撕碎了的回忆
    2020-12-18 03:44

    Im not really sure if I understand your question well but this is my solution.

    I created a simple procedure on a oracle DB:

    PROCEDURE TESTPROCOUTPUT
       (param2 OUT VARCHAR2)
       IS
       GETPARAM VARCHAR2(100);
    BEGIN
        param2 := 'procedure Called';
    END TESTPROCOUTPUT;
    

    To use @Procedure in the Spring environment you will need an Entity and a Repository. So I created a simple Entity and it's Repository:

    @Entity
    public class City {
    
        @Id
        private String cityCode;
    
        //...getter/setter
    }
    

    Repository:

    public interface LandRepository extends CrudRepository {
    
        @Procedure(name="TESTPROCOUTPUT", outputParameterName="param2")
        String TESTPROCOUTPUT();
    }
    

    It is important that the method name has the same name like the procedure has. (Not sure if its just for oracle the case. And could also be in camelCase I think)

    So in your controller you can now easily autowire the repository (or if you have an implementation of the interface use this).

    @Controller
    public class CityController {
    
        private CityRepository cityRepository;
    
        @RequestMapping(value="/howto", method=RequestMethod.GET)
        @ResponseStatus(HttpStatus.OK)
        @ResponseBody
        public String howto() { 
            String s = cityRepository.TESTPROCOUTPUT();
            return "{\"result\":" + s + "}";
        }
    
        public CityRepository getCityRepository () {
            return cityRepository;
        }
    
        @Autowired
        public void setCityRepository (CityRepository cityRepository) {
            this.cityRepository= cityRepository;
        }
    }
    

    And the result is:

    So you are not able to use @Procedure annotation on non repository methods.

    Annotation to declare JPA 2.1 stored procedure mappings directly on repository methods.

提交回复
热议问题