Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,183 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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
*
* https://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 grails.gorm.tests.jpa

import grails.gorm.transactions.Rollback
import org.grails.orm.hibernate.HibernateDatastore
import spock.lang.AutoCleanup
import spock.lang.Issue
import spock.lang.Shared
import spock.lang.Specification
import spock.lang.Unroll

import jakarta.persistence.Entity
import jakarta.persistence.Id
import jakarta.persistence.MappedSuperclass

@Issue('https://github.com/apache/grails-core/issues/14494')
class JpaCompositeIdSpec extends Specification {

@Shared @AutoCleanup HibernateDatastore hibernateDatastore = new HibernateDatastore(JpaCompositeIdEntity, JpaSingleCodeIdEntity)

@Rollback
void 'a JPA entity with two @Id properties compiles and is saved by its composite id'() {
when:
new JpaCompositeIdEntity(orgId: 1L, userNo: 2L, name: 'org-user').save(flush: true, failOnError: true)
JpaCompositeIdEntity.withSession { it.clear() }

then:
JpaCompositeIdEntity.count() == 1
JpaCompositeIdEntity.get(new JpaCompositeIdEntity(orgId: 1L, userNo: 2L)).name == 'org-user'
}

@Unroll
void 'the @Id properties on #layout #outcome'() {
expect: 'the entity declares getId() only when exactly one @Id is declared anywhere in its hierarchy'
(entity.declaredMethods.any { it.name == 'getId' }) == declaresGetId

where:
layout | entity || declaresGetId
'the entity (two)' | JpaCompositeIdEntity || false
'the entity (one)' | JpaSingleCodeIdEntity || true
'a mapped superclass and the entity (one each)' | JpaSplitIdEntity || false
'a mapped superclass only (the entity has none)' | JpaInheritedIdEntity || false
'a mapped superclass (two) and the entity (one)' | JpaTwoInheritedIdEntity || false
'a plain superclass (one) and the entity (one)' | JpaPlainIdChild || true
'a plain superclass (two) and the entity (one)' | JpaPlainTwoIdChild || true
'an entity superclass (one) and the entity (one)' | JpaEntityBaseChild || false
'a mapped superclass (one) above a plain class, and the entity (one)' | JpaMappedAbovePlainChild || false
'a plain superclass whose @Id is on a getter, and the entity (one)' | JpaPlainGetterIdChild || true
outcome = declaresGetId ? 'give it a getId()' : 'leave getId() to the key'
}

@Rollback
void 'a JPA entity with one @Id not named id still exposes it as getId'() {
when:
JpaSingleCodeIdEntity entity = new JpaSingleCodeIdEntity(code: 7L, name: 'seven').save(flush: true, failOnError: true)

then:
entity.id == 7L
}
}

@Entity
class JpaCompositeIdEntity implements Serializable {
@Id
Long orgId
@Id
Long userNo
String name
}

@Entity
class JpaSingleCodeIdEntity {
@Id
Long code
String name
}

@MappedSuperclass
abstract class JpaOrgBase implements Serializable {
@Id
Long orgId
}

@Entity
class JpaSplitIdEntity extends JpaOrgBase {
@Id
String userNo
String name
}

@Entity
class JpaInheritedIdEntity extends JpaOrgBase {
String name
}

@MappedSuperclass
abstract class JpaTwoIdBase implements Serializable {
@Id
Long orgId
@Id
Long unitNo
}

@Entity
class JpaTwoInheritedIdEntity extends JpaTwoIdBase {
@Id
String userNo
}

abstract class JpaPlainIdBase {
@Id
Long orgId
}

@Entity
class JpaPlainIdChild extends JpaPlainIdBase {
@Id
String userNo
}

abstract class JpaPlainTwoIdBase {
@Id
Long orgId
@Id
Long unitNo
}

@Entity
class JpaPlainTwoIdChild extends JpaPlainTwoIdBase {
@Id
String userNo
}

@Entity
class JpaEntityBase implements Serializable {
@Id
Long orgId
}

@Entity
class JpaEntityBaseChild extends JpaEntityBase {
@Id
String userNo
}

class JpaPlainMiddle extends JpaOrgBase {
String note
}

@Entity
class JpaMappedAbovePlainChild extends JpaPlainMiddle {
@Id
String userNo
}

abstract class JpaPlainGetterIdBase {
@Id
Long getOrgId() { null }
}

@Entity
class JpaPlainGetterIdChild extends JpaPlainGetterIdBase {
@Id
String userNo
}
Original file line number Diff line number Diff line change
Expand Up @@ -184,6 +184,20 @@ class DirtyCheckingTransformer implements CompilationUnitAware {
}
}

