JPA不是通过'type_type'而是通过'type_varname'创建@ManyToMany表名

时间:2018-12-20 17:50:20

标签: hibernate jpa java-ee eclipselink

假设我们有两个(或更多)类,其中一个是@ManyToMany,它引用了其他类: (为简化起见,我在这里省略了很多注释)

@Entity
class Newspaper {
    @Id long                    id;
    @ManyToMany Set<Author>     authors     = new HashSet<>();
    @ManyToMany Set<Article>    oldArticles = new HashSet<>();
    @ManyToMany Set<Article>    newArticles = new HashSet<>();
}

@Entity
class Article {
    @Id long id;
}

@Entity
class Author {
    @Id long id;
}

默认情况下,JPA现在将创建两个表:

Newspaper_Author
Newspaper_Article

甚至将oldArticlesnewArticles混合到同一张表中,创建有趣的结果;-)

现在,可以通过在至少一个或所有成员变量上定义@JoinTable来轻松解决此问题:

    @Entity
class Newspaper {
    @Id long                                                            id;
    @ManyToMany Set<Author>                                             authors     = new HashSet<>();
    @ManyToMany Set<Article>                                            oldArticles = new HashSet<>();
    @ManyToMany @JoinTable(name = "Newspaper_newArticles") Set<Article> newArticles = new HashSet<>();
}

所以,终于问到我的问题了: 当只有这样定义的类时

@Entity
class Newspaper {
    @Id long                    id;
    @ManyToMany Set<Author>     authors     = new HashSet<>();
    @ManyToMany Set<Article>    oldArticles = new HashSet<>();
    @ManyToMany Set<Article>    newArticles = new HashSet<>();
}

有什么方法可以使JPA自动创建表

Newspaper_authors
Newspaper_oldArticles
Newspaper_newArticles

更新: ...并使问题变得非常疯狂:

@Entity
class Newspaper {
    @Id long                    id;
    @ManyToMany Set<Author>     authors     = new HashSet<>();
    @ManyToMany Set<OldArticle> oldArticles = new HashSet<>();
    @ManyToMany Set<NewArticle> newArticles = new HashSet<>();
}

@MappedSuperclass
class Article {
    @Id long                id;
    @ManyToMany Set<Author> authors = new HashSet<>();
}

@Entity
class OldArticle extends Article { /* */ }

@Entity
class NewArticle extends Article { /* */ }

@Entity
class Author {
    @Id long id;
}

如何在这里为Article.authors定义名称?

1 个答案:

答案 0 :(得分:4)

对于您而言,我建议对所有类型的文章使用@Inheritance和单个表格,而不要使用@MappedSuperclass

@Data
@NoArgsConstructor
@Entity
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "type")
public abstract class Article {
    @Id
    @GeneratedValue
    private Integer id;

    private String name;

    @ManyToMany
    private Set<Newspaper> newspapers;

    @ManyToMany
    private Set<Author> authors;

    public Article(String name, Set<Newspaper> newspapers, Set<Author> authors) {
        this.name = name;
        this.newspapers = newspapers;
        this.authors = authors;
    }

