Question

Recently I had discussion with my friend regarding usage of Spring @Autowire annotation on entity(JPA) classes.

In our project we are using @Autowire annotaion to inject Entity but my friend suggesting not to use @Autowire annotaions on entity classes. When I asked why? He dont have the proper answer for that. So i just wanted to know are there any disadvantages using @Autowire annotaion on entity classes.

Also please explain when to go for @Autowire annotaion or not with example.

Thank in advance.

Was it helpful?

Solution

@Entity and @Autowire are not interchangeable.

@Entity annotation indicates that the JavaBean is a persistent entity.This is actually a JPA annotation and not a Spring Annotation.
@Entity will be used in the sessionFactory by the packagesToScan poroerty.

@Autowired: inject a resource by-type, i.e. by the class or by the interface of the annotated field or contractor. See my answer Inject and Resource and Autowired annotations
@Autowired is used to inject dependencies as an alternative to setting it via xml configurations

Maybe this answer will help you understand Hibernate - spring annotated entities not scanned from within jar

UPDATE: Following the comment bellow:
Company is your domain object, so you don't need to use spring in this case.

<bean id="company" class="xxx.Company"/>

The above will return the same instance with @autowire.
Even if you switch to scope="prototype" I don't see any reason to use spring for that. You should have a service that will be used to CRUD company e.g. CompanyService, this service will be a single tone so you will use @Autowire to inject it to the controller and it will use your JPA framework to implement CRUD's

To create a new company you will use:

Company c = new Company  //this probably will  be binded from your ui form 
companyServic.saveOrUpdate(c);

See the following answer spring rest service - hibernate dao - annotations - pojo - namedqueries. For common practice of DAO and services.

OTHER TIPS

@Autowire is an annotation used to perform a dependency injection, its almost similar to the standard @Inject you can take a look at the spring reference manual to see the difference between those two annotations.

@Entity is a part of the jpa framework its used to mark a class as persistent, spring does not implement an equivalent annotation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top