Home > Mobile >  Hibernate @ManyToMany get a list of key instead of entities
Hibernate @ManyToMany get a list of key instead of entities

Time:10-29

The database schema is composed like this:

CREATE TABLE `pages`
  (
     `identifier`  INT(11) NOT NULL auto_increment,
     `title`       VARCHAR(150) NOT NULL,
     PRIMARY KEY (`identifier`),
  )

CREATE TABLE `tags`
  (
     `identifier`  INT(11) NOT NULL auto_increment,
     `name`        VARCHAR(50) NOT NULL,
     PRIMARY KEY (`identifier`)
  )

CREATE TABLE `pages_tags`
  (
     `page` INT(11) NOT NULL,
     `tag`  INT(11) NOT NULL,
     KEY `pagetag_page` (`page`),
     KEY `pagetag_tag` (`tag`),
     CONSTRAINT `pages_tags_ibfk_1` FOREIGN KEY (`page`) REFERENCES `pages` (
     `identifier`),
     CONSTRAINT `pages_tags_ibfk_2` FOREIGN KEY (`tag`) REFERENCES `tags` (
     `identifier`)
  )

Each page can have many tags and each tag can be assigned to many pages (ManyToMany), On the page entity class, the many-to-many relationship is defined like this

@ManyToMany
@JoinTable(
    name = "pages_tags",
    joinColumns = { @JoinColumn(name = "page", nullable = false) },
    inverseJoinColumns = { @JoinColumn(name = "tag", nullable = false) }
)
private List<Tag> tags;

How can I get just the primary key instead of the whole tag entity? I know I could use a @NamedQuery but it would be much better if in the entity class I could add an integer list field

@NamedQuery(name = "Page.findTags", query = "SELECT p.tag FROM PageTag p WHERE p.page = :identifier")

In a nutshell instead of getting a list of tag entities I would like hibernate to automatically generate a list of integers containing the pages_tags.tag field for that page

I'm using: spring-boot-starter-data-jpa 3.0.0-RC1

CodePudding user response:

Answer is @ElementCollection. check here please;

https://docs.jboss.org/hibernate/orm/4.1/manual/en-US/html_single/#d5e5405

CodePudding user response:

Assuming that you have the following mapping:

@Entity
@Table(name = "pages")
public class Page {
    @Id
    @Column(name = "identifier")
    private Long id;

    @Column(name = "title")
    private String title;

    @ManyToMany
    @JoinTable(
        name = "pages_tags",
        joinColumns = @JoinColumn(name = "page", nullable = false),
        inverseJoinColumns = @JoinColumn(name = "tag", nullable = false)
    )
    private List<Tag> tags;

    // ...
}

@Entity
@Table(name = "tags")
public class Tag {
    @Id
    @Column(name = "identifier")
    private Long id;

    @Column(name = "name")
    private String name;

    // ...
}

you can use the following query:

@NamedQuery(
    name = "Page.findTags",
    query = "select t.id from Page p join p.tags t where p.id = :id"
)

List<Long> tagIds = em.createNamedQuery("Page.findTags")
                .setParameter("id", 2L).getResultList();
  • Related