/*
* Copyright 2002-2007 the original author or authors.
*
* Licensed under the Apache license, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.internna.iwebmvc.utils;
import static org.springframework.util.StringUtils.hasText;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import javax.persistence.OneToMany;
import org.springframework.beans.BeanUtils;
/**
* Utility methods for working with JPa entities.
*
* @author Jose Noheda
* @since 1.0
*/
public final class JPAUtils extends org.springframework.util.ClassUtils {
/**
* Default private constructor for a Utility class.
*/
private JPAUtils() {
throw new AssertionError("Do not try to instantiate utility class");
}
/**
* Reads the collection property information available in the primary class
* trying to detect the matching field in the target class.
*/
public static Method getReverseSetter(Class<?> primary, Class<?> target, String property) {
Assert.notNull(target);
Assert.notNull(primary);
Assert.hasText(property);
Method reverseSetter = null;
Field collection = ClassUtils.getField(primary, property);
if (collection != null) {
OneToMany oneToMany = collection.getAnnotation(OneToMany.class);
if (oneToMany != null) {
String reverse = oneToMany.mappedBy();
if (hasText(reverse)) {
PropertyDescriptor reverseProperty = BeanUtils.getPropertyDescriptor(target, reverse);
if (reverseProperty != null) reverseSetter = reverseProperty.getWriteMethod();
}
}
if (reverseSetter == null) {
Class<?> targetFieldClass = ClassUtils.getGenericType(collection);
if (targetFieldClass != null)
for (PropertyDescriptor reverseProperty : BeanUtils.getPropertyDescriptors(targetFieldClass))
if (reverseProperty.getPropertyType().isAssignableFrom(primary))
reverseSetter = reverseProperty.getWriteMethod();
}
}
return reverseSetter;
}
}