字符串解耦和字段名称
我有许多域/业务对象,当在休眠条件中使用时,它们由字段名称作为字符串引用,例如:
Criteria crit = session.createCriteria(User.class);
Order myOrdering = Order.desc("firstname");
crit.addOrder(myOrdering);
其中 firstname 是 User 的字段/属性。类。
我可以手动创建一个枚举并将所有字符串存储在其中;有没有其他我缺少的方法并且需要更少的工作(我可能会忘记维护枚举)。
I have a number of domain/business objects, which when used in a hibernate criteria are referenced by the field name as a string, for example :
Criteria crit = session.createCriteria(User.class);
Order myOrdering = Order.desc("firstname");
crit.addOrder(myOrdering);
Where firstname is a field/property of User.class.
I could manually create an Enum and store all the strings in there; is there any other way that I am missing and requires less work(I'll probably forget to maintain the Enum).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
恐怕没有什么好的办法。
即使您决定使用反射,只有在查询运行时您才会发现问题。
但是有一个更好的解决方案如何及早发现问题:如果您使用命名查询(javax.persistence.NamedQueries),一旦您的实体被 Hibernate 处理,您将立即编译所有查询,所以基本上它会发生在服务器启动期间。因此,如果某个对象发生更改而破坏了查询,您会在下次启动服务器时知道它,而不是在实际运行查询时知道。
希望有帮助。
I'm afraid there is no a good way to do that.
Even if you decide to use reflections, you'll discover the problem only when the query will run.
But there is a little bit better solution how to discover the problem early: if you use the Named Queries (javax.persistence.NamedQueries) you'll get all your queries compiled as soon as your entities are processed by Hibernate, so basically it will happen during the server's start-up. So if some object was changed breaking the query, you'll know about it the next time you start the server and not when the query is actually run.
Hope it helps.
这是 Hibernate 让我恼火的事情之一。
无论如何,我过去使用两种机制之一解决了这个问题,要么自定义用于从 Hibernate 配置文件生成基类的模板,要么询问我的 Hibernate 类的注释/属性并生成适当的枚举、类、常量,等等。这非常简单。
它为构建过程增加了一个步骤,但在我看来,这正是我执行此操作时所需要的。 (最近的几个项目我还没有完成,但对于大型的、多开发的事情我真的很喜欢它。)
This is one of the things that irritates me about Hibernate.
In any case, I've solved this in the past using one of two mechanisms, either customizing the templates used to generate base classes from Hibernate config files, or interrogating my Hibernate classes for annotations/properties and generating appropriate enums, classes, constants, etc. from that. It's pretty straight-forward.
It adds a step to the build process, but IMO it was exactly what I needed when I did it. (The last few projects I haven't done it, but for large, multi-dev things I really like it.)