Example usage for javax.persistence GenerationType IDENTITY

List of usage examples for javax.persistence GenerationType IDENTITY

Introduction

In this page you can find the example usage for javax.persistence GenerationType IDENTITY.

Prototype

GenerationType IDENTITY

To view the source code for javax.persistence GenerationType IDENTITY.

Click Source Link

Document

Indicates that the persistence provider must assign primary keys for the entity using a database identity column.

Usage

From source file:com.vgorcinschi.concordiafootballmanager.model.Player.java

@Id
@Column(name = "PlayerId")
@GeneratedValue(strategy = GenerationType.IDENTITY)
public long getId() {
    return id;
}

From source file:com.eclecticlogic.pedal.dialect.postgresql.CopyCommand.java

@SuppressWarnings("unchecked")
private void setupFor(Class<? extends Serializable> clz) {
    if (fieldNamesByClass.get(clz) == null) {
        List<String> fields = new ArrayList<>();
        List<Method> methods = new ArrayList<>();
        for (Method method : clz.getMethods()) {
            String columnName = null;
            if (method.isAnnotationPresent(Id.class) && method.isAnnotationPresent(GeneratedValue.class)
                    && method.getAnnotation(GeneratedValue.class).strategy() == GenerationType.IDENTITY) {
                // Ignore pk with identity strategy.
            } else if (method.isAnnotationPresent(Column.class)) {
                columnName = extractColumnName(method, clz);
            } else if (method.isAnnotationPresent(JoinColumn.class)
                    && method.getAnnotation(JoinColumn.class).insertable()) {
                columnName = method.getAnnotation(JoinColumn.class).name();
            } else if (method.isAnnotationPresent(EmbeddedId.class)) {
                // Handle Attribute override annotation ...
                if (method.isAnnotationPresent(AttributeOverrides.class)) {
                    AttributeOverrides overrides = method.getAnnotation(AttributeOverrides.class);
                    for (AttributeOverride override : overrides.value()) {
                        fields.add(override.column().name());
                    }// w w w.  j  ava2  s  . c  o  m
                }
                methods.add(method);
            } else if (method.getReturnType().isAnnotationPresent(Embeddable.class)) {
                methods.add(method);
                // Embeddables can have column names remapped using attribute overrides.
                // We expect all attributes to be overridden. 
                if (method.isAnnotationPresent(AttributeOverrides.class)) {
                    AttributeOverrides overrides = method.getAnnotation(AttributeOverrides.class);
                    for (AttributeOverride overrideAnnotation : overrides.value()) {
                        fields.add(overrideAnnotation.column().name());
                    }
                } else {
                    // Use the column names from the embeddable class. Assumption: @Column annotation exists.
                    for (Method embedded : method.getReturnType().getMethods()) {
                        if (embedded.isAnnotationPresent(Column.class)) {
                            fields.add(extractColumnName(embedded,
                                    (Class<? extends Serializable>) method.getReturnType()));
                        }
                    }
                }
            }
            if (columnName != null) {
                // Certain one-to-on join situations can lead to multiple columns with the same column-name.
                if (!fields.contains(columnName)) {
                    fields.add(columnName);
                    methods.add(method);
                }
            } // end if annotation present
        }
        extractorsByClass.put(clz, getExtractor(clz, methods));
        StringBuilder builder = new StringBuilder();
        for (String field : fields) {
            builder.append(",").append(field);
        }
        fieldNamesByClass.put(clz, builder.substring(1));
    }
}

From source file:jp.co.tis.gsp.tools.dba.dialect.Dialect.java

public GenerationType getGenerationType() {
    return GenerationType.IDENTITY;
}

From source file:cn.org.awcp.core.mybatis.mapper.EntityHelper.java

/**
 * ?//from  w ww . jav  a 2s.c o m
 * 
 * @param entityClass
 */
public static synchronized void initEntityNameMap(Class<?> entityClass) {
    if (entityTableMap.get(entityClass) != null) {
        return;
    }
    // ??
    EntityTable entityTable = null;
    if (entityClass.isAnnotationPresent(Table.class)) {
        Table table = entityClass.getAnnotation(Table.class);
        if (!table.name().equals("")) {
            entityTable = new EntityTable();
            entityTable.setTable(table);
        }
    }
    if (entityTable == null) {
        entityTable = new EntityTable();
        entityTable.name = camelhumpToUnderline(entityClass.getSimpleName()).toUpperCase();
    }
    entityTableMap.put(entityClass, entityTable);
    // 
    List<Field> fieldList = getAllField(entityClass, null);
    List<EntityColumn> columnList = new ArrayList<EntityColumn>();
    List<EntityColumn> pkColumnList = new ArrayList<EntityColumn>();
    List<EntityColumn> obColumnList = new ArrayList<EntityColumn>();

    for (Field field : fieldList) {
        // 
        if (field.isAnnotationPresent(Transient.class)) {
            continue;
        }
        EntityColumn entityColumn = new EntityColumn();
        if (field.isAnnotationPresent(Id.class)) {
            entityColumn.setId(true);
        }
        if (field.isAnnotationPresent(OrderBy.class)) {
            OrderBy orderBy = field.getAnnotation(OrderBy.class);
            if (StringUtils.isNotBlank(orderBy.value()) && orderBy.value().equalsIgnoreCase("desc")) {
                entityColumn.setOrderBy(OrderByEnum.DESC);
            } else {
                entityColumn.setOrderBy(OrderByEnum.ASC);
            }
        }
        String columnName = null;
        if (field.isAnnotationPresent(Column.class)) {
            Column column = field.getAnnotation(Column.class);
            columnName = column.name();
        }
        if (columnName == null || columnName.equals("")) {
            columnName = camelhumpToUnderline(field.getName());
        }
        entityColumn.setProperty(field.getName());
        entityColumn.setColumn(columnName.toUpperCase());
        entityColumn.setJavaType(field.getType());
        //  - Oracle?MySqlUUID
        if (field.isAnnotationPresent(SequenceGenerator.class)) {
            SequenceGenerator sequenceGenerator = field.getAnnotation(SequenceGenerator.class);
            if (sequenceGenerator.sequenceName().equals("")) {
                throw new RuntimeException(entityClass + "" + field.getName()
                        + "@SequenceGeneratorsequenceName!");
            }
            entityColumn.setSequenceName(sequenceGenerator.sequenceName());
        } else if (field.isAnnotationPresent(GeneratedValue.class)) {
            GeneratedValue generatedValue = field.getAnnotation(GeneratedValue.class);
            if (generatedValue.generator().equals("UUID")) {
                if (field.getType().equals(String.class)) {
                    entityColumn.setUuid(true);
                } else {
                    throw new RuntimeException(field.getName()
                            + " - @GeneratedValue?UUID?String");
                }
            } else if (generatedValue.generator().equals("JDBC")) {
                if (Number.class.isAssignableFrom(field.getType())) {
                    entityColumn.setIdentity(true);
                    entityColumn.setGenerator("JDBC");
                } else {
                    throw new RuntimeException(field.getName()
                            + " - @GeneratedValue?UUID?String");
                }
            } else {
                // ?generator??idsql,mysql=CALL
                // IDENTITY(),hsqldb=SELECT SCOPE_IDENTITY()
                // ??generator
                if (generatedValue.strategy() == GenerationType.IDENTITY) {
                    // mysql
                    entityColumn.setIdentity(true);
                    if (!generatedValue.generator().equals("")) {
                        String generator = null;
                        MapperHelper.IdentityDialect identityDialect = MapperHelper.IdentityDialect
                                .getDatabaseDialect(generatedValue.generator());
                        if (identityDialect != null) {
                            generator = identityDialect.getIdentityRetrievalStatement();
                        } else {
                            generator = generatedValue.generator();
                        }
                        entityColumn.setGenerator(generator);
                    }
                } else {
                    throw new RuntimeException(field.getName()
                            + " - @GeneratedValue?????:"
                            + "\n1.?@GeneratedValue(generator=\"UUID\")"
                            + "\n2.useGeneratedKeys@GeneratedValue(generator=\\\"JDBC\\\")  "
                            + "\n3.mysql?@GeneratedValue(strategy=GenerationType.IDENTITY[,generator=\"Mysql\"])");
                }
            }
        }
        columnList.add(entityColumn);
        if (entityColumn.isId()) {
            pkColumnList.add(entityColumn);
        }
        if (entityColumn.getOrderBy() != null) {
            obColumnList.add(entityColumn);
        }
    }
    if (pkColumnList.size() == 0) {
        pkColumnList = columnList;
    }
    entityClassColumns.put(entityClass, columnList);
    entityClassPKColumns.put(entityClass, pkColumnList);
    entityOrderByColumns.put(entityClass, obColumnList);
}

