How to make Unidirectional Relationship in EJB 3.0 Entity-Beans (JPA)?
For example Customer know about Order but Order has not any method for Customer. using (@OneToMany or @OneToOne or @ManyToMany)
Regards
How to make Unidirectional Relationship in EJB 3.0 Entity-Beans (JPA)?
For example Customer know about Order but Order has not any method for Customer. using (@OneToMany or @OneToOne or @ManyToMany)
Regards
Here's how you'd make a unidirectional @OneToMany
relationship using JPA 2.0:
@Entity
public class Customer {
@Id
@Column(name="cust_id")
private long id;
...
@OneToMany
@JoinColumn(name="owner_id", referencedColumnName="cust_id")
private List<Order> order;
...
}
@Entity
public class Order {
@Id
@Column(name="order_id")
private long id;
...
}
Relational database:
Customer:
+---------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+---------+---------+------+-----+---------+-------+
| cust_id | int(11) | NO | PRI | NULL | |
+---------+---------+------+-----+---------+-------+
Order:
+----------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------+---------+------+-----+---------+-------+
| order_id | int(11) | NO | PRI | NULL | |
| owner_id | int(11) | NO | MUL | NULL | |
+----------+---------+------+-----+---------+-------+
Leaving "uni-directional" aside for the moment, one could model a Customer-Order relationship as follows.
@Entity
public class Customer {
// ...
@Id @GeneratedValue
int id;
@OneToMany(cascade = CascadeType.ALL, mappedBy = "customer")
Set<Order> orders;
// ...
}
@Entity
public class Order {
// ...
@ManyToOne(optional = false)
Customer customer;
// ...
}
Here I'm assuming that each Order has exactly one Customer. In the database, the Order table would have a "customer_id" column with a foreign key to the Customer table's "id" column. The DDL would look something like the following.
CREATE TABLE Customer (
id INT NOT NULL,
...
PRIMARY KEY (id)
);
CREATE TABLE Order (
...
customer_id INT NOT NULL,
...
FOREIGN KEY (customer_id) REFERENCES Customer (id)
);
Although the Customer class contains a collection of orders, this doesn't actually affect the database structure in any way; it's just a convenient way of retrieving/managing orders that belong to the customer. For example, you can drop the "orders" member from Customer altogether and rely on queries to fetch these records instead.
The point I'm trying to make is that, from the perspective of the database, there really is no such thing as a "uni-directional" relationship. The example reverendgreen provided will produce Java classes where there is no direct way to get a Customer object from an Order object, but the resulting database structure will be identical (ignoring minor differences in column names). You can always find the customer for a given order by means of a query.