简体   繁体   English

字符串解耦和字段名称

[英]string decoupling and field names

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 : 我有许多域/业务对象,当在hibernate标准中使用时,字段名称将其引用为字符串,例如:

Criteria crit = session.createCriteria(User.class);
Order myOrdering = Order.desc("firstname");
crit.addOrder(myOrdering);

Where firstname is a field/property of User.class . firstnameUser.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). 有没有其他方式,我缺少,需要较少的工作(我可能会忘记保持Enum)。

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. 但是有一个更好的解决方案如何尽早发现问题:如果使用命名查询(javax.persistence.NamedQueries),只要你的实体被Hibernate处理,你就会得到所有的查询,所以基本上它会在服务器启动期间发生。 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. 希望能帮助到你。

This is one of the things that irritates me about Hibernate. 这是让我对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. 在任何情况下,我在过去使用两种机制中的一种解决了这个问题,要么自定义用于从Hibernate配置文件生成基类的模板,要么查询我的Hibernate类以获取注释/属性并生成适当的枚举,类,常量,等等。 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. 它为构建过程增加了一个步骤,但IMO正是我所需要的。 (The last few projects I haven't done it, but for large, multi-dev things I really like it.) (最后几个项目我还没有完成它,但对于我非常喜欢的大型多开发项目。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM