Skip to content

Commit cfbcf00

Browse files
committed
Handle nulls in stored procedure parameters properly.
Hibernate 6.1 properly handles TypeParameterValue for general parameters, but not for temporal ones. So we must dereference in those scenarios. Related: #2544, hibernate/hibernate-orm#5438
1 parent 6a4209b commit cfbcf00

File tree

3 files changed

+225
-8
lines changed

3 files changed

+225
-8
lines changed

spring-data-jpa/src/main/java/org/springframework/data/jpa/repository/query/QueryParameterSetter.java

+18-8
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,12 @@
1515
*/
1616
package org.springframework.data.jpa.repository.query;
1717

18-
import static org.springframework.data.jpa.repository.query.QueryParameterSetter.ErrorHandling.*;
18+
import static org.springframework.data.jpa.repository.query.QueryParameterSetter.ErrorHandling.LENIENT;
19+
20+
import jakarta.persistence.Parameter;
21+
import jakarta.persistence.Query;
22+
import jakarta.persistence.TemporalType;
23+
import jakarta.persistence.criteria.ParameterExpression;
1924

2025
import java.lang.reflect.Proxy;
2126
import java.util.Collections;
@@ -25,13 +30,9 @@
2530
import java.util.Set;
2631
import java.util.function.Function;
2732

28-
import jakarta.persistence.Parameter;
29-
import jakarta.persistence.Query;
30-
import jakarta.persistence.TemporalType;
31-
import jakarta.persistence.criteria.ParameterExpression;
32-
3333
import org.apache.commons.logging.Log;
3434
import org.apache.commons.logging.LogFactory;
35+
import org.hibernate.query.TypedParameterValue;
3536
import org.springframework.lang.Nullable;
3637
import org.springframework.util.Assert;
3738

@@ -79,10 +80,17 @@ class NamedOrIndexedQueryParameterSetter implements QueryParameterSetter {
7980
public void setParameter(BindableQuery query, JpaParametersParameterAccessor accessor,
8081
ErrorHandling errorHandling) {
8182

82-
Object value = valueExtractor.apply(accessor);
83-
8483
if (temporalType != null) {
8584

85+
Object extractedValue = valueExtractor.apply(accessor);
86+
87+
final Object value;
88+
if (extractedValue instanceof TypedParameterValue<?>) {
89+
value = ((TypedParameterValue<?>) extractedValue).getValue();
90+
} else {
91+
value = extractedValue;
92+
}
93+
8694
// One would think we can simply use parameter to identify the parameter we want to set.
8795
// But that does not work with list valued parameters. At least Hibernate tries to bind them by name.
8896
// TODO: move to using setParameter(Parameter, value) when https://hibernate.atlassian.net/browse/HHH-11870 is
@@ -107,6 +115,8 @@ public void setParameter(BindableQuery query, JpaParametersParameterAccessor acc
107115

108116
} else {
109117

118+
final Object value = valueExtractor.apply(accessor);
119+
110120
if (parameter instanceof ParameterExpression) {
111121
errorHandling.execute(() -> query.setParameter((Parameter<Object>) parameter, value));
112122
} else if (query.hasNamedParameters() && parameter.getName() != null) {
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,166 @@
1+
/*
2+
* Copyright 2015-2022 the original author or authors.
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* https://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
package org.springframework.data.jpa.repository.procedures;
17+
18+
import jakarta.persistence.Entity;
19+
import jakarta.persistence.EntityManagerFactory;
20+
import jakarta.persistence.GeneratedValue;
21+
import jakarta.persistence.GenerationType;
22+
import jakarta.persistence.Id;
23+
import lombok.AccessLevel;
24+
import lombok.AllArgsConstructor;
25+
import lombok.Data;
26+
import lombok.NoArgsConstructor;
27+
28+
import java.util.Date;
29+
import java.util.Properties;
30+
import java.util.UUID;
31+
32+
import javax.sql.DataSource;
33+
34+
import org.hibernate.dialect.PostgreSQL91Dialect;
35+
import org.junit.jupiter.api.Test;
36+
import org.junit.jupiter.api.extension.ExtendWith;
37+
import org.postgresql.ds.PGSimpleDataSource;
38+
import org.springframework.beans.factory.annotation.Autowired;
39+
import org.springframework.context.annotation.Bean;
40+
import org.springframework.context.annotation.ComponentScan;
41+
import org.springframework.context.annotation.FilterType;
42+
import org.springframework.core.io.ClassPathResource;
43+
import org.springframework.data.jpa.repository.JpaRepository;
44+
import org.springframework.data.jpa.repository.Temporal;
45+
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
46+
import org.springframework.data.jpa.repository.query.Procedure;
47+
import org.springframework.jdbc.datasource.init.DataSourceInitializer;
48+
import org.springframework.jdbc.datasource.init.ResourceDatabasePopulator;
49+
import org.springframework.orm.jpa.AbstractEntityManagerFactoryBean;
50+
import org.springframework.orm.jpa.JpaTransactionManager;
51+
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
52+
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
53+
import org.springframework.test.context.ContextConfiguration;
54+
import org.springframework.test.context.junit.jupiter.SpringExtension;
55+
import org.springframework.transaction.PlatformTransactionManager;
56+
import org.springframework.transaction.annotation.EnableTransactionManagement;
57+
import org.springframework.transaction.annotation.Transactional;
58+
import org.testcontainers.containers.PostgreSQLContainer;
59+
60+
/**
61+
* Testcase to verify {@link org.springframework.jdbc.object.StoredProcedure}s properly handle null values.
62+
*
63+
* @author Greg Turnquist
64+
*/
65+
@Transactional
66+
@ExtendWith(SpringExtension.class)
67+
@ContextConfiguration(classes = PostgresStoredProcedureNullHandlingIntegrationTests.Config.class)
68+
public class PostgresStoredProcedureNullHandlingIntegrationTests {
69+
70+
@Autowired TestModelRepository repository;
71+
72+
@Test // 2544
73+
void invokingNullOnNonTemporalStoredProcedureParameterShouldWork() {
74+
repository.countUuid(null);
75+
}
76+
77+
@Test // 2544
78+
void invokingNullOnTemporalStoredProcedureParameterShouldWork() {
79+
repository.countLocalDate(null);
80+
}
81+
82+
@Data
83+
@AllArgsConstructor
84+
@NoArgsConstructor(access = AccessLevel.PROTECTED)
85+
@Entity
86+
public class TestModel {
87+
88+
@Id
89+
@GeneratedValue(strategy = GenerationType.AUTO) private long id;
90+
private UUID uuid;
91+
private Date date;
92+
}
93+
94+
@Transactional
95+
public interface TestModelRepository extends JpaRepository<TestModel, Long> {
96+
97+
@Procedure("countByUuid")
98+
void countUuid(UUID this_uuid);
99+
100+
@Procedure("countByLocalDate")
101+
void countLocalDate(@Temporal Date localDate);
102+
}
103+
104+
@EnableJpaRepositories(considerNestedRepositories = true,
105+
includeFilters = @ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = TestModelRepository.class))
106+
@EnableTransactionManagement
107+
static class Config {
108+
109+
@Bean(initMethod = "start", destroyMethod = "stop")
110+
public PostgreSQLContainer<?> container() {
111+
112+
return new PostgreSQLContainer<>("postgres:9.6.12") //
113+
.withUsername("postgres");
114+
}
115+
116+
@Bean
117+
public DataSource dataSource(PostgreSQLContainer<?> container) {
118+
119+
PGSimpleDataSource dataSource = new PGSimpleDataSource();
120+
dataSource.setUrl(container.getJdbcUrl());
121+
dataSource.setUser(container.getUsername());
122+
dataSource.setPassword(container.getPassword());
123+
124+
return dataSource;
125+
}
126+
127+
@Bean
128+
public AbstractEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) {
129+
130+
LocalContainerEntityManagerFactoryBean factoryBean = new LocalContainerEntityManagerFactoryBean();
131+
factoryBean.setDataSource(dataSource);
132+
factoryBean.setPersistenceUnitRootLocation("simple-persistence");
133+
factoryBean.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
134+
factoryBean.setPackagesToScan(this.getClass().getPackage().getName());
135+
136+
Properties properties = new Properties();
137+
properties.setProperty("hibernate.hbm2ddl.auto", "create");
138+
properties.setProperty("hibernate.dialect", PostgreSQL91Dialect.class.getCanonicalName());
139+
properties.setProperty("hibernate.proc.param_null_passing", "true");
140+
properties.setProperty("hibernate.globally_quoted_identifiers", "true");
141+
properties.setProperty("hibernate.globally_quoted_identifiers_skip_column_definitions", "true");
142+
factoryBean.setJpaProperties(properties);
143+
144+
return factoryBean;
145+
}
146+
147+
@Bean
148+
PlatformTransactionManager transactionManager(EntityManagerFactory entityManagerFactory) {
149+
return new JpaTransactionManager(entityManagerFactory);
150+
}
151+
152+
@Bean
153+
DataSourceInitializer initializer(DataSource dataSource) {
154+
155+
DataSourceInitializer initializer = new DataSourceInitializer();
156+
initializer.setDataSource(dataSource);
157+
158+
ClassPathResource script = new ClassPathResource("scripts/postgres-nullable-stored-procedures.sql");
159+
ResourceDatabasePopulator populator = new ResourceDatabasePopulator(script);
160+
populator.setSeparator(";;");
161+
initializer.setDatabasePopulator(populator);
162+
163+
return initializer;
164+
}
165+
}
166+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
CREATE TABLE test_model
2+
(
3+
ID numeric NOT NULL,
4+
uuid UUID,
5+
local_date DATE,
6+
CONSTRAINT test_model_pk PRIMARY KEY (ID)
7+
);;
8+
9+
CREATE OR REPLACE FUNCTION countByUuid(this_uuid uuid)
10+
RETURNS int
11+
LANGUAGE 'plpgsql'
12+
AS
13+
$BODY$
14+
DECLARE
15+
c integer;
16+
BEGIN
17+
SELECT count(*)
18+
INTO c
19+
FROM test_model
20+
WHERE test_model.uuid = this_uuid;
21+
RETURN c;
22+
END;
23+
$BODY$
24+
;;
25+
26+
CREATE OR REPLACE FUNCTION countByLocalDate(this_local_date DATE)
27+
RETURNS int
28+
LANGUAGE 'plpgsql'
29+
AS
30+
$BODY$
31+
DECLARE
32+
c integer;
33+
BEGIN
34+
SELECT count(*)
35+
INTO c
36+
FROM test_model
37+
WHERE test_model.local_date = this_local_date;
38+
RETURN c;
39+
END;
40+
$BODY$
41+
;;

0 commit comments

Comments
 (0)