/*
* Copyright 2012 Adaptrex, LLC
*
* 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 com.adaptrex.core.persistence.jpa;
import java.lang.reflect.Method;
import javax.persistence.EntityManager;
import javax.persistence.metamodel.SingularAttribute;
import org.apache.commons.lang3.StringUtils;
import com.adaptrex.core.ext.ExtTypeFormatter;
import com.adaptrex.core.ext.FieldDefinition;
import com.adaptrex.core.persistence.api.AdaptrexAssociationType;
import com.adaptrex.core.persistence.api.AdaptrexEntityType;
import com.adaptrex.core.security.SecureEntity;
import com.adaptrex.core.utilities.StringUtilities;
public class JPAAssociationType extends AdaptrexAssociationType {
private Method getter;
private Method setter;
public JPAAssociationType(SingularAttribute<?,?> association, SecureEntity secureEntity) {
super(association.getName(), association.getJavaType(), secureEntity);
String associationName = association.getName();
this.idFieldDefinition =
new FieldDefinition(
associationName + StringUtils.capitalize(AdaptrexEntityType.ENTITY_ID_NAME),
ExtTypeFormatter.AUTO);
String capName = StringUtilities.capitalize(getName());
Class<?> declaringClass = association.getDeclaringType().getJavaType();
try {
getter = declaringClass.getMethod("get" + capName);
} catch (Exception e) {}
if (getter != null) {
try {
setter = declaringClass.getMethod("set" + capName, getter.getReturnType());
} catch (Exception e) {}
}
}
@Override
public Object getAssociationFrom(Object entity) throws Exception {
return getter.invoke(entity);
}
public void setById(EntityManager em, Object entity, Object associationId) throws Exception {
if (associationId == null || associationId.equals("null") || associationId.equals("")) {
setter.invoke(entity, (Object) null);
} else {
setter.invoke(entity, em.find(this.getAssociationType(), associationId));
}
}
}