Requirements: Students have a lot of photos, divided into pictures and work photos;
Section one: Each specific class corresponds to a table
Student.java:
PackageCom.cy.model;ImportJava.util.Set; Public classStudent {Private intID; PrivateString name; PrivateSet<image>images; Public intgetId () {returnID; } Public voidSetId (intID) { This. ID =ID; } PublicString GetName () {returnname; } Public voidsetName (String name) { This. Name =name; } PublicSet<image>getimages () {returnimages; } Public voidSetImages (set<image>images) { This. Images =images; } }
View Code
Abstract class Image.java:
PackageCom.cy.model; Public Abstract classImage {Private intID; PrivateString ImageName; PrivateStudent Student; Public intgetId () {returnID; } Public voidSetId (intID) { This. ID =ID; } PublicString Getimagename () {returnImageName; } Public voidsetimagename (String imageName) { This. ImageName =ImageName; } PublicStudent getstudent () {returnstudent; } Public voidsetstudent (Student Student) { This. Student =student; } }
View Code
Pictures Lifeimage.java:
Package Com.cy.model; Public class extends image{}
View Code
Work Photo Workimage.java:
Package Com.cy.model; Public class extends image{}
View Code
Student.hbm.xml:
package = "Com.cy.model" > <class name= "Student" table= "t_student" > <id name= " ID "column=" stuid "> class=" Native "></generator> </id> <property name=" Name "column=" Stuname "></property> </class>
LifeImage.hbm.xml:
<hibernate-mapping Package= "Com.cy.model"> <classname= "Lifeimage"Table= "T_lifeimage"> <IDname= "id"column= "Lifeimageid"> <Generatorclass= "Native"></Generator> </ID> < Propertyname= "ImageName"column= "ImageName"></ Property> <Many-to-onename= "Student"column= "Stuid"class= "Com.cy.model.Student"></Many-to-one> </class></hibernate-mapping>
View CodeWorkImage.hbm.xml:
<hibernate-mapping Package= "Com.cy.model"> <classname= "Workimage"Table= "T_workimage"> <IDname= "id"column= "Workimageid"> <Generatorclass= "Native"></Generator> </ID> < Propertyname= "ImageName"column= "ImageName"></ Property> <Many-to-onename= "Student"column= "Stuid"class= "Com.cy.model.Student"></Many-to-one> </class></hibernate-mapping>
View CodeTest Code Studenttest.java:
@Test Public voidtestgetallimages () {List<Image> imageList =NewArraylist<image>(); intStuid = 1; List<Image> lifeimagelist = (list<image>) session.createquery ("from lifeimage l where l.student.id =" +stuid). List (); Imagelist.addall (lifeimagelist); List<Image> workimagelist = (list<image>) session.createquery ("from Workimage w where w.student.id =" +stuid). List (); Imagelist.addall (workimagelist); for(Image image:imagelist) {System.out.println (Image.getimagename ()); } }
View CodeAssociation relationships for three tables:
T_lifeimage Table Structure:
T_lifeimage Table Data:
T_workimage Table Data:
Section Two: The root class corresponds to a table
Hibernate Learning 7-hibernate Mapping inheritance