SCENARIO: I have a MySQL Database where I have one Table with a Mapping of a user and a product. My Application offers an api so I have to be aware that the mapping will not be done multiple times. Therefor I want to check if the two ids( of the user and the product) are already mapped.
PROBLEM:
I have a query from here where I expect a boolean value that shows me if an entry already exists.
@Query(value ="SELECT case when count(id) > 0 then true else false end FROM user_product_matching WHERE user_id=:userId AND product_id=:productId", nativeQuery = true) Boolean productAlreadyAdded(@Param("userId") Long userId,@Param("productId") Long productId);
The error I get is:
java.math.BigInteger cannot be cast to java.lang.Boolean
Although I can’t run this right now my goal is to write ONE natve query in spring
where I can the result of this query to execute an if else case scenario where a can execute the insert or skip.
Is this possible and how do I have to write the query?
EDIT: I forgot to mention that thhis has to work also from docker containers where the databases and table are not created by spring. So I guess stored procedures would be a better way to go?
Advertisement
Answer
Aperently this question was discussed in this thread too. Depending on the wanted behavior you could use something like
INSERT IGNORE INTO table