A tutorial on the mapping of collection class data structure in Java Hibernate framework _java

Source: Internet
Author: User
Tags arrays object model rollback set set

One, set mapping

1. Collection of small media
set mapping is also a basic mapping, but not often used in the development process, so do not need a deep understanding, only need to understand the basic methods of use, etc. in the development process encountered such problems can be queried to solve the problem. Corresponding set mapping it actually refers to mapping a collection in Java to a corresponding table, a collection object mapping, in Java there are four types of collections, sets, maps, lists, and ordinary arrays, which are very different from each other:
(1) Set, there can be no duplication of objects, the object is unordered;
(2) List, which can be in order with duplicate objects, between objects;
(3) Map, which appears as a pair of key values;
(4) array, which can be repeated, with order between objects.
The difference between them determines what kind of collection to use at development time, usually when the set is used at development time, the objects inside it are not needed, and you can use iterators to get internal objects. When these collections want to map to the corresponding relational model, they must use the mapping tags provided by hibernate,<set>, <list>, <map>, <array>.

2. Mapping Small Media
continue to discuss the relational model of set mapping, which refers to an object that corresponds to a collection of another object, which, when saved, saves the data collection to the corresponding table and saves the data to the datasheet according to the ID of the hibernate, if a separate table is assigned to the collection, Then the ID is assigned to the collection table, and the corresponding relational table is as follows:

3. class files
How the collection map is implemented through code, and then the specific analysis. This holds all the collections into a class, which we call Collectionmapping.java, and its corresponding internal code is as follows:

Package com.hibernate; 
Import java.util.List; 
Import Java.util.Map; 
 
