View Javadoc

1   /*
2    * Copyright 2006 Outsource Cafe, Inc.
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    *    http://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.javagen.agile.db.model;
17  
18  import java.util.EnumSet;
19  import java.util.HashMap;
20  import java.util.Map;
21  
22  /***
23   * Cardinality of database relationships.  Single sided and reverse perspectives are
24   * supported through utility methods.
25   * 
26   * @author Richard Easterling
27   */
28  public enum Cardinality {
29  	
30  	ONE_TO_ONE("one-to-one"), 
31  	ONE_TO_MANY("one-to-many"), 
32  	MANY_TO_ONE("many-to-one"), 
33  	MANY_TO_MANY("many-to-many");
34  	
35  	private String mapping;
36  	private Cardinality reverse;
37  	private static Map<String, Cardinality> lookupTable = new HashMap<String, Cardinality>();
38  	
39  	private Cardinality(String mapping) {	this.mapping = mapping; }
40      
41      
42      /*** Cardinality for one end of a reference */
43      public enum Side {ONE, MANY};
44      
45      public static EnumSet<Cardinality> ONE_TO_X = EnumSet.of(ONE_TO_MANY, ONE_TO_ONE);
46      public static EnumSet<Cardinality> X_TO_ONE = EnumSet.of(ONE_TO_ONE, MANY_TO_ONE);
47  
48  	public static Side thisSide(Cardinality card) { return ONE_TO_X.contains(card) ? Side.ONE : Side.MANY; }
49  	public static Side otherSide(Cardinality card) { return X_TO_ONE.contains(card) ? Side.ONE : Side.MANY; }
50  	public static String thisSide(String card) { return thisSide(lookup(card)).toString(); }
51  	public static String otherSide(String card) { return otherSide(lookup(card)).toString(); }
52      
53      /*** text representation of cardinality */
54      public String getMapping() { return mapping; }
55      
56      /*** lookup cardinality given text representation */
57  	public static Cardinality lookup(String mapping) { 
58  		return mapping==null ? null : lookupTable.get(mapping.toUpperCase()); 
59  	}
60  	
61      /*** reverse relationship cardinality */
62      public Cardinality getReverse() { return reverse; }
63      
64      static {
65          for (Cardinality card : Cardinality.values()) {
66      			lookupTable.put(card.getMapping().toUpperCase(), card);
67      			lookupTable.put(card.toString(), card);
68          }
69      	ONE_TO_ONE.reverse = ONE_TO_ONE;
70      	ONE_TO_MANY.reverse = MANY_TO_ONE;
71      	MANY_TO_ONE.reverse = ONE_TO_MANY;
72      	MANY_TO_MANY.reverse = MANY_TO_MANY;
73      }
74  }
75