JPA:Map <entity1,set <entity2>&gt;可能?

时间:2016-04-06 03:14:11

标签: java jpa

我没有在任何地方看到一个例子,所以我不确定这是可能的。但基本上,我试图看看我是否可以将实体中的字段绑定到

   Map<Skill,Set<Rating>> ratings;


CREATE TABLE Worker (
  ID         BIGINT PRIMARY KEY,

);

CREATE TABLE Skill (
  ID   BIGINT PRIMARY KEY,
  name VARCHAR(32) NOT NULL,
  UNIQUE (name)
);

CREATE TABLE WorkerSkillRating (
  ID       BIGINT PRIMARY KEY,
  WorkerID BIGINT NOT NULL,
  SkillID  BIGINT NOT NULL,
  Rating   INT,
  FOREIGN KEY (WorkerID) REFERENCES Worker (ID),
  FOREIGN KEY (SkillID) REFERENCES Skill (ID),
  FOREIGN KEY (Rating) REFERENCES Rating (ID)
);

CREATE TABLE Rating (
  ID       BIGINT PRIMARY KEY,
  score    TINYINT NOT NULL,
  comments VARCHAR(256)
);

实体

@Entity
public class Skill {

    @Id
    private Long id;

    private String name;


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

    public Skill() {
        this.id = Math.abs( new Random().nextLong());
    }

}


@Entity
public class Worker {

    @Id
    private Long id;

    // The open question
    public Map<Skill, Set<Rating>> ratings;

}

@Entity
public class Rating {

    @Id
    private Long id;
    private Byte score;
    private String comments;

}

2 个答案:

答案 0 :(得分:1)

根据JSR-0038 JPA规范。使用Map时,只允许以下组合:基本类型,实体和可嵌入。

Map<Basic,Basic> 
Map<Basic, Embeddable> 
Map<Basic, Entity>

Map<Embeddable, Basic> 
Map<Embeddable,Embeddable>
Map<Embeddable,Entity> 

Map<Entity, Basic>
Map<Entity,Embeddable>
Map<Entity, Entity> 

我认为以你想要的方式进行可能的映射并不是很重要,但这不符合规范,并且大多数提供者都遵循它们,我认为映射根本不常见。

  

“工人有很多技能,他可能会获得很多评分   单一技能。 “

然后将技能类添加到Set<Ratings>,而不是直接嵌套在地图中作为其值。

答案 1 :(得分:0)

它可能无法用地图回答您的问题,但是......

看起来你的评级表是不必要的。

你可以改为

CREATE TABLE Worker (
  ID         BIGINT PRIMARY KEY,
);

CREATE TABLE Skill (
  ID   BIGINT PRIMARY KEY,
  name VARCHAR(32) NOT NULL,
  UNIQUE (name)
);

CREATE TABLE WorkerSkill (
  ID       BIGINT PRIMARY KEY,
  WorkerID BIGINT NOT NULL,
  SkillID  BIGINT NOT NULL,
  score    TINYINT NOT NULL,
  comments VARCHAR(256)
  FOREIGN KEY (WorkerID) REFERENCES Worker (ID),
  FOREIGN KEY (SkillID) REFERENCES Skill (ID)
);
  

注意我已将评级信息移至WorkerSkill表。

然后您可以按照以下方式映射您的实体

@Entity
public class Skill {

    @Id
    private Long id;

    private String name;

    // Getter setters const etc

}

@Entity
public class WorkerSkill {

    @Id
    private Long id;

    private int score;

    private String comments;

    @ManyToOne
    private Skill skill;

    @ManyToOne        
    private Worker worker;

    // Getter setters const etc

}


@Entity
public class Worker {

    @Id
    private Long id;

    @OneToMany
    public List<WorkerSkill> workerSkills = new ArrayList<>();

    // Getter setters const etc

}

然后,您可以使用worker.getWorkerSkill();

访问所有工作人员的技能