将来自 spring @Component
和 JPA @Entity
的注释放在同一个类上是错误的想法吗?为什么需要它是在 JSF 页面上使用这个类,它还描述了表结构。原因是为了避免将实体对象映射到将成为表示层的某个值对象。
这是一些反模式吗?你有更好的解决方案吗?
最佳答案
Is it wrong idea to put annotation from spring @Component and JPA @Entity on the same class.
这是 Controller 和模型的紧耦合。
Why It is needed is to use this class on JSF page and also It describes the table structure. The reason is to avoid mapping Entity object to some value object which will be the presentation layer.
你把事情搞得太复杂了。您不需要将它映射到一个全新的值对象类,您只需将该实体设为 Controller 的一个属性即可。
例如
@Component // Or CDI @Named or JSF @ManagedBean
public class Controller {
private Entity entity;
@AutoWired // Or CDI @Inject or JSF @EJB
private EntityService service;
@PostConstruct
public void init() {
entity = new Entity(); // In case "new entry" is required.
}
public void save() {
service.save(entity);
}
public Entity getEntity() { // No setter required.
return entity;
}
}
并在 JSF 组件中按如下方式引用它:
<h:inputText value="#{controller.entity.name}" />
<h:inputText value="#{controller.entity.value}" />
<h:inputText value="#{controller.entity.something}" />
...
<h:commandButton value="save" action="#{controller.save}" />
看,不需要在 Controller 中复制所有实体的属性。
另见:
关于java - 同一个类上注解Entity和Component是不是错了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18426778/