@Entity
public class Husband implements Serializable {
@Id
private int id;
private String name;
@OneToOne
private Wife wife;
}
@Entity
public class Wife implements Serializable {
@Id
private int id;
private String name;
@OneToOne(mappedBy="wife")
private Husband husband;
}
Serializable
in broad term?Serializable
interface?Serialization, in broad terms, is the way Java provides developers to persist the state of any object to a persistent store.
If a developer wants that for some reason instance of his coded class should be persisted to a backing store, then the class needs to be declared as implementing Serializable.
The above code represents a One to One relationship between a Husband and a Wife. Which basically means that each wife is related to one husband and each husband is related to one wife. :-) Also in the above relationship, the Husband is the master of the relationship [in Entity-Relationship terms] and that is why Wife says that it is mapped/associated to Husband by the Husband and not the other way around. Which means Husband identifies its wife and not the other way around.
1) The Serializable
interface is just a marker. It means that objects can be serialized, i.e. they can be represented as a bit string and restored from that bit string.
For example, both of your classes are serializable because they can be represented as a bit string (or regular string). On the other hand, a class that represents a file handle given out by the operating system can not be serialized: As soon as the program is finished, that handle is gone, and there is no way to get it back. Reopening the file by file name is not guaranteed to work, since it may have been deleted/moved/changed permissions in the meantime.
2) Serializing objects that don't implement the Serializable interface will result in a NotSerializableException
being thrown.
3) According to the documentation:
mappedBy
This element is only specified on the inverse (non-owning) side of the association.
The interface Serializable helps to persist the state of an object instance.
According to the jpa specification:
"If an entity instance is to be passed by value as a detached object (e.g., through a remote interface), the entity class must implement the Serializable interface" - JSR 220 Persistence - see 2.1 Requirements on the Entity Class
According to the java ee documentation:
"The field that owns the relationship. This element is only specified on the inverse (non-owning) side of the association." - Java EE 6 Documentation
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