java - 同一个类上注解Entity和Component是不是错了

标签 java spring hibernate jsf jpa

将来自 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/

相关文章:

java - long : - Postgresql, Hibernate, Spring 类型的错误值

java - 映射我的 bean 时 Hibernate 配置文件中出现异常

java - 如何选择最大连接池大小?

java - 有什么方法可以进一步优化 Java 反射方法调用?

java - 无法识别 Hibernate 符号 @id @column

java - Spring 和 Java 中的 Websocket

java - 如何解决hibernate中乐观锁(Versioning)的问题?

Java时间不同步

Java:尝试创建一个存储的数据库

java - Linux 上的 shell 脚本无法识别新行