"Hibernate Step by Step"--the final set map

Source: Internet
Author: User

The previous article discussed in detail the principle of composite object mapping, which actually refers to how to map the composite relationship in the object model to the relational model, which is implemented by using the <component> tag provided by Hibernate, and it is necessary to add the properties of the corresponding composite object to the tag. For a mapping of composite objects, see the author's previous article. This article discusses in detail the mapping of the next set, the Java collection of four are set, MAP, List and general set, in the development of these sets often need to transform these collections into corresponding relational models, the implementation of this set of mapping is the topic we will discuss today.


first, set mapping


1.1 Collection Small Medium


Set mappings are also basic mappings, but are not often used in the development process, so there is no need for a deep understanding, only need to understand the basic use of the method, and so on in the development process encountered this problem can be queried to solve the method. Corresponding set mapping it actually refers to the mapping of a collection in Java to the corresponding table, is a collection object mapping, there are four types of collections in Java, respectively, set, MAP, list and ordinary arrays, there is a big difference between them:

Set, can not have duplicate object, object is unordered;

List, which can be ordered with duplicate objects, between objects;

Map, which is the key value in pairs appear;

arrays, which can be repeated, are ordered between objects.

The difference between them determines which collection to use at development time, usually using set at development time, the objects inside it are not needed, and an iterator can be used to get the inner object. If these collections want to map to the corresponding relational model, they must use the mapping tags provided by hibernate,<set>, <list>, <map>, <array>.


1.2 Mapping small-medium


To continue the discussion of the relational model of collection mappings, which refers to one object that corresponds to another collection of objects, Hibernate saves the data collection to the appropriate table when it is saved, and saves the data to the data table according to its assigned ID, if a new table is assigned to the collection separately. Then the ID is assigned to the ID of the collection table, and the corresponding relational table is as follows:


Class 1.3 Files

How collection mappings are implemented in code is then analyzed in detail. Here we hold all the collections into a class, which we call Collectionmapping.java, and the 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 {//idprivate int id;public int getId () {return ID;} 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;} public void Setsetvalues (Set setvalues) {this.setvalues = setvalues;} List collection Private list Listvalues;public list getlistvalues () {return listvalues;} public void Setlistvalues (List listvalues) {this.listvalues = listvalues;} Array Collection 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;} public void Setmapvalues (Map mapvalues) {this.mapvalues = mapvalues;}}

This class encapsulates several common collections that you want to convert to a relational model, and you have to look at the mappings below.


1.4 Set Map


The mapping of the collection is actually quite simple, only need to add the corresponding set tag, Hibernate provides the collection label <set>, <map>, <list>, <array>, respectively; By using a centralized tag to map the collection to the corresponding relational table, and by adding <key> tags to the association of the table's foreign keys, 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/ Hibernate-mapping-3.0.dtd ">
Note that the list label and the array label, the objects in the two collections are in order, so you need to add the mapping label to use the List-index or index tags to indicate the order of the objects, and when adding sub-labels must be added in order, that is, add < key> tag, add <list-index> tag, add <element> tag, otherwise the following error will appear:

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*) ".


1.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 fk2e0dd0c067676b68alter table t_list_values drop foreign key fke01ec98bf4fcb03a Lter table t_map_values drop foreign key fkd169ba107402b585alter table t_set_values drop foreign key Fk7bb8d04a7e79f8bfdro P table if exists t_array_valuedrop table if exists t_collection_mappingdrop table if exists t_list_valuesdrop table if ex Ists t_map_valuesdrop table if exists t_set_valuescreate table T_array_value (array_id integer NOT null, Array_value Varch AR (255), array_index integer NOT NULL, primary key (array_id, Array_index)) CREATE TABLE t_collection_mapping (ID integer n OT null auto_increment, name varchar (255), primary key (ID)) CREATE TABLE t_list_values (list_id integer NOT NULL, List_val UE varchar (255), list_index integer NOT NULL, primary key (list_id, List_index)) CREATE TABLE t_map_values (map_id integer Not NULL, Map_value varchar (255), Map_key varchar (255) is 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), add constraint fk2e0dd0c067676 B68 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 t_collection_mapping (ID) ALTER TABLE t_map_values Add index fkd169ba107402b585 (map_id), add constraint fkd169ba107402b585 foreign key (map_id) references T_collection_map Ping (ID) ALTER TABLE t_set_values Add index FK7BB8D04A7E79F8BF (set_id), add constraint fk7bb8d04a7e79f8bf foreign key (SE t_id) references t_collection_mapping (ID)


The corresponding database views generated are as follows:


second, data operation


2.1 Data Write

Write data operations, you need to pay attention to the creation of data objects, the list, Set, map needs to create data objects, data objects written to the database, because they are object interface, so you need to create an object, write objects to the database, the code is 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.2 Loading Data

The method of loading the data is simple, it loads the data in the table into the object as 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);}}

Result of the build:

Hibernate:select collection0_.id as id0_0_, collection0_.name as name0_0_ from T_collection_mapping collection0_ where co Llection0_.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= zhangsanhibernate: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_.map_key as map3_0_ from T_map_values mapvalues0_ where mapvalues0_.map_id= ? cm.map= {k1=v1, k2=v2}cm.array= [Ljava.lang.string;@758d8478hibernate:select setvalues0_.set_id as set1_0_, Setvalues0_.set_value as set2_0_ from T_set_values setvalues0_ where setvalues0_.set_id=?cm.set= [B, A]


Conclusion


Collection mapping is not often used in the development process, but to do a basic understanding of the implementation of this mapping is through the corresponding set of tags to achieve the transformation of the model, very simple. As of this article, Hibernate basic mapping has been discussed, these mappings are often used in the transformation of the object model into a relational model, the use of the map is discussed in detail, the relationship between them has not been further explored, so the next article will be a basic summary of the map to the outlook, The mapping is compared and classified.




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.