From source file:com.github.abel533.mapperhelper.EntityHelper.java

/**
 * ?/*from   www.  j a  va 2s. c  o m*/
 *
 * @param entityClass
 */
public static synchronized void initEntityNameMap(Class<?> entityClass) {
    if (entityTableMap.get(entityClass) != null) {
        return;
    }
    //??
    EntityTable entityTable = null;
    if (entityClass.isAnnotationPresent(Table.class)) {
        Table table = entityClass.getAnnotation(Table.class);
        if (!table.name().equals("")) {
            entityTable = new EntityTable();
            entityTable.setTable(table);
        }
    }
    if (entityTable == null) {
        entityTable = new EntityTable();
        //??????@Table
        entityTable.name = camelhumpToUnderline(entityClass.getSimpleName());
    }
    //
    List<Field> fieldList = getAllField(entityClass, null);
    Set<EntityColumn> columnSet = new HashSet<EntityColumn>();
    Set<EntityColumn> pkColumnSet = new HashSet<EntityColumn>();
    for (Field field : fieldList) {
        //
        if (field.isAnnotationPresent(Transient.class)) {
            continue;
        }
        EntityColumn entityColumn = new EntityColumn();
        if (field.isAnnotationPresent(Id.class)) {
            entityColumn.setId(true);
        }
        String columnName = null;
        if (field.isAnnotationPresent(Column.class)) {
            Column column = field.getAnnotation(Column.class);
            columnName = column.name();
        }
        if (columnName == null || columnName.equals("")) {
            columnName = camelhumpToUnderline(field.getName());
        }
        entityColumn.setProperty(field.getName());
        entityColumn.setColumn(columnName.toUpperCase());
        entityColumn.setJavaType(field.getType());
        //order by
        if (field.isAnnotationPresent(OrderBy.class)) {
            OrderBy orderBy = field.getAnnotation(OrderBy.class);
            if (orderBy.value().equals("")) {
                entityColumn.setOrderBy("ASC");
            } else {
                entityColumn.setOrderBy(orderBy.value());
            }
        }
        // - Oracle?MySqlUUID
        if (field.isAnnotationPresent(SequenceGenerator.class)) {
            SequenceGenerator sequenceGenerator = field.getAnnotation(SequenceGenerator.class);
            if (sequenceGenerator.sequenceName().equals("")) {
                throw new RuntimeException(entityClass + "" + field.getName()
                        + "@SequenceGeneratorsequenceName!");
            }
            entityColumn.setSequenceName(sequenceGenerator.sequenceName());
        } else if (field.isAnnotationPresent(GeneratedValue.class)) {
            GeneratedValue generatedValue = field.getAnnotation(GeneratedValue.class);
            if (generatedValue.generator().equals("UUID")) {
                if (field.getType().equals(String.class)) {
                    entityColumn.setUuid(true);
                } else {
                    throw new RuntimeException(field.getName()
                            + " - @GeneratedValue?UUID?String");
                }
            } else if (generatedValue.generator().equals("JDBC")) {
                if (Number.class.isAssignableFrom(field.getType())) {
                    entityColumn.setIdentity(true);
                    entityColumn.setGenerator("JDBC");
                } else {
                    throw new RuntimeException(field.getName()
                            + " - @GeneratedValue?UUID?String");
                }
            } else {
                //?generator??idsql,mysql=CALL IDENTITY(),hsqldb=SELECT SCOPE_IDENTITY()
                //??generator
                if (generatedValue.strategy() == GenerationType.IDENTITY) {
                    //mysql
                    entityColumn.setIdentity(true);
                    if (!generatedValue.generator().equals("")) {
                        String generator = null;
                        MapperHelper.IdentityDialect identityDialect = MapperHelper.IdentityDialect
                                .getDatabaseDialect(generatedValue.generator());
                        if (identityDialect != null) {
                            generator = identityDialect.getIdentityRetrievalStatement();
                        } else {
                            generator = generatedValue.generator();
                        }
                        entityColumn.setGenerator(generator);
                    }
                } else {
                    throw new RuntimeException(field.getName()
                            + " - @GeneratedValue?????:"
                            + "\n1.?@GeneratedValue(generator=\"UUID\")"
                            + "\n2.useGeneratedKeys@GeneratedValue(generator=\\\"JDBC\\\")  "
                            + "\n3.mysql?@GeneratedValue(strategy=GenerationType.IDENTITY[,generator=\"Mysql\"])");
                }
            }
        }
        columnSet.add(entityColumn);
        if (entityColumn.isId()) {
            pkColumnSet.add(entityColumn);
        }
    }
    entityTable.entityClassColumns = columnSet;
    if (pkColumnSet.size() == 0) {
        entityTable.entityClassPKColumns = columnSet;
    } else {
        entityTable.entityClassPKColumns = pkColumnSet;
    }
    //
    entityTableMap.put(entityClass, entityTable);
}

