The
example used for ONE-TO-MANY relationship is as follows: Order and Order Items.
Order
class has a Set of Order Items, and the OrderItem has the Order object to which
this order item belongs to.
public class Order {
@OneToMany(mappedBy = "Order")
private Set<OrderItem> orderItems = new HashSetOrderItem>();
}
public
class OrderItem{
@ManyToOne
@JoinColumn(name = "BOI_ORDER_ID")
private Order Order;
}
1.
As you see OneToMany
does not mention the fetch type. This is because, OPEN JPA, by default, lazy
loads the Collections; so does Hibernate 3.0.
2.
Fetch Type Eager makes
sense for most of the ManyToOne, however, in case the One Side i.e. the parent
Entity, is a big object and it is not required for processing most of the times,
it would be better to set the FetchType=Lazy, as follows
@ManyToOne(fetch = FetchType.LAZY)
3.
Setting FetchType Lazy
also makes sense for very large attributes, typically clobs. This can be done
with the Basic annotation e.g. a contract document of a order, let us assume it
a clob in the db.
public class Order {
@Basic(fetch = FetchType.LAZY)
@Coulmn(name =”ORDER_CONTRACT)
private String contract;
}
4.
JPA default assumes
that the foreign key is a Primary Key in the reference table. However, though
not often, there are foreign keys that are Unique in the reference table. To
accommodate this, JPA provides referenceColumnName in JoinColumn annotation.
E.g. If the social security number is a unique key in the
employee table, EMP_SSN_ID, (not a Primary key for obvious reasons) , this key
is reference to a table that gather data to be sent to Social Security Dept.
for processing. In this case, the social security number will be a foreign key
in the ssn_dept table.
The Many-to-One side of this relationship will be defined as:
@ManyToOne
@JoinColumn(name="SSN_ID", referencedColumnName="EMP_SSN_ID")
private Employee employee;
5.
Many-to-One and
CascadeType: In some scenarios it makes sense in setting CascadeType to Persist
on a Many-to-One. This means when a many-to-one is persisted, the One side is
automatically persisted. E.g. Order and a Customer, when an Order is Persisted
it makes sense that the customer is automatically persisted too.
Example:
public class Order {
@OneToMany(mappedBy = "order")
private Set<Customer>
customers = new HashSet<Customer>();
}
6.
Difference between
optional and nullable: The main difference is the scope at which these are
applied. Optional is validation before the data is sent to Database, where as
nullable is applied to a database column when database tables are generated
from JPA.
The optional throws InvalidSateException.
This is how the
annotation is applied, please not optional is part of Basic and nullable is
part of column.
public class Customer{
@Basic(optional=false)
@Column(name = “CUST_NAME”, nullable=true)
private String custName;
}
Note that in the absence of the Basic annotation, if custName
contains null, it is passed to the database and a database exception will be
thrown at the time of insert/update.
The nullable will have no effect on insert/update, it will only
play a role when the db table is created.
Most reverse engineering tools, do not generate the Basic
(nullable=false) or Column(nullabe=true) for not null columns in the db.
7.
Validation of
Attributes Before sending to Database: The optional validation can be done
using @Basic as mentioned earlier. For any other validation (size etc.), JPA
does not provide any annotations. If this is a requirement, use Bean Validation
API, jsr 303.
8.
Consequences of Lazy
Loading outside the Entity Manager Context:
The consequences depend on the underline implementation of lazy
initialization. Hibernate uses proxy objects at the runtime, whereas openjpa
enhances the entity classes before runtime.
Hibernate throws LazyInitializationException, while openjpa
returns null and hence a NPE is likely to be thrown if there is no check for
null.
Consider the code below in the context of our
order->orderItem example.
Set<OrderItems> sitems = order.getOrderItems() ;
System.out.println(
items.size() );
When the code above is executed
outside of Entity Manager, (and of course Items were not retrieved when
Order was returned from entity manager), Hibernate will throw
LazyInitializationError; while openjpa will return null, and hence a NPE will
be thrown.
A good practice for retrieving collections outside of the Entity
Manager context is using NamedQueries.
9.
Difference between
persist and merge: This is significant for Hibernate users, who typically use
saveOrUpdate. In case of saveOrUpdate, Hibernate attaches the object (passed to
the method) to the context. In case of JPA, persist attaches the object (passed
to the method) to the context whereas merge does not. The object returned by
merge is attached to the context.
It can be better explained with this example.
Order order = new
Order(); // A new order is created.
order.setCustName(“ ABC
Inc.”);
entityManager.persist(order);
System.out.println(“ New
Order id: “ + order.getId()); // ID is generated at the time of insert.
In the above example, if the id generated was 1000, it will
print
New Order id : 1000
Now let us make some change to the above
code, and use merge as follows.
Order order = new
Order(); // A new order is created.
order.setCustName(“ ABC
Inc.”);
Order ordRef = entityManager.merger(order);
System.out.println(“ New
Order id: “ + order.getId()); // ID is generated at the time of insert.
System.out.println(“ New Order Ref id: “ +
ordRef.getId()); // ID is generated at the time of insert.
Again, if the id generated was 1000, it will print
New Order id: 0 (If Id
was initialized as an instance field )
New Order Ref id: 1000
Note: In case of persist, the object order was synchronized with
the db, where as in case of merge, the order object was copied, and the ordRef
object , the objet returned had the id, since this returned object was the
object from the context.
The best practice for save/update is as follows: (sOrder is the
object to be save/updated)
Order rOrder = em.find(Order.class, sOrder.getId());
if (rOrder == null) {
em.persist(sOrder);
}
else {
em.merge(sOrder);
}
10.
TableGenerator for ID
Column: I prefer this over all other ID generators, for various reasons. First
and foremost it is truly database independent. Secondly the sequence’s current
status is accessible and visible any time.
This is how it works:
Generate a table in the db, with a minimum of two columns, key and
value. Key is similar to the sequence name and value is the current value.
create table seq_id_gen
(tab_key varchar2(100), key_value number);
Insert into seq_id_gen
(“ORD_PK”, 1);
Insert into seq_id_gen
(“ORD_ITEM_PK”, 1);
Now for Order and OrderItem, the Id annotations will be:
public class Order {
@Id
@GeneratedValue(strategy = GenerationType.TABLE, generator = "ORD_PK")
@TableGenerator(name = "ORD_PK", table = "SEQ_ID_GEN", pkColumnName = "TAB_ _KEY", valueColumnName = "KEY_VALUE", pkColumnValue = "ORD_PK", allocationSize = 10)
@Column(name = "ORD_ID")
private long ordId;
}
Please note the values of: pkColumnName
(The column that stores the seq name)
valueColumnName: (The column that stores
the current value of the sequence)
pk_column_value: Identifies the row that
will be used.
allocation_size is the cached number of
sequence numbers.
public class
OrderItem{
@Id
@GeneratedValue(strategy = GenerationType.TABLE, generator = "ORD_ITEM_PK")
@TableGenerator(name = "ORD_ITEM_PK", table = "SEQ_ID_GEN", pkColumnName = "TAB_ _KEY", valueColumnName = "KEY_VALUE", pkColumnValue = "ORD_ITEM_PK", allocationSize = 10)
@Column(name = "ORD_ID")
private long ordId;
}
It is not mandatory
to have the generator name same as the pkColumnValue, I just find it convenient to track.
What happens when a
new record is persisted?
As you would expect, for Order, 1 is assigned to order.id and
the key_value is updated to 11 fro the row having tab_key = ORDER_PK.
OPEN JPA selects the
value using Select ..for update when available or locks the table is
required.
In either case the row
is locked and hence does not pose any concurrency issues.
Also note, if the
INSERT fails (in this case for Order) then the corresponding sequence number
is lost, it is not rolled back.
No comments:
Post a Comment