java 具有复合主键的 JPA 存储库/服务设计
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15850064/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JPA Repository / Service design with composite primary keys
提问by PWillms
I designed the following database tables:
我设计了以下数据库表:
- "article" with "materialID" as primary key.
- "supplier" with "supplierID" as primary key.
- "procurement" with "materialID" and "supplierID" as composite primary key (including foreign key relationships to tables 1 and 2).
- 以“materialID”作为主键的“文章”。
- “supplier”以“supplierID”为主键。
- 以“materialID”和“supplierID”作为复合主键的“采购”(包括与表1和表2的外键关系)。
Now I want to deal with them in Spring using JPA. First, I will demonstrate the approach working for the entities "article" and "supplier".
现在我想在 Spring 中使用 JPA 处理它们。首先,我将演示适用于实体“文章”和“供应商”的方法。
Entity class:
实体类:
@Entity
public class Article {
@Id
private String materialID;
@Column(nullable = false)
private String shortText; }
JpaRepository for the entity:
实体的 JpaRepository:
@Repository
public interface IArticleRepository extends JpaRepository<Article, String>
{
List<Article> findByShortTextLike(String shortText); //just another search method
}
Service providing transactions to the user:
向用户提供交易的服务:
@Service
public class ArticleService implements IArticleService {
@Autowired
private IArticleRepository articleRepository;
@Override
@Transactional(readOnly = true)
public Article getArticleByID(String id) {
return this.articleRepository.findOne(id);
}
@Override
@Transactional
public Article createArticle(String id, String shortText) {
Article article = new Article();
article.setMaterialID(id);
article.setShortText(shortText);
this.articleRepository.save(article);
return article;
}
Unfortunately, this system does not seem to work properly for the "procurement" entity. I have already read about the composite primary key challenge and wrote this entity class.
不幸的是,这个系统对于“采购”实体似乎不能正常工作。我已经阅读了复合主键挑战并编写了这个实体类。
@Entity
@Table
public class Procurement implements Serializable {
private static final long serialVersionUID = 4976268749443066505L;
@EmbeddedId
private ProcId pk;
The class of the embedded id looks like this.
嵌入 id 的类看起来像这样。
@Embeddable
public class ProcId implements Serializable {
private String materialID;
private int supplierID;
}
Are the entity and the id classes correct? Has anyone an idea how to change the repository / service in order to work with the composite primary key?
实体和 id 类是否正确?有没有人知道如何更改存储库/服务以使用复合主键?
采纳答案by skirsch
Your ProcId
should be defined like this:
你ProcId
应该像这样定义:
@Embeddable
public class ProcId implements Serializable {
@ManyToOne(optional = false)
private Article article;
@ManyToOne(optional = false)
private Supplier supplier;
}