This example is constructed to illustrate some advanced configurations of Hibernate and their related mechanisms during the test:
There are three classes: category. Java, prodcuct. Java, and configurationtest. java. The third class is used for testing.
Category. Java code:
- Package unsaved_value;
- Import ......
- Public class category {
- Private integer ID;
- Private string name;
- Private string description;
- Private set Products;
- Public category (){
- Id = NULL;
- Name = NULL;
- Description = NULL;
- Products = new hashset ();
- }
- Public void addproduct (product P ){
- Products. Add (P );
- }
- // ********** Setter and getter
- ........
- }
Product. Java code:
- Package unsaved_value;
- Public class product {
- Private integer ID;
- Private string name;
- Private category;
- Private string description;
- Public Product (){
- }
- // ******* Getter and setter
- .........
- }
Configurationtest. Java
- Public void testsave () throws exception {
- CATEGORY Category = new category ();
- Category. setname ("Java programming book 2 ");
- Category. setdescription ("programming classic books 2 ");
- Product pro = new product ();
- Pro. setname ("Java programming ideology 2 ");
- Pro. setdescription ("Chinese Version 4 2 ");
- Pro. setcategory (category );
- Category. addproduct (Pro );
- Transaction Tx = session. begintransaction ();
- Assert (session! = NULL) :( "session is null ");
- Session. Save (category );
- TX. Commit ();
- }
Category represents the product catalog, while product represents the product. Obviously, category and product are one-to-multiple relationships. There are two ways for hibernate to map one-to-multiple relationships. One is one-to-one, and the other is two-way. Compared with the two, the two-way one-to-multiple advantage is reflected in two aspects: first, it is also very obvious that because of the two-way association, we will be more convenient in actual business logic, for example, we can retrieve all the products under a category and find out which product belongs. Second, bidirectional relationships are more advantageous in accessing databases than unidirectional ones. This will be discussed later in inverse.
. Two-way Association is the only "disadvantage" of one-way Association, because two-way association needs to write more ing files than one-way Association. This is not a problem. Two-way Association is used to map these two databases:
- Category. HBM. xml:
- Version = "1.0" encoding = "UTF-8"?>
- Http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd>
- <Hibernate-mapping package = "unsaved_value">
- <Class name = "category" table = "category">
- <ID name = "ID" column = "ID">
- <Generator class = "native">