如何将 Builder 模式用于带有 JPA 的实体
我读到,当你有一个带有很多参数的类时,使用构建器模式很有用。我想知道如何使用构建器模式来实现实体。如果您能提供示例代码那就太好了。
I read that it's useful to use builder pattern when you have a class with a lot of parameters. I wonder how you can implement an entity using builder pattern. It would be great if you can provide sample code.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当然这是可能的,您只需为每个实体提供一个(可能是嵌套的)构建器即可。
这是一个有效的示例:
使用它的代码如下:
请记住,如果有的话,您必须排除自动生成的字段,例如主键(在此示例中
id
)。如果您想摆脱为每个实体创建构建器类的“样板”代码,我会推荐一个方便的库,例如 Lombok。然后,您只需注释您的实体即可获得您的构建器(甚至更多),也许需要花费一些额外的工作来排除 id 字段。
您应该看看 Project Lombok
不过,这里有一些代码测试此构建器(使用 Spring Boot 和 Hibernate 实现)。
存储库:
这里有一些测试:
Of course it is possible, you just have to provide a (possibly nested) Builder for every Entity.
Here is a working example:
The code to use it would be this:
Just keep in mind that you have to exclude auto-generated fields like the primary key (in this example
id
) if you have some.If you want to get rid of the "boilerplate" code for creating Builder classes for every Entity I would recommend a convenience library, something like Lombok. Then you will get your Builders (and even more) by just annotating your Entites, maybe it costs a little extra work to exclude the id fields.
You should take a look at Project Lombok
Nevertheless, here is some code to test this Builder (implemented with Spring Boot and Hibernate).
The repository:
And here are some tests: