-
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
Changes from 5 commits
14e64bd
683f8cf
0f8ef36
5a1517d
6944c96
31c56c1
d1fdb2a
1c6245b
9f396ff
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| { | ||
| "ruleKey": "S8948", | ||
| "hasTruePositives": false, | ||
| "falseNegatives": 8, | ||
| "falsePositives": 0 | ||
| } |
| 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 | ||
| } | ||
| } |
| 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 | ||
| } | ||
| } |
| 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.")); | ||
|
gitar-bot[bot] marked this conversation as resolved.
|
||
| } | ||
|
|
||
| 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())); | ||
| } | ||
| } | ||
| 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(); | ||
| } | ||
| } |
| 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 | ||
|
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. The format for the links in documentation should be: |
||
| 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> | ||
|
|
||
| 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" | ||
| } | ||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -535,6 +535,7 @@ | |
| "S8745", | ||
| "S8786", | ||
| "S8911", | ||
| "S8924" | ||
| "S8924", | ||
| "S8948" | ||
| ] | ||
| } | ||
Uh oh!
There was an error while loading. Please reload this page.