7

I want to call a database function from spring boot application which will return a decrypted value.

Is it possible to call database functions using spring data jpa? If possible how?

If not possible using spring data jpa, Is there any alternatives to call functions from spring boot?

Here is my function

IF OBJECT_ID('fn_MASK_CARD') IS NOT NULL
    DROP FUNCTION fn_MASK_CARD
GO

CREATE FUNCTION fn_MASK_CARD (
    @CARD_NUMBER  VARCHAR(19)
    )
   RETURNS VARCHAR(19)
AS
BEGIN
    RETURN SUBSTRING(@CARD_NUMBER,1,6)+REPLICATE('#',LEN(@CARD_NUMBER)-10)+
                                                        SUBSTRING(@CARD_NUMBER,LEN(@CARD_NUMBER)-3,LEN(@CARD_NUMBER));
END
GO
8
  • Hi and welcome, please read how to ask a question here (stackoverflow.com/help/how-to-ask) , then edit your question accordingly. Commented Sep 5, 2018 at 9:53
  • You could just simply use @Query for that Commented Sep 5, 2018 at 9:59
  • Look up JPA custom queries. It is very possible yes. Commented Sep 5, 2018 at 10:00
  • Thank you @benjaminc . Can u provide me any examples for the same? Commented Sep 5, 2018 at 10:01
  • @benjaminc I want to call the above function using spring data jpa? Since i don't have any entity related to that function how can i create an interface extending jpaRepository Commented Sep 5, 2018 at 10:06

4 Answers 4

15

Finally found the answer, just added the below code in my repository and it worked!

@Query(nativeQuery = true, value = "SELECT DBO.fn_MASK_CARD(:text)")
String callMaskCard(@Param("text") String text);
Sign up to request clarification or add additional context in comments.

1 Comment

for me this worked @Query(nativeQuery = true, value = "SELECT CAST(gen_random_uuid as varchar) from gen_random_uuid") I had to cast the output otherwise it was throwing an error.
1

It worked for me. Try adding the below code into your repository.

@Query(nativeQuery = true, value = "SELECT fn_MASK_CARD(:card_num) FROM DUAL")
String maskCard(@Param("card_num") String card_num);

Comments

1

nativeQuery = true it is a precondition in Spring JPA to call the database functions.

@Query(value = "SELECT your_function()", nativeQuery = true)

GL

Comments

0

you call DB function from a DAO as

{? = call <package_name>.<>Function_Name(<parameter >)}

eg

{? = call mypackage.myfunction(?)}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.