Is it wrong idea to put annotation from spring @Component
and JPA @Entity
on the same class. 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.
Is this some anti-pattern ? Do you have any better solution ?
We can use @Component across the application to mark the beans as Spring's managed components. Spring will only pick up and register beans with @Component, and doesn't look for @Service and @Repository in general. @Service and @Repository are special cases of @Component.
Interfaces are annotated with @Component annotation in spring IoC/DI.
@Repository @Service and @Controller are serves as specialization of @Component for more specific use on that basis you can replace @Service to @Component but in this case you loose the specialization.
@Component and @ComponentScan are for different purposes. @Component indicates that a class might be a candidate for creating a bean. It's like putting a hand up. @ComponentScan is searching packages for Components.
Is it wrong idea to put annotation from spring @Component and JPA @Entity on the same class.
This is tight-coupling of the controller and the model.
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.
You're overcomplicating things. You do not need to map it to a whole new value object class or so, you can just make the entity a property of the controller.
E.g.
@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;
}
}
and reference it as follows in JSF components:
<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}" />
See, no need to copy all entity's properties in the controller.
There's no pretty way of doing what you want since JPA doesn't use the Spring container to instantiate its entities. Think of JPA as a separate ORM container that instantiates and manages the lifecycle of entities (completely separate from Spring) and does DI based on entity relationships only. Ravi Thapliyal
Bean injection inside a JPA @Entity
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With