Article From:https://www.cnblogs.com/DawnCHENXI/p/9123184.html

 

 

 

 

Contents

————I have no him, but my hands are ripe, humility is foolishness, but learning is hunger.

 

 

 

 

This blog will tellHibernateAssociated query in it,And itsCascade (cascade)Operation, andWhich party is specified to maintain an association (inverse)

 

One, the catalogue is as follows:

  1.Unidirectional one to many:(Add a district and other subordinate streets.

  2.Single item to one to many:(Query a district and county, and all the corresponding streets below.

  3.Single item multiple to one:(Inquire about a designated street and show its corresponding counties at the same time.

  4.Bi-directional one to many (multiple to one):(It is worth noting: toString () routines are not easy to cause errors Error——StackOverflowError.

  5.inverseThe use and detailed explanation:(Which party is specified to maintain the relationship)

  6.cascading deletion:(Delete the data in the main table, and the foreign key will be its data.Use it carefully!!!!!!)

  Note: actually, I want to talk about more than many, but I am not prepared. The next blog will summarize in detail.

 

Two,Unidirectional one to many:(Add a district and other subordinate streets.

  1.Brief introduction:

    I will do all the preparatory work in this case, and other cases will be slightly modified in this case.

  2.The preparation of the entity class:

    2.1:DistrictDistrict and county entity class

 

package cn.dawn.day03.entity;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Dawn on 2018/5/30.
 */

/*District and county*/
public class District {
    private  Integer id;//District and county ID
    private  String name;//District and county name

    /*A district corresponds to a number of streets*/
    private List<Street> streets=new ArrayList<Street>();

    @Override
    public String toString() {
        return "District{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", streets=" + streets +
                '}';
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<Street> getStreets() {
        return streets;
    }

    public void setStreets(List<Street> streets) {
        this.streets = streets;
    }

    public District() {
    }

    public District(Integer id, String name, List<Street> streets) {
        this.id = id;
        this.name = name;
        this.streets = streets;
    }

    public District(Integer id, String name) {
        this.id = id;
        this.name = name;
    }
}

 

    2.2:StreetStreet class

 

package cn.dawn.day03.entity;

/**
 * Created by Dawn on 2018/5/30.
 */
/*Street class*/
public class Street {
    private Integer id;//Street ID
    private String name;//Street name

    private District district;

    @Override
    public String toString() {
        return "Street{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", district=" + district +
                '}';
    }

    public Street() {
    }

    public Street(Integer id, String name) {
        this.id = id;
        this.name = name;
    }

    public District getDistrict() {
        return district;
    }

    public void setDistrict(District district) {
        this.district = district;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

 

  3.hbmPreparation of documents:

    3.1:District.hbm.xmlConfiguration of files

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="cn.dawn.day03.entity">
    <!--If package is specified above, the class name does not need to write the whole class name.-->
    <!--lazy:Lazy loading (lazy loading) the default value is true, lazy loading.-->
    <!--<class name="Teacher">-->
    <!--Direct loading-->
    <class name="District" lazy="false">
        <!--Primary key-->
        <id name="id" column="id">
            <!--Key key generation of assigned programmers themselves-->
            <!--identityIt is the self increment in mysql, which will increase the operation and do not need to assign the primary key again.-->
            <!--incrementFirst, check the largest primary key column and add one to the primary key in the next column.-->
            <!--sequenceIt is the primary key of oracle that generates the strategy. He will need to specify the sequence name < param name= "sequence" > sequence name < /param>-->
            <generator class="assigned"></generator>
        </id>
        <property name="name" column="name"></property>
        <!-- Configuring a one to many association managementName: association relation attribute nameColumn: the corresponding foreign key in the databaseClass: type of AssociationCascade: to the current objectDoes it affect the associated object when it is operatedInverse= "true": abandoning the interaction with the database-->
        <bag name="streets" cascade="save-update" >
            <key column="districtid"></key>
            <one-to-many class="Street"></one-to-many>
        </bag>
    </class>
</hibernate-mapping>

    3.2:Street.hbm.xmlFile configuration

 

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="cn.dawn.day03.entity">
    <!--If package is specified above, the class name does not need to write the whole class name.-->
    <!--lazy:Lazy loading (lazy loading) the default value is true, lazy loading.-->
    <!--<class name="Teacher">-->
    <!--Direct loading-->
    <class name="Street" lazy="false">
        <!--Primary key-->
        <id name="id" column="id">
            <!--Key key generation of assigned programmers themselves-->
            <!--identityIt is the self increment in mysql, which will increase the operation and do not need to assign the primary key again.-->
            <!--incrementFirst, check the largest primary key column and add one to the primary key in the next column.-->
            <!--sequenceIt is the primary key of oracle that generates the strategy. He will need to specify the sequence name < param name= "sequence" > sequence name < /param>-->
            <generator class="assigned"></generator>
        </id>
        <property name="name" column="name"></property>
        <!--Configuring a multi - to - one AssociationThe attribute name of the association in the name: classClass: type of AssociationColumn: the foreign keys of two tables in a database-->
        <!--<many-to-one  name="district" class="District" column="districtId"/>-->
    </class>
</hibernate-mapping>

 

  4.Single test method,Add one district and the following corresponding streets:

 

    @Test
    /**
     * One to one, increase one district, county and other subordinate streets.* be sure to add to the HBM: cascade* cascade= "Save-update"*/
    public void t1OneToMany(){
        /*Create three streets*/
        Street  street1=new Street(1,"1 Street, Haidian ");
        Street  street2=new Street(2,"2 street, Haidian ");
        Street  street3=new Street(3,"3 Street, Haidian ");
        List<Street> streets=new ArrayList<Street>();
        streets.add(street1);
        streets.add(street2);
        streets.add(street3);
        /*Add a zone to the database*/
        District district=new District(1,"Test Haidian District ");
        /*You can also get a zone from the database, and recommend second.*/
        /*District district = session.get(District.class, 1);*/
        district.setStreets(streets);

        /*New streets*/
        session.save(district);
        tr.commit();



        /*results of enforcementHibernate: create table District (ID integer not null, name varchar (255), primary key (ID)) engine=MyISAMHibernate: create table Street (ID integer not null, name varchar (255), DIstrictid integer, primary key (ID)) engine=MyISAMHibernate: alter table Street add constraInt FKjuba2team1j6124qeurjyblk1 foreign key (districtid) references District (ID)Hibernate:Select street_.id, street_.name as name2_1_ from Street street_ where street_.id=?HibernatE: select street_.id, street_.name as name2_1_ from Street street_ where street_.id=?HibernAte: select street_.id, street_.name as name2_1_ from Street street_ where street_.id=?HibeRnate: insert into District (name, ID) values (???)Hibernate: insert into Street (name, ID)) values (??)Hibernate: insert into Street (name, ID) values (???)Hibernate: inSERT into Street (name, ID) values (?,?)Hibernate: update Street set districtid=? Where id=?Hibernate: update Street set districtid=? Where id=?Hibernate: update Street setDistrictid=? Where id=?*/
    }

 

 

Three,Single item to one to many:(Query a district and county, and all the corresponding streets below.

  1.If the original code does not change, do the following operations

  2.Search for a district, and all the corresponding streets below.

 

    @Test
    /*Query all the streets in the designated district and county*/
    public void t2selectStreetByDistrict(){
        /*Get a district of 1 ID*/
        District district=session.get(District.class,1);
        /*Get all the streets in the district and county*/
        List<Street> streets = district.getStreets();
        for (Street street:streets) {
            System.out.println(street);
        }


        /*Running resultHibernate: alter table Street add constraint FKjuba2team1j6124qeurjyblk1 foreign key (d)Istrictid) references District (ID)Hibernate: select district0_.id as id1_0_0_, district0_.Name as name2_0_0_ from District district0_ where district0_.id=?Hibernate: select streets0_.districtid as district3_1_0_, streets0_.id as id1_1_0_, streets0_.id as id1_1_1_, streets0_.name aS name2_1_1_ from Street streets0_ where streets0_.districtid=?Street{id=1, name='Haidian 1 Street']Street{id=2, name='Haidian 2 Street']Street{id=3, name='Haidian 3 Street']**/
    }

 

 

Four,Single item multiple to one:(Inquire about a designated street and show its corresponding counties at the same time.

  1.First, two.3.3.1 in District.hbm.xmlAnnotate &lt, bag node, or directly kill >

 

        <!--<bag name="streets" cascade="save-update" >
            <key column="districtid"></key>
            <one-to-many class="Street"></one-to-many>
        </bag>-->

 

  2.In fact, there should be more parties to implant a smaller party, but I have already done it in preparation.

 

/*Street class*/
public class Street {
    private Integer id;//Street ID
    private String name;//Street name

    /*A key:::::::::*/
    private District district;

 

  3.In the Street.hbm.xml configuration file,Release the node of the < many-to-one> I have annotated.

 

     <!--Configuring a multi - to - one AssociationThe attribute name of the association in the name: classClass: type of AssociationColumn: the foreign keys of two tables in a database-->
        <many-to-one  name="district" class="District" column="districtId"/>

 

  4.Writing test method:Search for a designated street and show the corresponding districts and counties:

 

    @Test
    /*Inquire the county area corresponding to the designated Street*/
    /*Multi to one*/
    /*Get rid of the previous one*/
    public void t3ManyToOne(){
        /*You need to add fewer objects to one party's entity class, and configure manytoone in HBM.*/
        Street street = session.get(Street.class, 1);
        System.out.println(street);

        /*
        Hibernate: alter table Street add constraint FKfch89j84iailpfqs5bpkj2rs0 foreign key (districtId) references District (id)
        Hibernate: select street0_.id as id1_1_0_, street0_.name as name2_1_0_, street0_.districtId as district3_1_0_ from Street street0_ where street0_.id=?
        Hibernate: select district0_.id as id1_0_0_, district0_.name as name2_0_0_ from District district0_ where district0_.id=?
        Street{id=1, name='Haidian 1 Street ', district=District{id=1, name=' test Haidian District ', streets=[]}}*/
    }

 

 

Five,Bi-directional one to many (multiple to one):(It is worth noting:toString()Wrong wayeasilyCause error Error——StackOverflowError

  1.Explanation:

    Their relationship is mutual, and they must participate in maintaining the relationship.

  2.Comment on the four middle notesDistrict.hbm.xmlin< bag> label again

 

        <bag name="streets" cascade="save-update" >
            <key column="districtid"></key>
            <one-to-many class="Street"></one-to-many>
        </bag>

 

  3.It is worth noticing that we need to modify the toString () method. If not, he will call each other, and there will be a stack overflow error.

  4.When you don’t change toString () first,Writing test method: (inquiring a street and its corresponding districts and counties)

 

    @Test
    /*One way or two is mutual relationship!!!!!!!!*/
    /*Add the T3 to the configuration.*/
    public void t4twoway(){
        Street street = session.get(Street.class, 1);
        System.out.println(street);


        /*Note: toString needs to do something, otherwise it will be recycled if you call each other, stack overflow java.lang.StackOverflowError*/

        /*
        Hibernate: alter table Street add constraint FKfch89j84iailpfqs5bpkj2rs0 foreign key (districtId) references District (id)
        Hibernate: select street0_.id as id1_1_0_, street0_.name as name2_1_0_, street0_.districtId as district3_1_0_ from Street street0_ where street0_.id=?
        Hibernate: select district0_.id as id1_0_0_, district0_.name as name2_0_0_ from District district0_ where district0_.id=?
        Hibernate: select streets0_.districtid as district3_1_0_, streets0_.id as id1_1_0_, streets0_.id as id1_1_1_, streets0_.name as name2_1_1_, streets0_.districtId as district3_1_1_ from Street streets0_ where streets0_.districtid=?

        java.lang.StackOverflowError
        ......
        * */
    }

 

  5.Modify any toString () method so that it no longer calls each other incontinence.

 

/*District and county*/
public class District {
    private  Integer id;//District and county ID
    private  String name;//District and county name

    /*A district corresponds to a number of streets*/
    private List<Street> streets=new ArrayList<Street>();

    @Override
    public String toString() {
        return "District{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", streets=" + streets.size() +
                '}';
    }

 

  6.Re executing the code in 4, found that no errors will occur again, and successfully query.

 

Six,inverseThe use and detailed explanation:(Which party is specified to maintain the relationship

  1.Explain:

    (1).HibernateThe rule is that many parties must maintain the relationship, so we can only modify one side (one-to-many).

    (2).inverseThe default value is falseInteracting with the databaseMaintaining association relationships,If we want to improve our performance, we can give up one side to interact with the database.Give up the maintenance of the association and change the value to trueCan;

  2.District.hbm.xmlThe configuration is modified as follows:

 

        <!-- Configuring a one to many association managementName: association relation attribute nameColumn: the corresponding foreign key in the databaseClass: type of AssociationCascade: to the current objectDoes it affect the associated object when it is operatedInverse= "true": abandoning the interaction with the database-->
        <bag name="streets" cascade="save-update" inverse="false">
            <key column="districtid"></key>
            <one-to-many class="Street"></one-to-many>
        </bag>

 

  3.Single test method (first test one party to maintain correlation):

    @Test
    public   void  t5inverse(){
        //Create district and county
        District district=new District(2,"Daxing District ");
        //Create a street
        Street street1=new Street(4,"Daxing 3 Street ");
        Street street2=new Street(5,"Daxing 4 Street ");
        //Put the streets in the district and County Street Collection
        district.getStreets().add(street1);
        district.getStreets().add(street2);
        //New district and county
        session.save(district);
        tr.commit();
        /**
         *   8 SQL statements are produced! Find the back of the two update is no work!!!!!Hibernate: alter table Street add constraint FKfch89j84Iailpfqs5bpkj2rs0 foreign key (districtId) references District (ID)Hibernate: select streeT_.id, street_.name as name2_1_, street_.districtId as district3_1_ from Street street_ where street__.id=?Hibernate: select street_.id, street_.name as name2_1_, street_.districtId as distriCt3_1_ from Street street_ where street_.id=?Hibernate: insert into District (name, ID) VALues (???)Hibernate: insert into Street (name, districtId, ID) values (?????)Hibernate: insert into Street (name, districtId, ID) values (?????)Hibernate: update StrEET set districtid=? Where id=?Hibernate: update Street set districtid=? Where id=?The 3 insert is produced by District!Why two update?? Street!Hibernate stipulates that:More than 1One party, many-to-one, must safeguard the relationship between the two sides.Because many-to-one has no inverse attribute at all.02.inverse default is false!Turn! I'll keep it!3, we must set up inverse= "true" on one side to give up the right to maintain.Maintain = = = whether or not to interact with the database!*/
    }

  4.takeinverseChange to true, give up the power of maintenance,Then execute the code, and find out:

 

        /*Modify inverse=true, delete the data you just added, and execute the single test again.*/
        /*
        Hibernate: alter table Street add constraint FKfch89j84iailpfqs5bpkj2rs0 foreign key (districtId) references District (id)
        Hibernate: select street_.id, street_.name as name2_1_, street_.districtId as district3_1_ from Street street_ where street_.id=?
        Hibernate: select street_.id, street_.name as name2_1_, street_.districtId as district3_1_ from Street street_ where street_.id=?
        Hibernate: insert into District (name, id) values (?, ?)
        Hibernate: insert into Street (name, districtId, id) values (?, ?, ?)
        Hibernate: insert into Street (name, districtId, id) values (?, ?, ?)
        It was found that there was no update behind.*/

 

 

Seven,cascading deletionUse caution with caution!!!!!!!!!!!!!!!!!!!!!!

  1.Tell about:

    If you have set up a record in the table that is located in the main key, the record of its associated foreign key will also be dried out, so it is very dangerous, do not use it!

  2.Set upDistrict.hbm.xmlThe cascade= “delete” and the inverse= “false” (or inverse are not configured)

 

        <bag name="streets" cascade="delete" inverse="false">
            <key column="districtid"></key>
            <one-to-many class="Street"></one-to-many>
        </bag>

 

  3.Write the test code, such as deleting a district and county:

 

    @Test
    /*cascading deletion*/
    /*cascade="delete" inverse="false"*/
    public void t6deleteMapping(){
        /*cascade="delete" inverse="false"Remember to change this parameter*/
        /*Get a district of 2 ID*/
        District district=session.get(District.class,2);
        /*delete*/
        session.delete(district);

        tr.commit();

        /*
        Hibernate: alter table Street add constraint FKfch89j84iailpfqs5bpkj2rs0 foreign key (districtId) references District (id)
        Hibernate: select district0_.id as id1_0_0_, district0_.name as name2_0_0_ from District district0_ where district0_.id=?
        Hibernate: select streets0_.districtid as district3_1_0_, streets0_.id as id1_1_0_, streets0_.id as id1_1_1_, streets0_.name as name2_1_1_, streets0_.districtId as district3_1_1_ from Street streets0_ where streets0_.districtid=?
        Hibernate: update Street set districtid=null where districtid=?
        Hibernate: delete from Street where id=?
        Hibernate: delete from Street where id=?
        Hibernate: delete from District where id=?
        * */
        /*He will kill both tables, so be careful!!!!!!!!!!!*/
    }

 

 

 

 

 

Author:Dawn Dawn

Please indicate the source of the reprint:https://www.cnblogs.com/DawnCHENXI/p/9123184.html

If there is any mistake, please point out, thank you!!!!!!!!!!!!!!

Similar Posts:

Leave a Reply

Your email address will not be published. Required fields are marked *