Getting Started 12 - List Map
This introduces how to map when the property includes the attribute of the LIST type, first we assume that we have to make an online file management, the user uploaded file name may be repeated, with the same name, the previous use set is not allowed Duplicate content, so this time we use List, our User category is written as follows:
User.java
Package online.
Import java.util. *;
PUBLIC CLASS User {
Private long id;
PRIVATE STRING NAME;
PRIVATE LIST FILES = New ArrayList ();
Public List getFiles () {
Return Files;
}
Public void setfiles (list files) {
THIS.FILES = Files;
}
Public long getId () {
Return ID;
}
Public void setid (long id) {
THIS.ID = ID;
}
Public string getname () {
Return Name;
}
Public void setname (String name) {
THIS.NAME = Name;
}
Public void addfiles (string name) {
FILES.ADD (Name);
}
Public void addfiles (int i, string name) {
FILES.ADD (I, Name);
}
}
We use ArrayList in the program to be imaged to the database in Hibernate, basically the same as the image set, we use the tag to replace
User.hbm.xml
XML Version = "1.0"?>
Public "- // hibernate / hibernate mapping dtd // en"
"http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd">
id>
Property>
list>
clas>
hibernate-maping>
Similar to SET, record the files table of the List, use the same user_id value as the USER table, let's take a look at how the data is stored in the data table, suppose our programs store data in the following manner:
User USER1 = New user ();
User1.setname ("CATERPILLAR");
User1.addfiles ("hibernate2.jar");
User1.addfiles ("jtx.jar");
User USER2 = New user ();
User2.setname ("momor");
User2.addfiles ("fan.jpg");
User2.addfiles ("fan.jpg");
User2.addfiles ("bush.jpg");
Session session = sessionFactory.openSession ();
Transaction tx = session.begintransaction ();
Session.save (user1);
Session.save (user2);
TX.comMit ();
session.close ();
Then the USER and the Files form in the database will save the following content:
MySQL> Select * from user;
-------- -----------
| User_id | NAME |
-------- -----------
| 1 | CATERPILLAR |
| 2 | MoMor |
-------- -----------
2 rows in set (0.00 sec)
Mysql> Select * from files;
-------- -------------- --------
| User_id | filename | Position |
-------- -------------- --------
| 1 | Hibernate2.jar | 0 |
| 1 | jtx.jar | 1 |
| 2 | FAN.JPG | 0 |
| 2 | FAN.JPG | 1 |
| 2 | Bush.jpg | 2 |
-------- -------------- --------
5 rows in set (0.00 sec)