下面列出了怎么用javax.persistence.ManyToMany的API类实例代码及写法,或者点击链接到github查看源代码。
protected boolean isJpaLazy(Collection<Annotation> annotations, boolean isAssociation) {
for (Annotation annotation : annotations) {
if (annotation instanceof OneToMany) {
OneToMany oneToMany = (OneToMany) annotation;
return oneToMany.fetch() == FetchType.LAZY;
}
if (annotation instanceof ManyToOne) {
ManyToOne manyToOne = (ManyToOne) annotation;
return manyToOne.fetch() == FetchType.LAZY;
}
if (annotation instanceof ManyToMany) {
ManyToMany manyToMany = (ManyToMany) annotation;
return manyToMany.fetch() == FetchType.LAZY;
}
if (annotation instanceof ElementCollection) {
ElementCollection elementCollection = (ElementCollection) annotation;
return elementCollection.fetch() == FetchType.LAZY;
}
}
return isAssociation;
}
private boolean getCascade(ManyToMany manyManyAnnotation, ManyToOne manyOneAnnotation, OneToMany oneManyAnnotation,
OneToOne oneOneAnnotation) {
if (manyManyAnnotation != null) {
return getCascade(manyManyAnnotation.cascade());
}
if (manyOneAnnotation != null) {
return getCascade(manyOneAnnotation.cascade());
}
if (oneManyAnnotation != null) {
return getCascade(oneManyAnnotation.cascade());
}
if (oneOneAnnotation != null) {
return getCascade(oneOneAnnotation.cascade());
}
return false;
}
private String getMappedBy(MetaAttribute attr) {
ManyToMany manyManyAnnotation = attr.getAnnotation(ManyToMany.class);
OneToMany oneManyAnnotation = attr.getAnnotation(OneToMany.class);
OneToOne oneOneAnnotation = attr.getAnnotation(OneToOne.class);
String mappedBy = null;
if (manyManyAnnotation != null) {
mappedBy = manyManyAnnotation.mappedBy();
}
if (oneManyAnnotation != null) {
mappedBy = oneManyAnnotation.mappedBy();
}
if (oneOneAnnotation != null) {
mappedBy = oneOneAnnotation.mappedBy();
}
if (mappedBy != null && mappedBy.length() == 0) {
mappedBy = null;
}
return mappedBy;
}
@Override
public Optional<ResourceFieldType> getFieldType(BeanAttributeInformation attributeDesc) {
Optional<OneToOne> oneToOne = attributeDesc.getAnnotation(OneToOne.class);
Optional<OneToMany> oneToMany = attributeDesc.getAnnotation(OneToMany.class);
Optional<ManyToOne> manyToOne = attributeDesc.getAnnotation(ManyToOne.class);
Optional<ManyToMany> manyToMany = attributeDesc.getAnnotation(ManyToMany.class);
if (oneToOne.isPresent() || oneToMany.isPresent() || manyToOne.isPresent() || manyToMany.isPresent()) {
return Optional.of(ResourceFieldType.RELATIONSHIP);
}
Optional<Id> id = attributeDesc.getAnnotation(Id.class);
Optional<EmbeddedId> embeddedId = attributeDesc.getAnnotation(EmbeddedId.class);
if (id.isPresent() || embeddedId.isPresent()) {
return Optional.of(ResourceFieldType.ID);
}
return Optional.empty();
}
@Override
public Optional<SerializeType> getSerializeType(BeanAttributeInformation attributeDesc) {
Optional<OneToMany> oneToMany = attributeDesc.getAnnotation(OneToMany.class);
if (oneToMany.isPresent()) {
return toSerializeType(oneToMany.get().fetch());
}
Optional<ManyToOne> manyToOne = attributeDesc.getAnnotation(ManyToOne.class);
if (manyToOne.isPresent()) {
return toSerializeType(manyToOne.get().fetch());
}
Optional<ManyToMany> manyToMany = attributeDesc.getAnnotation(ManyToMany.class);
if (manyToMany.isPresent()) {
return toSerializeType(manyToMany.get().fetch());
}
Optional<ElementCollection> elementCollection = attributeDesc.getAnnotation(ElementCollection.class);
if (elementCollection.isPresent()) {
return toSerializeType(elementCollection.get().fetch());
}
return Optional.empty();
}
@Override
public Optional<String> getMappedBy(BeanAttributeInformation attributeDesc) {
Optional<OneToMany> oneToMany = attributeDesc.getAnnotation(OneToMany.class);
if (oneToMany.isPresent()) {
return Optional.of(oneToMany.get().mappedBy());
}
Optional<OneToOne> oneToOne = attributeDesc.getAnnotation(OneToOne.class);
if (oneToOne.isPresent()) {
return Optional.of(oneToOne.get().mappedBy());
}
Optional<ManyToMany> manyToMany = attributeDesc.getAnnotation(ManyToMany.class);
if (manyToMany.isPresent()) {
return Optional.of(manyToMany.get().mappedBy());
}
return Optional.empty();
}
private static boolean hasAnnotationsOnIdClass(XClass idClass) {
// if(idClass.getAnnotation(Embeddable.class) != null)
// return true;
List<XProperty> properties = idClass.getDeclaredProperties( XClass.ACCESS_FIELD );
for ( XProperty property : properties ) {
if ( property.isAnnotationPresent( Column.class ) || property.isAnnotationPresent( OneToMany.class ) ||
property.isAnnotationPresent( ManyToOne.class ) || property.isAnnotationPresent( Id.class ) ||
property.isAnnotationPresent( GeneratedValue.class ) || property.isAnnotationPresent( OneToOne.class ) ||
property.isAnnotationPresent( ManyToMany.class )
) {
return true;
}
}
List<XMethod> methods = idClass.getDeclaredMethods();
for ( XMethod method : methods ) {
if ( method.isAnnotationPresent( Column.class ) || method.isAnnotationPresent( OneToMany.class ) ||
method.isAnnotationPresent( ManyToOne.class ) || method.isAnnotationPresent( Id.class ) ||
method.isAnnotationPresent( GeneratedValue.class ) || method.isAnnotationPresent( OneToOne.class ) ||
method.isAnnotationPresent( ManyToMany.class )
) {
return true;
}
}
return false;
}
private static String getMappedByFromAnnotation(CtField persistentField) {
OneToOne oto = PersistentAttributesHelper.getAnnotation( persistentField, OneToOne.class );
if ( oto != null ) {
return oto.mappedBy();
}
OneToMany otm = PersistentAttributesHelper.getAnnotation( persistentField, OneToMany.class );
if ( otm != null ) {
return otm.mappedBy();
}
// For @ManyToOne associations, mappedBy must come from the @OneToMany side of the association
ManyToMany mtm = PersistentAttributesHelper.getAnnotation( persistentField, ManyToMany.class );
return mtm == null ? "" : mtm.mappedBy();
}
private String getMappedBy(MetaAttribute attr) {
ManyToMany manyManyAnnotation = attr.getAnnotation(ManyToMany.class);
OneToMany oneManyAnnotation = attr.getAnnotation(OneToMany.class);
OneToOne oneOneAnnotation = attr.getAnnotation(OneToOne.class);
String mappedBy = null;
if (manyManyAnnotation != null) {
mappedBy = manyManyAnnotation.mappedBy();
}
if (oneManyAnnotation != null) {
mappedBy = oneManyAnnotation.mappedBy();
}
if (oneOneAnnotation != null) {
mappedBy = oneOneAnnotation.mappedBy();
}
if (mappedBy != null && mappedBy.length() == 0) {
mappedBy = null;
}
return mappedBy;
}
/**
* Get the SUSE Products
* @return the SUSE Products
*/
@ManyToMany(fetch = FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.MERGE})
@JoinTable(name = "suseSCCSubscriptionProduct",
joinColumns = @JoinColumn(name = "subscription_id"),
inverseJoinColumns = @JoinColumn(name = "product_id"))
public Set<SUSEProduct> getProducts() {
return products;
}
/**
* @return the channels
*/
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "suseImageInfoChannel",
joinColumns = {
@JoinColumn(name = "image_info_id", nullable = false, updatable = false)},
inverseJoinColumns = {
@JoinColumn(name = "channel_id", nullable = false, updatable = false)}
)
public Set<Channel> getChannels() {
return channels;
}
/**
* @return the installed products
*/
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "suseImageInfoInstalledProduct",
joinColumns = {
@JoinColumn(name = "image_info_id", nullable = false, updatable = false)},
inverseJoinColumns = {
@JoinColumn(name = "installed_product_id", nullable = false, updatable = false)
})
public Set<InstalledProduct> getInstalledProducts() {
return installedProducts;
}
/**
* @return the patches
*/
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "rhnImageNeededErrataCache",
joinColumns = {@JoinColumn(name = "image_id")},
inverseJoinColumns = {@JoinColumn(name = "errata_id")}
)
public Set<PublishedErrata> getPatches() {
return patches;
}
/**
* 获取拥有角色
*
* @return {@link Role}
*/
@NotAudited
@ManyToMany
@JoinTable(name = "TB_ACCOUNT_USER_ROLE", joinColumns = { @JoinColumn(name = "USER_ID") }, inverseJoinColumns = { @JoinColumn(name = "ROLE_ID") })
public List<Role> getRoleList() {
return roleList;
}
/**
* @return the installed installedProducts
*/
@ManyToMany
@JoinTable(name = "suseImageInfoInstalledProduct",
joinColumns = { @JoinColumn(name = "image_info_id") },
inverseJoinColumns = { @JoinColumn(name = "installed_product_id") })
public Set<InstalledProduct> getInstalledProducts() {
return installedProducts;
}
@Override
protected RelationshipRepositoryBehavior getDefaultRelationshipRepositoryBehavior(BeanAttributeInformation attributeDesc) {
Optional<OneToOne> oneToOne = attributeDesc.getAnnotation(OneToOne.class);
Optional<OneToMany> oneToMany = attributeDesc.getAnnotation(OneToMany.class);
Optional<ManyToOne> manyToOne = attributeDesc.getAnnotation(ManyToOne.class);
Optional<ManyToMany> manyToMany = attributeDesc.getAnnotation(ManyToMany.class);
if (oneToOne.isPresent() || manyToOne.isPresent() || oneToMany.isPresent() || manyToMany.isPresent()) {
Optional<String> mappedBy = getMappedBy(attributeDesc);
if (mappedBy.isPresent() && mappedBy.get().length() > 0) {
return RelationshipRepositoryBehavior.FORWARD_OPPOSITE;
}
return RelationshipRepositoryBehavior.FORWARD_OWNER;
}
return RelationshipRepositoryBehavior.DEFAULT;
}
@XmlTransient
@LazyCollection(LazyCollectionOption.EXTRA)
@ManyToMany(fetch=FetchType.LAZY, cascade=CascadeType.ALL)
@JoinTable(name = "role_mappings", joinColumns = {
@JoinColumn(name = "user_id", nullable = false, updatable = false) },
inverseJoinColumns = { @JoinColumn(name = "role",
nullable = false, updatable = false) })
public List<Role> getRoles() {return _roles;}
@ManyToMany(fetch=FetchType.LAZY, cascade=CascadeType.PERSIST)
@JoinTable(name = "album_media",
joinColumns = {
@JoinColumn(name = "media_id", nullable = false, updatable = false) },
inverseJoinColumns = {
@JoinColumn(name = "album_id", nullable = false, updatable = false) })
public List<Album> getAlbums() {return albums;}
private static boolean discoverTypeWithoutReflection(XProperty p) {
if ( p.isAnnotationPresent( OneToOne.class ) && !p.getAnnotation( OneToOne.class )
.targetEntity()
.equals( void.class ) ) {
return true;
}
else if ( p.isAnnotationPresent( OneToMany.class ) && !p.getAnnotation( OneToMany.class )
.targetEntity()
.equals( void.class ) ) {
return true;
}
else if ( p.isAnnotationPresent( ManyToOne.class ) && !p.getAnnotation( ManyToOne.class )
.targetEntity()
.equals( void.class ) ) {
return true;
}
else if ( p.isAnnotationPresent( ManyToMany.class ) && !p.getAnnotation( ManyToMany.class )
.targetEntity()
.equals( void.class ) ) {
return true;
}
else if ( p.isAnnotationPresent( org.hibernate.annotations.Any.class ) ) {
return true;
}
else if ( p.isAnnotationPresent( ManyToAny.class ) ) {
if ( !p.isCollection() && !p.isArray() ) {
throw new AnnotationException( "@ManyToAny used on a non collection non array property: " + p.getName() );
}
return true;
}
else if ( p.isAnnotationPresent( Type.class ) ) {
return true;
}
else if ( p.isAnnotationPresent( Target.class ) ) {
return true;
}
return false;
}
public static boolean isManyToMany(Member member) {
if ( Field.class.isInstance( member ) ) {
return ( (Field) member ).getAnnotation( ManyToMany.class ) != null;
}
else if ( Method.class.isInstance( member ) ) {
return ( (Method) member ).getAnnotation( ManyToMany.class ) != null;
}
return false;
}
public static CtClass getTargetEntityClass(CtClass managedCtClass, CtField persistentField) throws NotFoundException {
// get targetEntity defined in the annotation
try {
OneToOne oto = PersistentAttributesHelper.getAnnotation( persistentField, OneToOne.class );
OneToMany otm = PersistentAttributesHelper.getAnnotation( persistentField, OneToMany.class );
ManyToOne mto = PersistentAttributesHelper.getAnnotation( persistentField, ManyToOne.class );
ManyToMany mtm = PersistentAttributesHelper.getAnnotation( persistentField, ManyToMany.class );
Class<?> targetClass = null;
if ( oto != null ) {
targetClass = oto.targetEntity();
}
if ( otm != null ) {
targetClass = otm.targetEntity();
}
if ( mto != null ) {
targetClass = mto.targetEntity();
}
if ( mtm != null ) {
targetClass = mtm.targetEntity();
}
if ( targetClass != null && targetClass != void.class ) {
return managedCtClass.getClassPool().get( targetClass.getName() );
}
}
catch (NotFoundException ignore) {
}
// infer targetEntity from generic type signature
String inferredTypeName = inferTypeName( managedCtClass, persistentField.getName() );
return inferredTypeName == null ? null : managedCtClass.getClassPool().get( inferredTypeName );
}
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "org_user_role_rel",
joinColumns = {@JoinColumn(name = "user_id")},
inverseJoinColumns = {@JoinColumn(name = "role_id")})
@Where(clause="delete_flag=0")
@OrderBy("no")
public Set<Role> getRoles() {
return roles;
}
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "org_role_resource_rel",
joinColumns = {@JoinColumn(name = "role_id")},
inverseJoinColumns = {@JoinColumn(name = "resources_id")})
public Set<Resource> getResources() {
return resources;
}
private CascadeType[] getCascadeTypes(AccessibleObject accessibleObject) {
CascadeType[] cascadeTypes = null;
if(accessibleObject.isAnnotationPresent(OneToMany.class)) {
cascadeTypes = accessibleObject.getAnnotation(OneToMany.class).cascade();
}else if(accessibleObject.isAnnotationPresent(ManyToOne.class)) {
cascadeTypes = accessibleObject.getAnnotation(ManyToOne.class).cascade();
}else if(accessibleObject.isAnnotationPresent(ManyToMany.class)) {
cascadeTypes = accessibleObject.getAnnotation(ManyToMany.class).cascade();
}
return cascadeTypes;
}
private boolean hasJpaAnnotations(MetaAttribute attribute) {
List<Class<? extends Annotation>> annotationClasses = Arrays.asList(Id.class, EmbeddedId.class, Column.class,
ManyToMany.class, ManyToOne.class, OneToMany.class, OneToOne.class, Version.class,
ElementCollection.class);
for (Class<? extends Annotation> annotationClass : annotationClasses) {
if (attribute.getAnnotation(annotationClass) != null) {
return true;
}
}
return false;
}
/**
* Gets the mappedBy value from an attribute
* @param attribute attribute
* @return mappedBy value or null if none.
*/
public static String getMappedBy(Attribute<?, ?> attribute) {
String mappedBy = null;
if (attribute.isAssociation()) {
Annotation[] annotations = null;
Member member = attribute.getJavaMember();
if (member instanceof Field) {
annotations = ((Field) member).getAnnotations();
}
else if (member instanceof Method) {
annotations = ((Method) member).getAnnotations();
}
for (Annotation a : annotations) {
if (a.annotationType().equals(OneToMany.class)) {
mappedBy = ((OneToMany) a).mappedBy();
break;
}
else if (a.annotationType().equals(ManyToMany.class)) {
mappedBy = ((ManyToMany) a).mappedBy();
break;
}
else if (a.annotationType().equals(OneToOne.class)) {
mappedBy = ((OneToOne) a).mappedBy();
break;
}
}
}
return "".equals(mappedBy) ? null : mappedBy;
}
@ManyToMany(cascade = {CascadeType.ALL}, fetch = FetchType.EAGER)
@JoinTable(name = "ContactToContactJoinTable",
joinColumns = @JoinColumn(name = "parentContactId"),
inverseJoinColumns = @JoinColumn(name = "childContactId"))
@XmlTransient
public Set<Contact> getContactChildren() {
return contactChildren;
}
/**
* {@inheritDoc}
*/
public void initialize(Object control, String property, InitializationConfig config) {
if (this.dao == null) {
log.warn("Nothing to do without persistent service");
return;
}
Class<?> clazz = config.getType();
PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(clazz, property);
if (pd == null) {
log.error("Not found property descriptor for property [" + property + "]") ;
return;
}
ResolvableType propertyType = ResolvableType.forMethodReturnType(pd.getReadMethod());
Annotation[] annotations = getAnnotations(property, clazz);
for (Annotation a : annotations) {
List<Object> items = null;
if (ManyToOne.class.equals(a.annotationType()) || ManyToMany.class.equals(a.annotationType()) ) {
items = getEntityList(propertyType, config.getSortPropertyName());
}
else if (Reference.class.equals(a.annotationType())) {
Reference r = (Reference) a;
Class<?> type = void.class.equals(r.target()) ? propertyType.resolve() : r.target();
List<Object> entities = getEntityList(type, config.getSortPropertyName());
items = StringUtils.isEmpty(r.property()) ? entities :
getValueList(entities, r.property());
}
if (items != null) {
if (control instanceof AbstractSelect) {
for (Object item : items)
((AbstractSelect) control).addItem(item);
}
break;
}
}
}
private static boolean needsToCascade(Field field) {
Class<?> fieldtype = field.getType();
if (!DomainObject.class.isAssignableFrom(fieldtype))
return false;
Annotation ann;
CascadeType[] cascades = null;
ann = field.getAnnotation(OneToOne.class);
if (ann != null) {
cascades = ((OneToOne) ann).cascade();
} else {
ann = field.getAnnotation(OneToMany.class);
if (ann != null) {
cascades = ((OneToMany) ann).cascade();
} else {
ann = field.getAnnotation(ManyToOne.class);
if (ann != null) {
cascades = ((ManyToOne) ann).cascade();
} else {
ann = field.getAnnotation(ManyToMany.class);
if (ann != null) {
cascades = ((ManyToMany) ann).cascade();
}
}
}
}
if (cascades == null)
return false;
for (CascadeType cas : cascades) {
if ((cas == CascadeType.ALL) || (cas == CascadeType.MERGE)
|| (cas == CascadeType.PERSIST)
|| (cas == CascadeType.REMOVE)) {
return true;
}
}
return false;
}
protected void addAssertValidCheckIfRequired(final Annotation constraintAnnotation, final Collection<Check> checks,
@SuppressWarnings("unused") /*parameter for potential use by subclasses*/final AccessibleObject fieldOrMethod) {
if (containsCheckOfType(checks, AssertValidCheck.class))
return;
if (constraintAnnotation instanceof OneToOne || constraintAnnotation instanceof OneToMany || constraintAnnotation instanceof ManyToOne
|| constraintAnnotation instanceof ManyToMany) {
checks.add(new AssertValidCheck());
}
}