    @Override
    public String toString() {
        return getClass().getSimpleName() + "{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}

所有类型的文章都将存储在单个表格中,您可以通过在type注释中设置的列@DiscriminatorColumn来确定其类型。

然后,您将可以在Newspaper实体中使用一组文章:

@Data
@NoArgsConstructor
@Entity
public class Newspaper {

    @Id
    @GeneratedValue
    private Integer id;

    private String name;

    @ManyToMany(mappedBy = "newspapers")
    private Set<Author> authors;

    @ManyToMany(mappedBy = "newspapers")
    private Set<Article> articles;

    public Newspaper(String name) {
        this.name = name;
    }
}

请注意在使用bi-directional ManyToMany时必须使用的参数 mappedBy

具体文章:

@NoArgsConstructor
@Entity
@DiscriminatorValue("FIRST")
public class FirstTypeArticle extends Article {
    public FirstTypeArticle(String name, Set<Newspaper> newspapers, Set<Author> authors) {
        super(name, newspapers, authors);
    }
}

@NoArgsConstructor
@Entity
@DiscriminatorValue("SECOND")
public class SecondTypeArticle extends Article {
    public SecondTypeArticle(String name, Set<Newspaper> newspapers, Set<Author> authors) {
        super(name, newspapers, authors);
    }
}

注释@DiscriminatorValue的注释,它用于设置鉴别符列的值。

作者实体(也包含一组文章):

@Data
@NoArgsConstructor
@Entity
public class Author {
    @Id
    @GeneratedValue
    private Integer id;

    private String name;

    @ManyToMany
    private Set<Newspaper> newspapers;

    @ManyToMany(mappedBy = "authors")
    private Set<Article> articles;

    public Author(String name, Set<Newspaper> newspapers) {
        this.name = name;
        this.newspapers = newspapers;
    }
}

对于我的Spring Boot 2.1.1演示项目(带有H2数据库)中的这些实体集,Hibernate创建了以下表,而没有任何其他设置:

ARTICLE
ARTICLE_AUTHORS
ARTICLE_NEWSPAPERS
AUTHOR
AUTHOR_NEWSPAPERS
NEWSPAPER

存储库:

public interface ArticleRepo extends JpaRepository<Article, Integer> {
}

public interface AuthorRepo extends JpaRepository<Author, Integer> {
}

public interface NewspaperRepo extends JpaRepository<Newspaper, Integer> {
}

用法示例:

@RunWith(SpringRunner.class)
@DataJpaTest
public class ArticleRepoTest {

    @Autowired private ArticleRepo articleRepo;
    @Autowired private AuthorRepo authorRepo;
    @Autowired private NewspaperRepo newspaperRepo;

    private List<Article> articles;

    @Before
    public void setUp() throws Exception {
        List<Newspaper> newspapers = newspaperRepo.saveAll(List.of(
                new Newspaper("newspaper1"),
                new Newspaper("newspaper2")
        ));

        List<Author> authors = authorRepo.saveAll(List.of(
                new Author("author1", new HashSet<>(newspapers)),
                new Author("author2", new HashSet<>(newspapers))
        ));

        articles = articleRepo.saveAll(List.of(
                new FirstTypeArticle("first type article", new HashSet<>(newspapers), new HashSet<>(authors)),
                new SecondTypeArticle("second type article", new HashSet<>(newspapers), new HashSet<>(authors))
        ));
    }

    @Test
    public void findAll() {
        List<Article> result = articleRepo.findAll();
        result.forEach(System.out::println);
        assertThat(result)
                .hasSize(2)
                .containsAll(articles);
    }
}

更新

  

我个人不喜欢使用@Inheritance ...
  我也尝试避免使用mappingBy功能,因为我不需要双向寻址...

当然,您可以使用@MappedSuperclass代替@Inheritance中的Article。而且您可以避免使用mappedBy并使用 unidirectional ManyToMany。

但是在这种情况下,您将只需要保存AuthorArticleNewspaper这样的独立实体(请参阅cascade = CascadeType.MERGE参数)。对于我来说,这很不方便(我尝试使用实用程序方法addAuthorsaddArticles中和它):

@Data
@NoArgsConstructor
@Entity
public class Newspaper {

    @Id
    @GeneratedValue
    private Integer id;

    private String name;

    @ManyToMany(cascade = CascadeType.MERGE)
    private Set<Author> authors = new HashSet<>();

    @ManyToMany(cascade = CascadeType.MERGE)
    private Set<FirstTypeArticle> firstTypeArticles = new HashSet<>();

    @ManyToMany(cascade = CascadeType.MERGE)
    private Set<SecondTypeArticle> secondTypeArticles = new HashSet<>();

    public Newspaper(String name) {
        this.name = name;
    }

    public Newspaper addAuthors(Author... authors) {
        if (authors != null) {
            this.authors.addAll(Set.of(authors));
        }
        return this;
    }

    public Newspaper addArticles(Article... articles) {
        for (Article article : articles) {
            if (article instanceof FirstTypeArticle) {
                this.firstTypeArticles.add((FirstTypeArticle) article);
            }
            if (article instanceof SecondTypeArticle) {
                this.secondTypeArticles.add((SecondTypeArticle) article);
            }
        }
        return this;
    }
}
@Data
@NoArgsConstructor
@Entity
public class Author {
    @Id
    @GeneratedValue
    private Integer id;

    private String name;

    public Author(String name) {
        this.name = name;
    }
}
@Data
@NoArgsConstructor
@MappedSuperclass
public abstract class Article {
    @Id
    @GeneratedValue
    private Integer id;

    private String name;

    @ManyToMany(cascade = CascadeType.MERGE)
    private Set<Author> authors = new HashSet<>();

    public Article(String name, Author... authors) {
        this.name = name;
        addAuthors(authors);
    }

    public void addAuthors(Author... authors) {
        if (authors != null) {
            this.authors.addAll(Set.of(authors));
        }
    }

    @Override
    public String toString() {
        return getClass().getSimpleName() + "{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}

@NoArgsConstructor
@Entity
public class FirstTypeArticle extends Article {
    public FirstTypeArticle(String name, Author... authors) {
        super(name, authors);
    }
}

@NoArgsConstructor
@Entity
public class SecondTypeArticle extends Article {
    public SecondTypeArticle(String name, Author... authors) {
        super(name, authors);
    }
}

然后您将获得以下自动生成的表:

AUTHOR
FIRST_TYPE_ARTICLE
FIRST_TYPE_ARTICLE_AUTHORS
SECOND_TYPE_ARTICLE
SECOND_TYPE_ARTICLE_AUTHORS
NEWSPAPER
NEWSPAPER_AUTHORS
NEWSPAPER_FIRST_TYPE_ARTICLES
NEWSPAPER_SECOND_TYPE_ARTICLES

用法示例

添加报纸:

newspapers = newspaperRepo.saveAll(List.of(
        new Newspaper("newspaper1"),
        new Newspaper("newspaper2")
));

添加作者:

newspaperRepo.save(newspapers.get(0).addAuthors(
        new Author("author1"),
        new Author("author2")
));

获得作者:

authors = authorRepo.findAll();

添加文章:

newspaperRepo.save(newspapers.get(0).addArticles(
        new FirstTypeArticle("article1", authors.get(0), authors.get(1)),
        new SecondTypeArticle("article2", authors.get(1))
));