Hi all,
I’m writing a Vaadin application using JPA for the data model. As far as now i’ve just needed to manipulate signle entity using Item.getProperty(); using JPAContainer.
First a little digression: JPAContainer need a Provider that need EntityManager, as now i’m getting it from a thread local:
MyApplication.getCurrent().getEntityManager();
that give me a singleton instance (for the session).
The singleton instance is created in the init() :
@Override
protected void init(VaadinRequest request) {
EntityManagerFactory factory = Persistence
.createEntityManagerFactory("EScrumDataModel");
entityManager = factory.createEntityManager();
}
Is this the right way?
Now i need to work on multiple entities:
@Entity
@Table(name="USER")
public class User {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private long id;
@Column(name="name")
private int name;
@Column(name="age")
private int age;
@ManyToOne()
@JoinColumn(name = "group_id")
private Group group;
//lot of code omitted
}
@Entity
@Table(name="GROUP")
public class Group{
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private long id;
@Column(name="name")
private int name;
//lot of code omitted
}
Now i need the oldest user in the group, so i need a ServiceLayer (since i cant execute a query inside the entity).
I’d like to introduce Spring, i still dont get it at all, but i know it can inject the EntityManager in a class (even if i still dont know how and when):
public class GroupService {
@PersistenceContext
private EntityManager em;
public User getOldestUser(Group group) {
em.createQuery(...);
...
return user;
}
}
(i’m a bit confused about the configurations to make this work…but)
How do i get an instance of the service ?
Do i need to create a method in MyApplication? so i can:
MyApplication.getCurrent().getGroupService();
but this way MyApplication must know all the entities type the app use.
Any tips?