From source file:com.thysmichels.swagger4forcedotcom.models.Contact.java

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "dbId", unique = true, nullable = false)
public Long getdbId() {
    return dbid;
}

From source file:com.mmnaseri.dragonfly.metadata.impl.AnnotationTableMetadataResolver.java

private ValueGenerationType determineValueGenerationType(Method method) {
    if (method.isAnnotationPresent(GeneratedValue.class)) {
        final GeneratedValue generatedValue = method.getAnnotation(GeneratedValue.class);
        return generatedValue.strategy().equals(GenerationType.AUTO) ? dialect.getDefaultGenerationType()
                : (generatedValue.strategy().equals(GenerationType.IDENTITY) ? ValueGenerationType.IDENTITY
                        : (generatedValue.strategy().equals(GenerationType.SEQUENCE)
                                ? ValueGenerationType.SEQUENCE
                                : (generatedValue.strategy().equals(GenerationType.TABLE)
                                        ? ValueGenerationType.TABLE
                                        : null)));
    } else {/*from   w  w w .  j av  a 2  s  .co  m*/
        return null;
    }
}

From source file:org.grails.datastore.gorm.jpa.GormToJpaTransform.java

public static void transformEntity(SourceUnit source, ClassNode classNode) {

    // add the JPA @Entity annotation
    classNode.addAnnotation(ANNOTATION_ENTITY);
    final AnnotationNode entityListenersAnnotation = new AnnotationNode(new ClassNode(EntityListeners.class));
    entityListenersAnnotation.addMember("value",
            new ClassExpression(new ClassNode(EntityInterceptorInvokingEntityListener.class)));
    classNode.addAnnotation(entityListenersAnnotation);

    PropertyNode mappingNode = classNode.getProperty(GrailsDomainClassProperty.MAPPING);
    Map<String, Map<String, ?>> propertyMappings = new HashMap<String, Map<String, ?>>();
    if (mappingNode != null && mappingNode.isStatic()) {
        populateConfigurationMapFromClosureExpression(classNode, mappingNode, propertyMappings);
    }//www  .j  a v a  2 s.  c  o m

    // annotate the id property with @Id
    String idPropertyName = GrailsDomainClassProperty.IDENTITY;
    String generationType = GenerationType.AUTO.toString();

    final PropertyNode errorsProperty = classNode.getProperty("errors");
    if (errorsProperty == null) {
        if (ClassUtils.isPresent("org.codehaus.groovy.grails.compiler.injection.ASTValidationErrorsHelper",
                Thread.currentThread().getContextClassLoader())) {
            addErrorsProperty(classNode);
        }
    }

    if (propertyMappings.containsKey(GrailsDomainClassProperty.IDENTITY)) {
        final Map<String, ?> idConfig = propertyMappings.get(GrailsDomainClassProperty.IDENTITY);
        if (idConfig.containsKey("name")) {
            idPropertyName = idConfig.get("name").toString();
        }
        if (idConfig.containsKey("generator")) {
            String generatorName = idConfig.get("generator").toString();
            if ("assigned".equals(generatorName)) {
                generationType = null;
            } else if ("sequence".equals(generatorName)) {
                generationType = GenerationType.SEQUENCE.toString();
            } else if ("identity".equals(generatorName)) {
                generationType = GenerationType.IDENTITY.toString();
            }
        }
    }

    PropertyNode idProperty = classNode.getProperty(idPropertyName);
    if (idProperty == null) {
        new DefaultGrailsDomainClassInjector().performInjectionOnAnnotatedEntity(classNode);
        idProperty = classNode.getProperty(GrailsDomainClassProperty.IDENTITY);
    }

    if (!idPropertyName.equals(GrailsDomainClassProperty.IDENTITY)) {
        PropertyNode toDiscard = classNode.getProperty(GrailsDomainClassProperty.IDENTITY);
        if (toDiscard != null && toDiscard.getType().equals("java.lang.Long")) {
            classNode.getProperties().remove(toDiscard);
        }
    }

    if (idProperty != null) {
        final FieldNode idField = idProperty.getField();

        idField.addAnnotation(ANNOTATION_ID);
        if (generationType != null) {
            final AnnotationNode generatedValueAnnotation = new AnnotationNode(
                    new ClassNode(GeneratedValue.class));
            generatedValueAnnotation.addMember("strategy", new PropertyExpression(
                    new ClassExpression(new ClassNode(GenerationType.class)), generationType));
            idField.addAnnotation(generatedValueAnnotation);
        }
    }

    // annotate the version property with @Version
    PropertyNode versionProperty = classNode.getProperty(GrailsDomainClassProperty.VERSION);
    if (versionProperty != null) {
        if (propertyMappings.containsKey(GrailsDomainClassProperty.VERSION)) {
            final Map<String, ?> versionSettings = propertyMappings.get(GrailsDomainClassProperty.VERSION);
            final Object enabledObject = versionSettings.get("enabled");
            if (enabledObject instanceof Boolean) {
                if (((Boolean) enabledObject).booleanValue()) {
                    versionProperty.addAnnotation(ANNOTATION_VERSION);
                }
            }
        } else {
            versionProperty.addAnnotation(ANNOTATION_VERSION);
        }
    }

    final List<MethodNode> methods = classNode.getMethods();
    for (MethodNode methodNode : methods) {
        if (methodNode.isStatic() || !methodNode.isPublic() || methodNode.isAbstract()) {
            continue;
        }

        final AnnotationNode annotationNode = gormEventMethodToJpaAnnotation.get(methodNode.getName());
        if (annotationNode == null) {
            continue;
        }

        //methodNode.setReturnType(new ClassNode(void.class));
        methodNode.addAnnotation(annotationNode);
    }

    Map<String, ClassNode> hasManyMap = lookupStringToClassNodeMap(classNode,
            GrailsDomainClassProperty.HAS_MANY);
    Map<String, ClassNode> hasOneMap = lookupStringToClassNodeMap(classNode, GrailsDomainClassProperty.HAS_ONE);
    Map<String, ClassNode> belongsToMap = lookupStringToClassNodeMap(classNode,
            GrailsDomainClassProperty.BELONGS_TO);
    Map<String, String> mappedByMap = lookupStringToStringMap(classNode, GrailsDomainClassProperty.MAPPED_BY);

    final List<PropertyNode> properties = classNode.getProperties();
    for (PropertyNode propertyNode : properties) {
        if (!propertyNode.isPublic() || propertyNode.isStatic()) {
            continue;
        }

        if (propertyNode == idProperty || propertyNode == versionProperty) {
            continue;
        }

        final String typeName = propertyNode.getType().getName();

        if (typeName.equals("java.util.Date") || typeName.equals("java.util.Calendar")) {
            AnnotationNode temporalAnnotation = new AnnotationNode(new ClassNode(Temporal.class));
            temporalAnnotation.addMember("value",
                    new PropertyExpression(new ClassExpression(new ClassNode(TemporalType.class)), "DATE"));
            propertyNode.getField().addAnnotation(temporalAnnotation);
        } else if (MappingFactory.isSimpleType(typeName)) {
            propertyNode.getField().addAnnotation(ANNOTATION_BASIC);
        } else {
            final String propertyName = propertyNode.getName();
            if (!belongsToMap.containsKey(propertyName) && !hasOneMap.containsKey(propertyName)
                    && !hasManyMap.containsKey(propertyName)) {
                handleToOne(classNode, belongsToMap, propertyName);
            }
        }
    }

    final PropertyNode transientsProp = classNode.getProperty(GrailsDomainClassProperty.TRANSIENT);
    List<String> propertyNameList = new ArrayList<String>();
    populateConstantList(propertyNameList, transientsProp);
    annotateAllProperties(classNode, propertyNameList, Transient.class);

    propertyNameList.clear();
    final PropertyNode embeddedProp = classNode.getProperty(GrailsDomainClassProperty.EMBEDDED);
    populateConstantList(propertyNameList, embeddedProp);
    annotateAllProperties(classNode, propertyNameList, Embedded.class);

    if (embeddedProp != null) {
        for (String propertyName : propertyNameList) {
            final PropertyNode property = classNode.getProperty(propertyName);
            if (property == null) {
                continue;
            }

            ClassNode embeddedType = property.getField().getType();
            annotateIfNecessary(embeddedType, Embeddable.class);
        }
    }

    if (!belongsToMap.isEmpty()) {
        for (String propertyName : belongsToMap.keySet()) {
            handleToOne(classNode, belongsToMap, propertyName);
        }
    }

    if (!hasOneMap.isEmpty()) {
        for (String propertyName : hasOneMap.keySet()) {
            final AnnotationNode oneToOneAnnotation = new AnnotationNode(new ClassNode(OneToOne.class));
            oneToOneAnnotation.addMember("optional", ConstantExpression.FALSE);
            oneToOneAnnotation.addMember("cascade", EXPR_CASCADE_ALL);
            annotateProperty(classNode, propertyName, oneToOneAnnotation);
        }
    }

    if (!hasManyMap.isEmpty()) {
        for (String propertyName : hasManyMap.keySet()) {
            ClassNode associatedClass = hasManyMap.get(propertyName);
            final Map<String, ClassNode> inverseBelongsToMap = lookupStringToClassNodeMap(associatedClass,
                    GrailsDomainClassProperty.BELONGS_TO);
            final Map<String, ClassNode> inverseHasManyMap = lookupStringToClassNodeMap(associatedClass,
                    GrailsDomainClassProperty.HAS_MANY);

            final AnnotationNode oneToManyAnnotation = new AnnotationNode(new ClassNode(OneToMany.class));
            oneToManyAnnotation.addMember("targetEntity", new ClassExpression(associatedClass));

            if (mappedByMap.containsKey(propertyName)) {
                oneToManyAnnotation.addMember("mappedBy",
                        new ConstantExpression(mappedByMap.get(propertyName)));
                oneToManyAnnotation.addMember("cascade", EXPR_CASCADE_PERSIST);
                annotateProperty(classNode, propertyName, oneToManyAnnotation);
            } else {
                if (inverseHasManyMap.containsValue(classNode)) {
                    // many-to-many association
                    List<ClassNode> belongsToList = getBelongsToList(classNode);

                    final AnnotationNode manyToManyAnnotation = new AnnotationNode(
                            new ClassNode(ManyToMany.class));
                    manyToManyAnnotation.addMember("targetEntity", new ClassExpression(associatedClass));
                    if (belongsToList.contains(associatedClass)) {
                        for (String inversePropertyName : inverseHasManyMap.keySet()) {
                            if (classNode.equals(inverseHasManyMap.get(inversePropertyName))) {
                                manyToManyAnnotation.addMember("mappedBy",
                                        new ConstantExpression(inversePropertyName));
                            }
                        }
                    } else {
                        manyToManyAnnotation.addMember("cascade", EXPR_CASCADE_ALL);
                    }
                    annotateProperty(classNode, propertyName, manyToManyAnnotation);
                }
                // Try work out the other side of the association
                else if (inverseBelongsToMap.containsValue(classNode)) {
                    for (String inversePropertyName : inverseBelongsToMap.keySet()) {
                        if (classNode.equals(inverseBelongsToMap.get(inversePropertyName))) {
                            oneToManyAnnotation.addMember("mappedBy",
                                    new ConstantExpression(inversePropertyName));
                            oneToManyAnnotation.addMember("cascade", EXPR_CASCADE_ALL);
                        }
                    }
                    annotateProperty(classNode, propertyName, oneToManyAnnotation);
                } else {
                    PropertyNode inverseClosestMatch = findClosestInverstTypeMatch(classNode, associatedClass);
                    if (inverseClosestMatch != null) {
                        oneToManyAnnotation.addMember("mappedBy",
                                new ConstantExpression(inverseClosestMatch.getName()));
                    }
                    // unidrectional one-to-many
                    oneToManyAnnotation.addMember("cascade", EXPR_CASCADE_ALL);
                    annotateProperty(classNode, propertyName, oneToManyAnnotation);
                }
            }
        }
    }
}

From source file:org.guzz.builder.JPA2AnnotationsBuilder.java

protected static void addIdMapping(GuzzContextImpl gf, POJOBasedObjectMapping map, SimpleTable st,
        DBGroup dbGroup, String name, Class domainClas, AnnotatedElement element) {
    javax.persistence.Column pc = (javax.persistence.Column) element
            .getAnnotation(javax.persistence.Column.class);
    org.guzz.annotations.Column gc = (org.guzz.annotations.Column) element
            .getAnnotation(org.guzz.annotations.Column.class);

    String type = gc == null ? null : gc.type();
    String column = pc == null ? null : pc.name();

    if (StringUtil.isEmpty(column)) {
        column = name;//from w ww .  j  a  v  a  2s  . c  o  m
    }

    TableColumn col = st.getColumnByPropName(name);
    boolean newId = false;

    if (col == null) {
        newId = true;
        col = new TableColumn(st);
    } else {
        log.info("override @Id in the parent class of [" + st.getBusinessName() + "].");
    }

    col.setColName(column);
    col.setPropName(name);
    col.setType(type);
    col.setAllowInsert(true);
    col.setAllowUpdate(true);
    col.setLazy(false);
    map.initColumnMapping(col, null);

    if (newId) {
        st.addPKColumn(col);
    }

    //@Id generator
    javax.persistence.GeneratedValue pgv = (javax.persistence.GeneratedValue) element
            .getAnnotation(javax.persistence.GeneratedValue.class);
    if (pgv == null) {
        pgv = (javax.persistence.GeneratedValue) domainClas
                .getAnnotation(javax.persistence.GeneratedValue.class);
    }

    //If @GeneratedValue is not defined, use auto.
    GenerationType gt = GenerationType.AUTO;
    String generatorName = null;

    if (pgv != null) {
        gt = pgv.strategy();
        generatorName = pgv.generator();
    }

    Properties idProperties = new Properties();
    String igCls;

    if (gt == GenerationType.AUTO) {
        //??guzz@GenericGenerator
        if (StringUtil.notEmpty(generatorName)) {
            GenericGenerator ggg = (GenericGenerator) element.getAnnotation(GenericGenerator.class);
            if (ggg != null && !generatorName.equals(ggg.name())) {
                ggg = null;
            }

            if (ggg == null) {
                //retreive @Id from GlobalContext
                Object g = gf.getGlobalIdGenerator(generatorName);

                //should be GenericGenerator
                if (!(g instanceof GenericGenerator)) {
                    throw new IllegalParameterException("The Id Generator [" + generatorName
                            + "] should be of type @org.guzz.annotations.GenericGenerator. domain class:"
                            + domainClas.getName());
                }

                ggg = (GenericGenerator) g;
            }

            igCls = ggg.strategy();
            Parameter[] ps = ggg.parameters();

            for (Parameter p : ps) {
                idProperties.setProperty(p.name(), p.value());
            }
        } else {
            //nativegeneratordialect?
            igCls = "native";
        }
    } else if (gt == GenerationType.IDENTITY) {
        igCls = "identity";
    } else if (gt == GenerationType.SEQUENCE) {
        igCls = "sequence";

        javax.persistence.SequenceGenerator psg = (javax.persistence.SequenceGenerator) element
                .getAnnotation(javax.persistence.SequenceGenerator.class);
        if (psg == null) {
            Object sg = gf.getGlobalIdGenerator(generatorName);
            Assert.assertNotNull(sg,
                    "@javax.persistence.SequenceGenerator not found for sequenced @Id. domain class:"
                            + domainClas.getName());

            if (sg instanceof SequenceGenerator) {
                psg = (SequenceGenerator) sg;
            } else {
                throw new IllegalParameterException("The Id Generator [" + generatorName
                        + "] should be of type @javax.persistence.SequenceGenerator. domain class:"
                        + domainClas.getName());
            }
        }

        idProperties.setProperty(SequenceIdGenerator.PARAM_SEQUENCE, psg.sequenceName());

        idProperties.setProperty("catalog", psg.catalog());
        idProperties.setProperty("allocationSize", String.valueOf(psg.allocationSize()));
        idProperties.setProperty("initialValue", String.valueOf(psg.initialValue()));

        //we need db_group param, but the JPA won't give us.
    } else if (gt == GenerationType.TABLE) {
        igCls = "hilo.multi";

        TableGenerator pst = (TableGenerator) element.getAnnotation(TableGenerator.class);
        if (pst == null) {
            Object sg = gf.getGlobalIdGenerator(generatorName);
            Assert.assertNotNull(sg,
                    "@javax.persistence.TableGenerator not found for hilo.multi @Id. domain class:"
                            + domainClas.getName());

            if (sg instanceof TableGenerator) {
                pst = (TableGenerator) sg;
            } else {
                throw new IllegalParameterException("The Id Generator [" + generatorName
                        + "] should be of type @javax.persistence.TableGenerator. domain class:"
                        + domainClas.getName());
            }
        }

        idProperties.setProperty("catalog", pst.catalog());
        idProperties.setProperty("schema", pst.schema());
        idProperties.setProperty(TableMultiIdGenerator.TABLE, pst.table());
        idProperties.setProperty(TableMultiIdGenerator.PK_COLUMN_NAME, pst.pkColumnName());
        idProperties.setProperty(TableMultiIdGenerator.PK_COLUMN_VALUE, pst.pkColumnValue());
        idProperties.setProperty(TableMultiIdGenerator.COLUMN, pst.valueColumnName());
        idProperties.setProperty(TableMultiIdGenerator.MAX_LO, String.valueOf(pst.allocationSize()));
        //we need db_group param, but the JPA won't give us.

        idProperties.setProperty("initialValue", String.valueOf(pst.initialValue()));
    } else {
        throw new GuzzException("unknown @javax.persistence.GenerationType:" + gt);
    }

    if ("native".equals(igCls)) {
        igCls = dbGroup.getDialect().getNativeIDGenerator();
    }

    String realClassName = (String) IdentifierGeneratorFactory.getGeneratorClass(igCls);
    Assert.assertNotNull(realClassName, "unknown Id generator:" + igCls);

    IdentifierGenerator ig = (IdentifierGenerator) BeanCreator.newBeanInstance(realClassName);

    if (ig instanceof Configurable) {
        ((Configurable) ig).configure(dbGroup.getDialect(), map, idProperties);
    }

    //register callback for GuzzContext's full starting.
    if (ig instanceof GuzzContextAware) {
        gf.registerContextStartedAware((GuzzContextAware) ig);
    }

    st.setIdentifierGenerator(ig);
}