View Javadoc
1   /**
2    *    Copyright 2006-2016 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    *       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.mybatis.generator.plugins;
17  
18  import java.util.List;
19  import java.util.StringTokenizer;
20  
21  import org.mybatis.generator.api.IntrospectedTable;
22  import org.mybatis.generator.api.PluginAdapter;
23  
24  /**
25   * This plugin can be used to specify columns that act as a primary key, even if
26   * they are not strictly defined as primary keys in the database.
27   * 
28   * To use the plugin, add a property to the table configuration specifying a
29   * comma delimited list of column names to use as a primary key:
30   * 
31   * <br><br>
32   * &lt;property name="virtualKeyColumns" value="ID1,ID2"&gt;
33   * 
34   * @author Jeff Butler
35   * 
36   */
37  public class VirtualPrimaryKeyPlugin extends PluginAdapter {
38  
39      /* (non-Javadoc)
40       * @see org.mybatis.generator.api.Plugin#validate(java.util.List)
41       */
42      public boolean validate(List<String> warnings) {
43          return true;
44      }
45  
46      /* (non-Javadoc)
47       * @see org.mybatis.generator.api.PluginAdapter#initialized(org.mybatis.generator.api.IntrospectedTable)
48       */
49      @Override
50      public void initialized(IntrospectedTable introspectedTable) {
51          String virtualKey = introspectedTable.getTableConfiguration()
52                  .getProperty("virtualKeyColumns"); //$NON-NLS-1$
53  
54          if (virtualKey != null) {
55              StringTokenizer st = new StringTokenizer(virtualKey, ", ", false); //$NON-NLS-1$
56              while (st.hasMoreTokens()) {
57                  String column = st.nextToken();
58                  introspectedTable.addPrimaryKeyColumn(column);
59              }
60          }
61      }
62  }