-
Notifications
You must be signed in to change notification settings - Fork 725
SONARJAVA-6537 Implement rule S8948: "@OneToMany" relationships should use "mappedBy" or "@JoinColumn" #5716
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
NoemieBenard
wants to merge
5
commits into
master
Choose a base branch
from
nb/sonarjava-6537-implement-S8948
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
6 changes: 6 additions & 0 deletions
6
its/autoscan/src/test/resources/autoscan/diffs/diff_S8948.json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| { | ||
| "ruleKey": "S8948", | ||
| "hasTruePositives": false, | ||
| "falseNegatives": 8, | ||
| "falsePositives": 0 | ||
| } |
61 changes: 61 additions & 0 deletions
61
java-checks-test-sources/default/src/main/java/checks/OneToManyMappingCheckSample.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,61 @@ | ||
| package checks; | ||
|
|
||
| import jakarta.persistence.Entity; | ||
| import jakarta.persistence.JoinColumn; | ||
| import jakarta.persistence.ManyToOne; | ||
| import jakarta.persistence.OneToMany; | ||
| import java.util.List; | ||
|
|
||
| public class OneToManyMappingCheckSample { | ||
|
|
||
| @Entity | ||
| class Author { | ||
| @OneToMany // Noncompliant {{Add "mappedBy" or "@JoinColumn" to this "@OneToMany" relationship.}} | ||
| // ^^^^^^^^^^ | ||
| private List<Book> books; | ||
| } | ||
|
|
||
| @Entity | ||
| class Book { | ||
| @ManyToOne | ||
| private Author author; | ||
| } | ||
|
|
||
| // Compliant: uses mappedBy | ||
| @Entity | ||
| class AuthorWithMappedBy { | ||
| @OneToMany(mappedBy = "author") | ||
| private List<BookWithAuthor> books; | ||
| } | ||
|
|
||
| @Entity | ||
| class BookWithAuthor { | ||
| @ManyToOne | ||
| @JoinColumn(name = "author_id") | ||
| private AuthorWithMappedBy author; | ||
| } | ||
|
|
||
| // Compliant: uses @JoinColumn on the @OneToMany field | ||
| @Entity | ||
| class AuthorWithJoinColumn { | ||
| @OneToMany | ||
| @JoinColumn(name = "author_id") | ||
| private List<BookNoRef> books; | ||
| } | ||
|
|
||
| @Entity | ||
| class BookNoRef { | ||
| // No reference back to Author | ||
| } | ||
|
|
||
| @Entity | ||
| class AuthorUnidirectional { | ||
| @OneToMany // Noncompliant | ||
| private List<AnotherBook> books; | ||
| } | ||
|
|
||
| @Entity | ||
| class AnotherBook { | ||
| // No reference back | ||
| } | ||
| } |
61 changes: 61 additions & 0 deletions
61
java-checks-test-sources/default/src/main/java/checks/OneToManyMappingCheckSampleJavax.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,61 @@ | ||
| package checks; | ||
|
|
||
| import java.util.List; | ||
| import javax.persistence.Entity; | ||
| import javax.persistence.JoinColumn; | ||
| import javax.persistence.ManyToOne; | ||
| import javax.persistence.OneToMany; | ||
|
|
||
| public class OneToManyMappingCheckSampleJavax { | ||
|
|
||
| @Entity | ||
| class Author { | ||
| @OneToMany // Noncompliant {{Add "mappedBy" or "@JoinColumn" to this "@OneToMany" relationship.}} | ||
| // ^^^^^^^^^^ | ||
| private List<Book> books; | ||
| } | ||
|
|
||
| @Entity | ||
| class Book { | ||
| @ManyToOne | ||
| private Author author; | ||
| } | ||
|
|
||
| // Compliant: uses mappedBy | ||
| @Entity | ||
| class AuthorWithMappedBy { | ||
| @OneToMany(mappedBy = "author") | ||
| private List<BookWithAuthor> books; | ||
| } | ||
|
|
||
| @Entity | ||
| class BookWithAuthor { | ||
| @ManyToOne | ||
| @JoinColumn(name = "author_id") | ||
| private AuthorWithMappedBy author; | ||
| } | ||
|
|
||
| // Compliant: uses @JoinColumn on the @OneToMany field | ||
| @Entity | ||
| class AuthorWithJoinColumn { | ||
| @OneToMany | ||
| @JoinColumn(name = "author_id") | ||
| private List<BookNoRef> books; | ||
| } | ||
|
|
||
| @Entity | ||
| class BookNoRef { | ||
| // No reference back to Author | ||
| } | ||
|
|
||
| @Entity | ||
| class AuthorUnidirectional { | ||
| @OneToMany // Noncompliant | ||
| private List<AnotherBook> books; | ||
| } | ||
|
|
||
| @Entity | ||
| class AnotherBook { | ||
| // No reference back | ||
| } | ||
| } |
74 changes: 74 additions & 0 deletions
74
java-checks/src/main/java/org/sonar/java/checks/OneToManyMappingCheck.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,74 @@ | ||
| /* | ||
| * SonarQube Java | ||
| * Copyright (C) SonarSource Sàrl | ||
| * mailto:info AT sonarsource DOT com | ||
| * | ||
| * You can redistribute and/or modify this program under the terms of | ||
| * the Sonar Source-Available License Version 1, as published by SonarSource Sàrl. | ||
| * | ||
| * This program is distributed in the hope that it will be useful, | ||
| * but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
| * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. | ||
| * See the Sonar Source-Available License for more details. | ||
| * | ||
| * You should have received a copy of the Sonar Source-Available License | ||
| * along with this program; if not, see https://sonarsource.com/license/ssal/ | ||
| */ | ||
| package org.sonar.java.checks; | ||
|
|
||
| import java.util.List; | ||
| import java.util.Set; | ||
| import org.sonar.check.Rule; | ||
| import org.sonar.plugins.java.api.IssuableSubscriptionVisitor; | ||
| import org.sonar.plugins.java.api.tree.AnnotationTree; | ||
| import org.sonar.plugins.java.api.tree.AssignmentExpressionTree; | ||
| import org.sonar.plugins.java.api.tree.IdentifierTree; | ||
| import org.sonar.plugins.java.api.tree.Tree; | ||
| import org.sonar.plugins.java.api.tree.VariableTree; | ||
|
|
||
| @Rule(key = "S8948") | ||
| public class OneToManyMappingCheck extends IssuableSubscriptionVisitor { | ||
|
|
||
| private static final Set<String> ONE_TO_MANY_ANNOTATIONS = Set.of( | ||
| "jakarta.persistence.OneToMany", | ||
| "javax.persistence.OneToMany"); | ||
|
|
||
| private static final Set<String> JOIN_COLUMN_ANNOTATIONS = Set.of( | ||
| "jakarta.persistence.JoinColumn", | ||
| "javax.persistence.JoinColumn"); | ||
|
|
||
| @Override | ||
| public List<Tree.Kind> nodesToVisit() { | ||
| return List.of(Tree.Kind.VARIABLE); | ||
| } | ||
|
|
||
| @Override | ||
| public void visitNode(Tree tree) { | ||
| var variable = (VariableTree) tree; | ||
| var annotations = variable.modifiers().annotations(); | ||
|
|
||
| annotations.stream() | ||
| .filter(OneToManyMappingCheck::isOneToManyAnnotation) | ||
| .filter(annotation -> !hasMappedBy(annotation)) | ||
| .filter(annotation -> annotations.stream().noneMatch(OneToManyMappingCheck::isJoinColumnAnnotation)) | ||
| .forEach(annotation -> reportIssue(annotation, "Add \"mappedBy\" or \"@JoinColumn\" to this \"@OneToMany\" relationship.")); | ||
| } | ||
|
|
||
| private static boolean isOneToManyAnnotation(AnnotationTree annotation) { | ||
| return ONE_TO_MANY_ANNOTATIONS.stream().anyMatch(annotation.annotationType().symbolType()::is); | ||
| } | ||
|
|
||
| private static boolean isJoinColumnAnnotation(AnnotationTree annotation) { | ||
| return JOIN_COLUMN_ANNOTATIONS.stream().anyMatch(annotation.annotationType().symbolType()::is); | ||
| } | ||
|
|
||
| private static boolean hasMappedBy(AnnotationTree annotation) { | ||
| return annotation.arguments().stream() | ||
| .filter(arg -> arg.is(Tree.Kind.ASSIGNMENT)) | ||
| .map(AssignmentExpressionTree.class::cast) | ||
| .map(AssignmentExpressionTree::variable) | ||
| .filter(v -> v.is(Tree.Kind.IDENTIFIER)) | ||
| .map(IdentifierTree.class::cast) | ||
| .anyMatch(id -> "mappedBy".equals(id.name())); | ||
| } | ||
| } |
41 changes: 41 additions & 0 deletions
41
java-checks/src/test/java/org/sonar/java/checks/OneToManyMappingCheckTest.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,41 @@ | ||
| /* | ||
| * SonarQube Java | ||
| * Copyright (C) SonarSource Sàrl | ||
| * mailto:info AT sonarsource DOT com | ||
| * | ||
| * You can redistribute and/or modify this program under the terms of | ||
| * the Sonar Source-Available License Version 1, as published by SonarSource Sàrl. | ||
| * | ||
| * This program is distributed in the hope that it will be useful, | ||
| * but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
| * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. | ||
| * See the Sonar Source-Available License for more details. | ||
| * | ||
| * You should have received a copy of the Sonar Source-Available License | ||
| * along with this program; if not, see https://sonarsource.com/license/ssal/ | ||
| */ | ||
| package org.sonar.java.checks; | ||
|
|
||
| import org.junit.jupiter.api.Test; | ||
| import org.sonar.java.checks.verifier.CheckVerifier; | ||
|
|
||
| import static org.sonar.java.checks.verifier.TestUtils.mainCodeSourcesPath; | ||
|
|
||
| class OneToManyMappingCheckTest { | ||
|
|
||
| @Test | ||
| void testJakarta() { | ||
| CheckVerifier.newVerifier() | ||
| .onFile(mainCodeSourcesPath("checks/OneToManyMappingCheckSample.java")) | ||
| .withCheck(new OneToManyMappingCheck()) | ||
| .verifyIssues(); | ||
| } | ||
|
|
||
| @Test | ||
| void testJavax() { | ||
| CheckVerifier.newVerifier() | ||
| .onFile(mainCodeSourcesPath("checks/OneToManyMappingCheckSampleJavax.java")) | ||
| .withCheck(new OneToManyMappingCheck()) | ||
| .verifyIssues(); | ||
| } | ||
| } |
106 changes: 106 additions & 0 deletions
106
sonar-java-plugin/src/main/resources/org/sonar/l10n/java/rules/java/S8948.html
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,106 @@ | ||
| <p>This is an issue when a one-to-many relationship in object-relational mapping is declared without either specifying which side owns the | ||
| bidirectional relationship or providing explicit foreign key column configuration, causing the ORM framework to create an unnecessary join table.</p> | ||
| <p>In JPA, this specifically refers to the <code>@OneToMany</code> annotation without a <code>mappedBy</code> attribute or <code>@JoinColumn</code> | ||
| annotation.</p> | ||
| <h2>Why is this an issue?</h2> | ||
| <p>When you define a one-to-many relationship in an object-relational mapping framework without specifying how the relationship should be mapped, the | ||
| persistence provider follows its specification default: it creates a separate join table to represent the association.</p> | ||
| <p>For example, if you have an <code>Author</code> entity with a collection of <code>Book</code> entities:</p> | ||
| <pre> | ||
| Entity: Author | ||
| one-to-many relationship -> books: collection of Book | ||
| </pre> | ||
| <p>The ORM will create three tables: <code>Author</code>, <code>Book</code>, and <code>Author_Book</code> (the join table). The join table contains | ||
| two foreign key columns: one referencing <code>Author</code> and one referencing <code>Book</code>.</p> | ||
| <p>This default behavior is rarely what you want for true one-to-many relationships</p> | ||
| <p>In JPA, this occurs when you use the <code>@OneToMany</code> annotation without additional mapping configuration. For example:</p> | ||
| <pre> | ||
| @Entity | ||
| public class Author { | ||
| @OneToMany | ||
| private List<Book> books; | ||
| } | ||
| </pre> | ||
| <h3>What is the potential impact?</h3> | ||
| <p>Using the default join table mapping for one-to-many relationships in object-relational mapping frameworks degrades application performance through | ||
| additional database tables, extra SQL statements, and more complex query plans. It also makes the database schema less intuitive and harder to | ||
| maintain, as the foreign key is not stored where developers would naturally expect it.</p> | ||
| <p>In Java, this specifically refers to the <code>@OneToMany</code> annotation in JPA (Java Persistence API) and Hibernate.</p> | ||
| <h2>How to fix it in Jakarta EE</h2> | ||
| <p>For bidirectional relationships (where the child entity has a reference back to the parent), use the <code>mappedBy</code> attribute on the | ||
| <code>@OneToMany</code> side to indicate that the relationship is owned by the child entity. This tells JPA to use the foreign key column on the child | ||
| table. The <code>mappedBy</code> value must match the field name in the child entity that references the parent.</p> | ||
| <p>For unidirectional relationships (where only the parent knows about the children), use <code>@JoinColumn</code> to specify that the foreign key | ||
| should be stored in the child table. The <code>@JoinColumn</code> annotation tells JPA to create or use a foreign key column in the child table | ||
| instead of creating a join table.</p> | ||
| <h3>Code examples</h3> | ||
| <h4>Noncompliant code example</h4> | ||
| <pre data-diff-id="1" data-diff-type="noncompliant"> | ||
| @Entity | ||
| public class Author { | ||
| @OneToMany // Noncompliant | ||
| private List<Book> books; | ||
| } | ||
|
|
||
| @Entity | ||
| public class Book { | ||
| @ManyToOne | ||
| private Author author; | ||
| } | ||
| </pre> | ||
| <h4>Compliant solution</h4> | ||
| <pre data-diff-id="1" data-diff-type="compliant"> | ||
| @Entity | ||
| public class Author { | ||
| @OneToMany(mappedBy = "author") | ||
| private List<Book> books; | ||
| } | ||
|
|
||
| @Entity | ||
| public class Book { | ||
| @ManyToOne | ||
| @JoinColumn(name = "author_id") | ||
| private Author author; | ||
| } | ||
| </pre> | ||
| <h4>Noncompliant code example</h4> | ||
| <pre data-diff-id="2" data-diff-type="noncompliant"> | ||
| @Entity | ||
| public class Author { | ||
| @OneToMany // Noncompliant | ||
| private List<Book> books; | ||
| } | ||
|
|
||
| @Entity | ||
| public class Book { | ||
| // No reference back to Author | ||
| } | ||
| </pre> | ||
| <h4>Compliant solution</h4> | ||
| <pre data-diff-id="2" data-diff-type="compliant"> | ||
| @Entity | ||
| public class Author { | ||
| @OneToMany | ||
| @JoinColumn(name = "author_id") | ||
| private List<Book> books; | ||
| } | ||
|
|
||
| @Entity | ||
| public class Book { | ||
| // No reference back to Author | ||
| // JPA will add author_id column to Book table | ||
| } | ||
| </pre> | ||
| <h2>Resources</h2> | ||
| <h3>Documentation</h3> | ||
| <ul> | ||
| <li>Jakarta Persistence Specification - OneToMany - <a | ||
| href="https://jakarta.ee/specifications/persistence/3.1/jakarta-persistence-spec-3.1.html#a11914">Official specification for @OneToMany annotation | ||
| and its default behavior</a></li> | ||
| <li>Hibernate ORM User Guide - Associations - <a | ||
| href="https://docs.jboss.org/hibernate/orm/6.2/userguide/html_single/Hibernate_User_Guide.html#associations">Comprehensive guide to Hibernate | ||
| associations including one-to-many mappings</a></li> | ||
| <li>Baeldung - JPA @OneToMany Annotation - <a href="https://www.baeldung.com/jpa-one-to-many">Practical tutorial on using @OneToMany with mappedBy | ||
|
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I get a page not found on this link |
||
| and @JoinColumn</a></li> | ||
| </ul> | ||
|
|
||
26 changes: 26 additions & 0 deletions
26
sonar-java-plugin/src/main/resources/org/sonar/l10n/java/rules/java/S8948.json
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,26 @@ | ||
| { | ||
| "title": "\"@OneToMany\" relationships should use \"mappedBy\" or \"@JoinColumn\"", | ||
| "type": "CODE_SMELL", | ||
| "status": "ready", | ||
| "remediation": { | ||
| "func": "Constant\/Issue", | ||
| "constantCost": "5 min" | ||
| }, | ||
| "tags": [ | ||
| "jpa", | ||
| "hibernate", | ||
| "performance", | ||
| "jakarta" | ||
| ], | ||
| "defaultSeverity": "Major", | ||
| "ruleSpecification": "RSPEC-8948", | ||
| "sqKey": "S8948", | ||
| "scope": "All", | ||
| "quickfix": "unknown", | ||
| "code": { | ||
| "impacts": { | ||
| "MAINTAINABILITY": "MEDIUM" | ||
| }, | ||
| "attribute": "EFFICIENT" | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -535,6 +535,7 @@ | |
| "S8745", | ||
| "S8786", | ||
| "S8911", | ||
| "S8924" | ||
| "S8924", | ||
| "S8948" | ||
| ] | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The format for the links in documentation should be:
- <source> - <url>[<title>]. In this example the title should be Hibernate ORM User Guide.