Java EE, creating entity object with one to one association
I have two entitys, A and B. A has a one to one relationship of B.
class A {
String aValue;
B b;
}
class B {
String bValue;
}
The class B stuff are already pre populat开发者_C百科ed. Now, a user on a website selects what B he wants to submit. On the server we get an Id of what B that was.
The Question: How do I create a new A, without actually do a DB query asking for the B that has this id. I mean, the A table in database only has a id reference. One should be able to set that Id without fetching the B.
If you are using JPA and Assuming the following:
@Entity
@Table(name="A")
class A {
@Id
@Column(name="id")
private int id;
String aValue;
@OneToOne
B b;
// Getters, setters and other stuff
}
@Entity
@Table(name="B")
class B {
@Id
@Column(name="id")
private int id;
Integer Id;
String bValue;
// Getters, setters and other stuff
}
If you now the id of entity B. You can simply make persist as follows:
B b = new B();
b.setId(1000); //Assuming that you know the id.
//There is no necessary fill all the object. Just the PK is needed.
A a = new A();
a.setId(100);
a.setAValue("nothing");
a.setB(b);
em.persist(a);
I have tested this with Hibernate as Persistence Provider. If you are using other ORM please specify it.
You should take a look at JPA 2.0.
With JPA you can define a relationship between 2 entites to automatically retrieve the related entities.
精彩评论