最近,我与我的朋友讨论过在实体(Spring @Autowire
)类中使用JPA
注释。
在我们的项目中,我们使用@Autowire
注释注入Entity
,但我的朋友建议不要在实体类上使用@Autowire
注释。当我问为什么?他没有正确的答案。所以我只是想知道在实体类上使用@Autowire
注释是否存在任何缺点。
另外,请通过示例说明何时进行@Autowire
注释。
提前感谢。
答案 0 :(得分:3)
@Entity和@Autowire不可互换。
@Entity注释表明JavaBean是一个持久化实体。这实际上是一个JPA注释,而不是一个Spring注释。
@Entity将由packagesToScan poroerty在sessionFactory中使用。
@Autowired:按类型注入资源,即通过类或注释字段或承包商的接口注入。请参阅我的回答Inject and Resource and Autowired annotations
@Autowired用于注入依赖项,作为通过xml配置设置它的替代方法
也许这个答案会帮助你理解 Hibernate - spring annotated entities not scanned from within jar
<强>更新强>
继评论如下:
公司是您的域对象,因此在这种情况下您不需要使用弹簧。
<bean id="company" class="xxx.Company"/>
以上内容将返回与@autowire相同的实例 即使你切换到scope =“prototype”,我也没有看到任何使用spring的理由。 你应该有一个将用于CRUD公司的服务,例如 CompanyService,这个服务将是单音,所以你将使用@Autowire将它注入控制器,它将使用你的JPA框架来实现CRUD的
要创建新公司,您将使用:
Company c = new Company //this probably will be binded from your ui form
companyServic.saveOrUpdate(c);
请参阅以下答案spring rest service - hibernate dao - annotations - pojo - namedqueries。 对于DAO和服务的通用实践。
答案 1 :(得分:2)
@Entity是jpa框架的一部分,用于将类标记为持久化,spring不实现等效的注释。