1 /*
2 * Copyright 2018-2020 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.util;
17
18 import java.util.Optional;
19
20 import org.hibernate.proxy.HibernateProxy;
21 import org.springframework.data.util.ProxyUtils.ProxyDetector;
22 import org.springframework.lang.Nullable;
23 import org.springframework.util.ClassUtils;
24
25 /**
26 * {@link ProxyDetector} to explicitly check for Hibernate's {@link HibernateProxy}.
27 *
28 * @author Oliver Gierke
29 */
30 class HibernateProxyDetector implements ProxyDetector {
31
32 private static final Optional<Class<?>> HIBERNATE_PROXY = Optional.ofNullable(loadHibernateProxyType());
33
34 /*
35 * (non-Javadoc)
36 * @see org.springframework.data.util.ProxyUtils.ProxyDetector#getUserType(java.lang.Class)
37 */
38 @Override
39 public Class<?> getUserType(Class<?> type) {
40
41 return HIBERNATE_PROXY //
42 .map(it -> it.isAssignableFrom(type) ? type.getSuperclass() : type) //
43 .filter(it -> !Object.class.equals(it)) //
44 .orElse(type);
45 }
46
47 @Nullable
48 private static Class<?> loadHibernateProxyType() {
49
50 try {
51 return ClassUtils.forName("org.hibernate.proxy.HibernateProxy", HibernateProxyDetector.class.getClassLoader());
52 } catch (ClassNotFoundException o_O) {
53 return null;
54 }
55 }
56 }
57