Emax
Emax

Reputation: 1403

Hibernate @ManyToMany get a list of key instead of entities

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

Upvotes: 0

Views: 32

Answers (1)

muhammed ozbilici
muhammed ozbilici

Reputation: 772

Answer is @ElementCollection. check here please;

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

Upvotes: 1

Related Questions