There are different starting points for establishing a domain model and a relational data model.
Domain model (object-oriented design): Consists of program code, which can improve the reusability of code and simplify programming by refining the granularity of the persisted class.
Relational data Model (database design): In the absence of data redundancy, you should minimize the number of tables and simplify the referential relationships between tables in order to increase the speed of data access.
In this article, we describe the relationship between worker (worker) and pay (compensation) as an example:
Hibernate divides the properties of a persisted class into two types:
value type: No OID, cannot be persisted independently, life cycle depends on the life cycle of the object of the owning persisted class.
entity type: There is an OID, which can be persisted independently and has an independent life cycle.
Obviously in the above example the worker is an entity type and pay is a value type. If we map these two classes to a table in a database instead of two tables based on the constituent relationships, then a single table query is faster than a multi-table query.
Hibernate uses the <component> element to map the composition relationship, which indicates that the pay attribute is a component of the Worker class and is called a component in Hibernate.
The following tests are done, starting with the new two Java classes:
public class Worker {
private Integer ID;
private String name;
Private pay;
Getters and Setters
} public
class pay {
private int monthlypay;
private int yearpay;
private int vocationwithpay;
Getters and Setters
}
Build the mapping file Worker.hbm.xml and map the constituent relationships in the mapping file:
<!--mapping Components--
<component name= "pay" class= "pay" >
<parent name= "worker"/>
<!-- Specify properties of components that make up the relationship-
<property name= "Monthlypay" column= "Monthly_pay" ></property>
<property Name= "Yearpay" column= "Year_pay" ></property>
<property name= "Vocationwithpay" column= "Vocation_ With_pay "></property>
</component>
To write a test program:
@Test public
void Testcomponent () {
worker worker = new Worker ();
Pay pay = new pay ();
Pay.setmonthlypay (+);
Pay.setyearpay (80000);
Pay.setvocationwithpay (5);
Worker.setname ("ABCD");
Worker.setpay (pay);
Session.save (worker);
}
Run the program and discover that a data table was generated worker:
and successfully inserted the record: