我们有一个 pojo 需要有一个整数列表。例如,我创建了一个Message
pojo,并希望关联一个列表groupIds
(这些 id 需要在 UI 中查询和显示)。所以理想情况下,我们希望能够做这样的事情:
Message msg = em.find(Message.class, 101);
List<Integer> groupIds = msg.getGroupIds();
我的印象是这只需要一个带有 JPA 的 pojo,但是根据这里的讨论,我需要创建第二个 pojo,因为 JPA 是根据对象而不是原始类型工作的。
从该讨论中,我尝试了以下示例代码,但出现错误openjpa-1.2.3-SNAPSHOT-r422266:907835 fatal user error: org.apache.openjpa.util.MetaDataException: The type of field "pojo.Group.messageId" isn't supported by declared persistence strategy "ManyToOne". Please choose a different strategy.
DDL:
创建表“应用程序”。“消息”( "MESSAGE_ID" INTEGER NOT NULL 始终作为标识生成(从 1 开始,按 1 递增), “作者” CHAR(20) 非空 ); ALTER TABLE "APP"."MESSAGE" 添加约束 "MESSAGE_PK" PRIMARY KEY ("MESSAGE_ID"); 创建表“APP”。“GROUP_ASSOC”( "GROUP_ID" INTEGER NOT NULL, “MESSAGE_ID”整数非空 ); ALTER TABLE "APP"."GROUP_ASSOC" 添加约束 "GROUP_ASSOC_PK" PRIMARY KEY ("MESSAGE_ID", "GROUP_ID"); ALTER TABLE "APP"."GROUP_ASSOC" 添加约束 "GROUP_ASSOC_FK" FOREIGN KEY ("MESSAGE_ID") 参考 "APP"."MESSAGE" ("MESSAGE_ID");
POJO:
@Entity
@Table(name = "MESSAGE")
public class Message {
@Id
@Column(name = "MESSAGE_ID")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long messageId;
@OneToMany
private List<Group> groups = new ArrayList<Group>();
@Column(name = "AUTHOR")
private String author;
// getters/setters ommitted
}
@Entity
@IdClass(pojo.Group.GroupKey.class)
@Table(name = "GROUP_ASSOC")
public class Group {
@Id
@Column(name = "GROUP_ID")
private Long groupId;
@Id
@Column(name = "MESSAGE_ID")
@ManyToOne
private Long messageId;
public static class GroupKey {
public Long groupId;
public Long messageId;
public boolean equals(Object obj) {
if(obj == this) return true;
if(!(obj instanceof Group)) return false;
Group g = (Group) obj;
return g.getGroupId() == groupId && g.getMessageId() == messageId;
}
public int hashCode() {
return ((groupId == null) ? 0 : groupId.hashCode())
^ ((messageId == null) ? 0 : messageId.hashCode());
}
}
// getters/setters ommitted
}
测试代码:
EntityManager em = Persistence.createEntityManagerFactory("JPATest").createEntityManager();
em.getTransaction().begin();
Message msg = new Message();
msg.setAuthor("Paul");
em.persist(msg);
List<Group> groups = new ArrayList<Group>();
Group g1 = new Group();
g1.setMessageId(msg.getMessageId());
Group g2 = new Group();
g2.setMessageId(msg.getMessageId());
msg.setGroups(groups);
em.getTransaction().commit();
这一切看起来很荒谬——3个类(如果你包括GroupKey复合标识类)来模拟整数列表——难道没有更优雅的解决方案吗?