Import Java.util.Set; 
  @SuppressWarnings ("Rawtypes") public class Collectionmapping {//id private int id; 
  public int getId () {return id; 
  The public void setId (int id) {this.id = ID; 
  }//Name private String name; 
  Public String GetName () {return name; 
  public void SetName (String name) {this.name = name; 
  //set set private set setvalues; 
  Public Set getsetvalues () {return setvalues; 
  The public void Setsetvalues (Set setvalues) {this.setvalues = setvalues; 
  //list Collection Private List listvalues; 
  Public List getlistvalues () {return listvalues; 
  The public void Setlistvalues (List listvalues) {this.listvalues = listvalues; 
  }//array set private string[] arrayvalues; 
  Public string[] Getarrayvalues () {return arrayvalues; } public void Setarrayvalues (string[] arrayvalues) {THis.arrayvalues = arrayvalues; 
  //map Collection Private Map mapvalues; 
  Public Map getmapvalues () {return mapvalues; 
  The public void Setmapvalues (Map mapvalues) {this.mapvalues = mapvalues; 
 } 
}

This class encapsulates several commonly used collections, and if you want to transform into a relational model, you must look at the mappings below.

4. Collection Mapping
the mapping of the set is actually quite simple, only need to add the corresponding collection tag, Hibernate provides the collection label <set>, <map>, <list>, <array> respectively; By using the central tab to map the collection to the corresponding relational table, and by adding <key> tags to implement the association of the foreign key of the table, the other properties are added by using <element>.
CollectionMapping.hbm.xml

<?xml version= "1.0"?> <! DOCTYPE hibernate-mapping Public "-//hibernate/hibernate mapping DTD 3.0//en" "Http://hibernate.sourceforge.net/hib Ernate-mapping-3.0.dtd ">  

Note that the list label and array label, the objects in the two collections are sequential, so you need to use the List-index or index tags to indicate the order of the objects when you add the mapping labels, and be sure to add the child tags in order, that is, add < key> tags, add <list-index> tags, and finally add <element> tags, otherwise there will be the following error:
The content of element type "list" must match "(meta*,subselect?,cache?,synchronize*,comment?,key,(index|list-index),(element|one-to-many|many-to-many|composite-element|many-to-any),loader?,sql-insert?,sql-update?,sql-delete?,sql-delete-all?,filter*)".

5. Relationship Model
the configured object model is transformed into the corresponding relational model, and the resulting SQL statement is as follows:

ALTER TABLE T_array_value drop FOREIGN key fk2e0dd0c067676b68 ALTER TABLE t_list_values drop FOREIGN key FKE01EC98BF4FCB ALTER TABLE t_map_values drop FOREIGN key fkd169ba107402b585 ALTER TABLE t_set_values drop FOREIGN key fk7bb8d04a7e79 F8BF drop table if exists t_array_value drop table if exists t_collection_mapping drop table if exists t_list_values D ROP table if exists t_map_values drop table if exists t_set_values create table T_array_value (array_id integer NOT NULL , Array_value varchar (255), array_index integer NOT NULL, primary key (array_id, Array_index)) CREATE TABLE T_collection_ Mapping (ID integer NOT NULL auto_increment, name varchar (255), primary key (ID)) CREATE TABLE t_list_values (list_id int Eger NOT NULL, List_value varchar (255), list_index integer NOT NULL, primary key (list_id, List_index)) CREATE TABLE T_ma 
P_values (map_id integer NOT NULL, Map_value varchar (255), Map_key varchar (255) NOT NULL, primary key (map_id, Map_key)) CREATE TABLE T_set_valueS (set_id integer NOT NULL, Set_value varchar (255)) ALTER TABLE T_array_value Add index fk2e0dd0c067676b68 (array_id), ad  D Constraint fk2e0dd0c067676b68 foreign key (array_id) references t_collection_mapping (ID) ALTER TABLE t_list_values add Index FKE01EC98BF4FCB03 (list_id), add constraint fke01ec98bf4fcb03 foreign key (list_id) references g (ID) ALTER TABLE t_map_values Add index fkd169ba107402b585 (map_id), add constraint fkd169ba107402b585 foreign key (map _id) references t_collection_mapping (ID) ALTER TABLE t_set_values Add index FK7BB8D04A7E79F8BF (set_id), add constraint 
 FK7BB8D04A7E79F8BF foreign KEY (set_id) references t_collection_mapping (ID)

The corresponding database views generated are as follows:

Second, data operation
1. Data Write
writes data operation, writes the data to need to notice to create the data object, in which the list, Set, map needs to create the data object, writes the data object to the database, because they all are the object interface, therefore needs to create an object, writes the object to the database, the concrete code as follows:

@SuppressWarnings ({"Unchecked", "rawtypes"}) public 
void Testsave () {session 
   
  Session=null; 
  try{ 
    session=hibernateutils.getsession (); 
    Session.begintransaction (); 
     
    Collectionmapping cm=new collectionmapping (); 
    Cm.setname ("Zhangsan"); 
     
    Set set=new hashset (); 
    Set.add ("a"); 
    Set.add ("B"); 
    Cm.setsetvalues (set); 
     
    List list=new ArrayList (); 
    List.add ("List1"); 
    List.add ("List2"); 
    Cm.setlistvalues (list); 
     
    String[] str=new string[]{"Array1", "Array2"}; 
    Cm.setarrayvalues (str); 
     
    Map map=new HashMap (); 
    Map.put ("K1", "v1"); 
    Map.put ("K2", "V2"); 
    Cm.setmapvalues (map); 
     
    Session.save (cm); 
    Session.gettransaction (). commit (); 
  catch (Exception e) { 
    e.printstacktrace (); 
    Session.gettransaction (). rollback (); 
  } finally{ 
    Hibernateutils.closesession (session); 
  } 
 

The resulting SQL statement is as follows:

Hibernate:insert into t_collection_mapping (name) VALUES (?) 
Hibernate:insert into T_set_values (set_id, Set_value) VALUES (?,?) 
Hibernate:insert into T_set_values (set_id, Set_value) VALUES (?,?) 
Hibernate:insert into T_list_values (list_id, List_index, List_value) VALUES (?,?,?) 
Hibernate:insert into T_list_values (list_id, List_index, List_value) VALUES (?,?,?) 
Hibernate:insert into T_map_values (map_id, Map_key, Map_value) VALUES (?,?,?) 
Hibernate:insert into T_map_values (map_id, Map_key, Map_value) VALUES (?,?,?) 
Hibernate:insert into T_array_value (array_id, Array_index, Array_value) VALUES (?,?,?) 
Hibernate:insert into T_array_value (array_id, Array_index, Array_value) VALUES (?,?,?) 

2. Loading data
the method of loading the data is simple, it loads the data from the table into the object in a collection, and then only needs to get the appropriate collection of objects.

public void TestLoad () {session 
  Session=null; 
  try{ 
    session=hibernateutils.getsession (); 
    Session.begintransaction (); 
     
    Collectionmapping cm= (collectionmapping) session.load (Collectionmapping.class, 1); 
     
    System.out.println ("Cm.name=" +cm.getname ()); 
    System.out.println ("cm.list=" +cm.getlistvalues ()); 
    System.out.println ("cm.map=" +cm.getmapvalues ()); 
    System.out.println ("cm.array=" +cm.getarrayvalues ()); 
    System.out.println ("cm.set=" +cm.getsetvalues ()); 
     
    Session.gettransaction (). commit (); 
  catch (Exception e) { 
    e.printstacktrace (); 
    Session.gettransaction (). rollback (); 
  } finally{ 
    Hibernateutils.closesession (session); 
  } 
 

Results generated by:

 Hibernate:select collection0_.id as id0_0_, collection0_.name as name0_0_ from T_collection_ 
Mapping collection0_ where collection0_.id=? Hibernate:select arrayvalue0_.array_id as array1_0_, Arrayvalue0_.array_value as array2_0_, Arrayvalue0_.array_index 
As array3_0_ from T_array_value arrayvalue0_ where arrayvalue0_.array_id=? Cm.name= Zhangsan hibernate:select listvalues0_.list_id as list1_0_, Listvalues0_.list_value as list2_0_, listvalues0_. 
List_index as list3_0_ from T_list_values listvalues0_ where listvalues0_.list_id=? cm.list= [List1, List2] hibernate:select mapvalues0_.map_id as map1_0_, Mapvalues0_.map_value as map2_0_, mapvalues0_.ma 
P_key as map3_0_ from T_map_values mapvalues0_ where mapvalues0_.map_id=? cm.map= {k1=v1, k2=v2} cm.array= [ljava.lang.string;@758d8478 hibernate:select setvalues0_.set_id as set1_0_, setvalues 
0_.set_value as set2_0_ from T_set_values setvalues0_ where setvalues0_.set_id=? cm.set= [B, a] 

Third, summary
Hibernate can persist instances of the following Java collections, including Java.util.Map, Java.util.Set, Java.util.SortedMap, Java.util.SortedSet, java.util.List , and an array of any persisted entities or values (using the Set collection type is the best choice). Properties of type Java.util.Collection or java.util.List can also be persisted using the "bag" semantics. The collection used for persistence, except for the collection interface, cannot retain any semantics attached to the class that implements these interfaces (for example, the iteration order that Linkedhashset brings). All the persistent collections, in fact, work directly according to the semantics of HashMap, HashSet, TreeMap, TreeSet, and ArrayList. In more depth, for a property that contains a collection, the Java type must be defined as an interface (i.e., map, Set, or list), not HashMap, TreeSet, or ArrayList. The reason for this limitation is that, when you don't know it, hibernate secretly replaces your map, set, and list instances with its own implementation of map, set, or list. (So in your program, use the = = operator sparingly.) (Note: For performance reasons, almost all Java collection interfaces are implemented in hibernate (for some features that are lazy to load). All ordered collection classes (maps, lists, arrays) all have a primary key consisting of <key> and <index>. In this case, the update of the collection class is very efficient-the primary key has been indexed effectively, so when Hibernate tries to update or delete a row, it can quickly find the row data. The primary key of a collection (sets) is composed of <key> and other element fields. This is inefficient for some element types, especially composite elements or large text, sophomore fields; The database may not be able to efficiently index complex primary keys. On the other hand, a one-to-many, Many-to-many association, especially a synthetic identifier, says the collection can achieve the same high performance. (Note: If you want Schemaexport to create a primary key for your <set>, you must declare all fields to be not-null= "true".) <idbag> mapping defines a surrogate key, so it can always be updated very efficiently. In fact, <idbag> has the best performance. Bag is the worst. Because bag allows duplicate element values and no indexed fields, it is not possible to define a primary key. Hibernate cannot determine the duplicate rows. When this collection is changed, hibernate will first remove the entire collection (through a single DELETE), and then recreate the entire collection. So the bag is very inefficient.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.