int jpaIdPropertyCount = 0
for (PropertyNode pn in propertyNodes) {
final List<AnnotationNode> idCandidates = pn.annotations + pn.getField().annotations
final GetterAndSetter idGetterAndSetter = gettersAndSetters[pn.name]
if (idGetterAndSetter?.getter != null) {
idCandidates.addAll(idGetterAndSetter.getter.annotations)
}
if (hasAnnotation(idCandidates, GormEntityTransformation.JPA_ID_ANNOTATION_NODE)) {
jpaIdPropertyCount++
}
}
// an identifier declared on a superclass belongs to the same key, so it counts as well
jpaIdPropertyCount += inheritedJpaIdCount(classNode)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A mapped superclass declares getCode, and the entity declares the same identifier again. The entity used to get a getter. It does not now, because the same name is counted twice. Count each name once.


boolean hasVersion = false
for (PropertyNode pn in propertyNodes) {
final propertyName = pn.name
Expand All @@ -208,8 +222,9 @@ class DirtyCheckingTransformer implements CompilationUnitAware {

if (hasAnnotation(allAnnotationNodes, GormEntityTransformation.JPA_ID_ANNOTATION_NODE)) {
if (!propertyName.equals(GormProperties.IDENTITY)) {
// if the property is a JPA @Id but the property name is not id add a transient getter to retrieve the id called getId
if (classNode.getField(GormProperties.IDENTITY) == null && gettersAndSetters[GormProperties.IDENTITY] == null) {
// if the property is the only JPA @Id but the property name is not id add a transient getter to retrieve the id called getId,
// a composite id has no single value to return
if (jpaIdPropertyCount == 1 && classNode.getField(GormProperties.IDENTITY) == null && gettersAndSetters[GormProperties.IDENTITY] == null) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A mapped superclass has @id Long orgId. The entity extends it and adds @id String userNo. The count sees only userNo, so it still generates getId() on both classes, with different return types. Compilation fails. Count inherited identifiers too, and do not generate getId() when there is more than one.

def getIdMethod = new MethodNode(
'getId',
Modifier.PUBLIC,
Expand Down Expand Up @@ -477,6 +492,47 @@ class DirtyCheckingTransformer implements CompilationUnitAware {
return ['Domain'] as String[]
}

private static final Set<String> MAPPED_SUPERCLASS_ANNOTATIONS = [
'jakarta.persistence.MappedSuperclass', 'jakarta.persistence.Entity', 'grails.persistence.Entity', 'grails.gorm.annotation.Entity'
] as Set<String>

/**
* Whether the mapping of a superclass is kept by the classes below it: a mapped superclass or an entity. The identifiers of
* a plain class are not part of the key of a class that extends it.
*/
private static boolean keepsMapping(ClassNode superClass) {
superClass.annotations.any { AnnotationNode annotation -> MAPPED_SUPERCLASS_ANNOTATIONS.contains(annotation.classNode.name) }
}

/**
* Counts the JPA {@code @Id} properties that the mapped superclasses of a class declare, by field, property or getter.
*/
private static int inheritedJpaIdCount(ClassNode classNode) {
Set<String> names = new LinkedHashSet<String>()
for (ClassNode superClass = classNode.superClass; superClass != null && superClass != ClassHelper.OBJECT_TYPE; superClass = superClass.superClass) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A plain superclass has an identifier field, and the entity has one identifier of its own. The entity used to get a getter. It does not now, because this counts the superclass field even though that class is not mapped. Count a superclass only when its mapping is kept.

if (!keepsMapping(superClass)) {
continue
}
for (FieldNode field in superClass.fields) {
if (!field.isStatic() && hasAnnotation(field.annotations, GormEntityTransformation.JPA_ID_ANNOTATION_NODE)) {
names.add(field.name)
}
}
for (PropertyNode property in superClass.properties) {
if (hasAnnotation(property.annotations, GormEntityTransformation.JPA_ID_ANNOTATION_NODE)) {
names.add(property.name)
}
}
for (MethodNode method in superClass.methods) {
if (method.parameters.length == 0 && method.name.startsWith('get') && method.name.length() > 3 &&
hasAnnotation(method.annotations, GormEntityTransformation.JPA_ID_ANNOTATION_NODE)) {
names.add(NameUtils.getPropertyNameForGetterOrSetter(method.name))
}
}
}
return names.size()
}

@CompileStatic
class GetterAndSetter {
MethodNode getter
Expand Down
Loading