Collection Annotation Mappings
A set-relational mapping can be thought of as a simplification of a one-to-many relationship mapping, and in an e-commerce system, the products sold may have more than one display image, and if we use a one-to-many to build an association map, we need to create an entity class images, There may be attributes: Images in the server's access path URL and picture of the product ProductID. But if we use a set-relational mapping, you don't need to create a new entity class, just define a collection member property in product.
Set Set
In the product, our picture path is generally not the same, we can use set set to establish the mapping
Let's look at a sample configuration for this requirement:
@Entity@Table"t_product")publicclass Product { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Integer id; private String name; @ElementCollection(fetch = FetchType.LAZY)//使用此注解配置集合映射关联 private Set<String> images ; //忽略get和set方法}
Here are our test methods:
new Product();product.setName("product"new HashSet<String>();for(int05; i ++){ imagesUrl.add("imageUrl"+ i);}product.setImages(imagesUrl);session.save(product);
To perform the above test method, we query the database:
That is, the internal implementation of the collection mapping is that hibernate creates a separate table for us to store this information.
If we want to customize this table to indicate the property name, we can use the following configuration:
@ElementCollection(fetch = FetchType.LAZY)@JoinTable"t_product_images"@JoinColumn"proId"))@Column"imagesUrl")private Set<String> images ;
Re-execute the test method and query the database:
The table name and property names were successfully modified.
List Collection
Using set sets ensures that element properties are not duplicated, but we cannot determine the order in which elements are inserted, unlike set sets, where the list collection has an indexed property in the database, we get records based on indexed properties, and we can tell the order in which elements are inserted according to indexed properties.
Below we use list to simulate a database-level queueing system: There are many doctors in a hospital, and every doctor has a lot of patients waiting in line. Here is our Doctor class:
@Entity@Table(name ="T_doctor") Public class Doctor { @Id @GeneratedValue(strategy = Generationtype.auto)PrivateInteger ID;PrivateString name;@ElementCollection(Fetch = Fetchtype.lazy)@JoinTable(name ="T_patient", Joincolumns =@JoinColumn(name ="doctor_id"))@Column(name ="Patient_name")//@IndexColumn (name = "Orders", base = 100) in the new version, this note has been deprecated, it is recommended to use the following two annotations instead @OrderColumn(name ="Orders")//Indicates that the index column is named Patient_name @ListIndexBase( -)//Indicates that the index starts at 100}
Here is our add-on test code:
new Doctor();doctor.setName("doctor"new ArrayList<String>();for(int05; i ++){ patients.add("patient" + i);}doctor.setPatientName(patients);session.save(doctor);
Run the code to view the database:
The data is inserted successfully, and carefully compared to the previous set set of pictures, we find here is ordered, do the following query operation:
1);System.out.println(doctor);for(String string : doctor.getPatientName()){ System.out.println(string);}
Console printing:
It shows that the data we get is orderly, so we can delete the first one dynamically, and the new record is added from the tail to achieve a queue effect.
In fact, we use list to configure multiple parties in a one-to-many mapping, and we can do the same thing.
Map Collection
In the product, there may be different specifications for different price of the object, this demand we can be achieved through map set map:
PackageCom.zeng4.model;ImportJava.util.Map;ImportJava.util.Set;ImportJavax.persistence.Column;ImportJavax.persistence.ElementCollection;Importjavax.persistence.Entity;ImportJavax.persistence.FetchType;ImportJavax.persistence.GeneratedValue;ImportJavax.persistence.GenerationType;ImportJavax.persistence.Id;ImportJavax.persistence.JoinColumn;Importjavax.persistence.JoinTable;ImportJavax.persistence.MapKey;ImportJavax.persistence.MapKeyColumn;Importjavax.persistence.Table;ImportOrg.hibernate.annotations.Type;@Entity@Table(name ="T_product") Public class Product { @Id @GeneratedValue(strategy = Generationtype.auto)PrivateInteger ID;PrivateString name;@ElementCollection @JoinTable(name ="T_specs_prize", Joincolumns =@JoinColumn(name ="product_id"))@Column(name ="Prize")//price for the corresponding specifications @MapKeyColumn(name ="Specs")//corresponding key-value column name PrivateMap<string, double> Prize;}
Here are our test methods:
new Product();product.setName("prodcut_with_many_prize"new HashMap();for(int05 ; i ++){prizes.put("specs"+i,1.2* i);}product.setPrize(prizes);session.save(product);
Execute the test method and query the database:
The Map collection properties in our Product class key are specification, corresponding to specs, value is price, corresponds to Peize.
Map Collection Association operations, which we can do by using code similar to the following:
1);for(Entry<String, Double> entry : product.getPrize().entrySet()){ System.out.println("specs = ""————prize = " + entry.getValue());}
Run method, console print:
SOURCE download
The contents of this section of the test code can be downloaded to https://github.com/jeanhao/hibernate/tree/master/collection
Hibernate5 (15) annotation map [7] Collection Association