Hibernate annotation annotation way to handle mapping relationships

Source: Internet
Author: User

In hibernate, there are usually two kinds of configuration object relationship mapping relationship, one is based on XML, the other is based on annotation annotation, cooked words, radish green vegetables, can have love, everyone has their favorite configuration, I tried these two ways, Find the way to use annotation can be more brief, so here is a simple record under the annotation to configure the various mapping relationships, after hibernate4 has been Annotation's jar package integration in, If you use the Hibernate3 version, you need to introduce the annotation jar package.

One, single-object operation

@Entity---> If our current bean is to be set as a solid object, we need to add entity to this annotation @table (name= "T_user")----> Set the table name of the database public class user{    private int id;    Private String username;    private String password;    Private Date born;    Private Date registerdate;
The Name property in the @Column (name= "register_date")---> Column corresponds to the name of the field in the database, and there are other properties, such as length,nullable, and so on public date Getregisterdate () { return registerdate; } public void Setregisterdate (Date registerdate) { this.registerdate = registerdate; }
@Id---> is defined as the primary key Id for the database (it is not recommended to introduce annotations on attributes, because the attribute is private and it is recommended to include annotations on getter methods if the introduction of annotations breaks their encapsulation characteristics) @GeneratedValue---- The > ID generation policy is to automatically generate public int getId () { return ID; } public void setId (int id) { this.id = ID; } ............}

Finally, you only need to add the entity class in the Hibernate.cfg.xml file:

<!--annotation-based configuration--        <mapping class= "Com.xiaoluo.bean.User"/><!--based on Hbm.xml profile        -- <mapping resource= "Com/xiaoluo/bean/user.hbm.xml"/>

So we can write the test class to do our crud operations.

Two or one-to-many mappings (One-to-many)

Here we define two entity classes, one is classroom, the other is student, and the two are one-to-many associations.

Classroom class:

@Entity @table (name= "T_classroom") public class classroom{private int id;    Private String ClassName;        Private set<student> students;    Public Classroom () {students = new hashset<student> ();    } public void Addstudent (Student Student) {students.add (Student);    } @Id @GeneratedValue public int getId () {return Id;    } public void setId (int id) {this.id = ID;    } public String GetClassName () {return className;    } public void Setclassname (String className) {this.classname = ClassName; } @OneToMany (mappedby= "")---> Onetomany specify a one-to-many relationship, mappedby= "Guest" Specifies the number of sides to maintain the association,Mappedby refers to the attribute of the dependence of a party to 1 on this side ., (Note: If you do not specify who will maintain the association relationship, the system will create an intermediate table for us) @LazyCollection (Lazycollectionoption.extra)---> The Lazycollection property is set to extra specifies that when the number of data is queried, only one count (*) statement is emitted, improving performance public set<student> getstudents () {RET    URN students;    } public void Setstudents (set<student> students) {this.students = students; }    }

Student class:

@Entity @table (name= "t_student") public class student{    private int id;    private String name;    private int age;    private classroom;        @ManyToOne (fetch=fetchtype.lazy)---> manytoone specifies a many-to-one relationship, and the Fetch=fetchtype.lazy property indicates that the object is loaded by lazy loading on the many side (default is not lazy loading )    @JoinColumn (name= "RID")---> Specifies the name of the foreign key by using the names property of Joincolumn RID (note: If we do not specify the name of the foreign key by Joincolum, the system will declare a name for us) Public    Classroom Getroom ()    {return to the hostel        ;    }    public void Setroom (classroom)    {        this.room = guest;    }    @Id    @GeneratedValue Public    int getId ()    {        return Id;    }    public void setId (int id)    {        this.id = ID;    }    Public String getName ()    {        return name;    }    public void SetName (String name)    {        this.name = name;    }    public int getage ()    {        return age;    }    public void Setage (int.)    {        this.age = age;    }    }

Three, one-to-one mapping (one-to-one)

Single-to-one relationship a person object and a Idcard object are defined here

Person class:

@Entity @table (name= "T_person") public class person{    private int id;    private String name;    Private Idcard card;        @OneToOne (mappedby= "person")---> Specifies the association of Onetoone, Mappedby also specifies that the other party will maintain the associated relationship public    Idcard Getcard ()    {        return card;    }    public void Setcard (Idcard card)    {        this.card = card;    }    @Id    @GeneratedValue Public    int getId ()    {        return Id;    }    public void setId (int id)    {        this.id = ID;    }    Public String getName ()    {        return name;    }    public void SetName (String name)    {        this.name = name;    }    }

Idcard class:

@Entity @table (name= "T_id_card") public class idcard{    private int id;    Private String No;    private person person;        @Id    @GeneratedValue Public    int getId ()    {        return Id;    }    public void setId (int id)    {        this.id = ID;    }    Public String Getno ()    {        return no;    }    public void Setno (String no)    {        this.no = no;    }    @OneToOne---> Onetoone specify a one-to-one relationship, one-to-one to maintain the mapping relationship, select Idcard for maintenance    @JoinColumn (name= "pid")---> Specifies the name of the foreign key PID public person    Getperson ()    {        return person;    }    public void Setperson (person person)    {        This.person = person;    }}

Note : When determining who is maintaining an association relationship, you can view the foreign key, which entity class defines the foreign key, and which class is responsible for maintaining the association relationship.

Iv. Many-to-many Mapping (many-to-many mapping relationships)

Many-to-many there are usually two ways to do this, one is by creating an intermediate table, and then by any of the one by one parties to maintain the association relationship, the other is to split the many-to-many into two one-to-many association relationships

1. Through the intermediate table by any one by one parties to maintain the association relationship

Teacher Class:

@Entity @table (name= "T_teacher") public class teacher{    private int id;    private String name;    Private set<course> courses;        Public Teacher ()    {        courses = new hashset<course> ();    }    public void Addcourse (Course Course)    {        courses.add (Course);    }        @Id    @GeneratedValue Public    int getId ()    {        return Id;    }    public void setId (int id)    {        this.id = ID;    }    Public String getName ()    {        return name;    }    public void SetName (String name)    {        this.name = name;    }    @ManyToMany (mappedby= "Teachers")---> represented by the Course to maintain public    set<course> getcourses ()    {        return courses;    }    public void setcourses (set<course> courses)    {        this.courses = courses;    }    }

Course class:

@Entity @table (name= "T_course") public class course{private int id;    private String name;        Private set<teacher> teachers;    Public Course () {teachers = new hashset<teacher> ();    } public void Addteacher (Teacher Teacher) {teachers.add (Teacher); } @ManyToMany---> Manytomany Specify a Many-to-many association @JoinTable (name= "T_teacher_course", joincolumns={@JoinColumn (name= "CID ")}, inversejoincolumns={@JoinColumn (name =" Tid ")})---> Because many-to-many will maintain a direct relationship between the two tables through a single intermediate table,jointableThis annotation declares that name specifies the name of the intermediate table,Joincolumns is an array of @JoinColumn type, representing the name of the foreign key that I have in the other side, and we are course, so the name of the foreign key in the other side is the RIDInversejoincolumns is also an array of @JoinColumn types, representing the other side in my place in the foreign key name, the other side is teacher, so the name of our foreign key is TidPublic set<teacher> Getteachers () {return teachers;    } public void Setteachers (set<teacher> teachers) {this.teachers = teachers;    } @Id @GeneratedValue public int getId () {return Id;    } public void setId (int id) {this.id = ID;    } public String GetName () {return name;    } public void SetName (String name) {this.name = name; }}

2. Split the Many-to-many into two one-to-many mappings (Admin, Role, Adminrole)

Admin class:

@Entity @table (name= "T_admin") public class admin{    private int id;    private String name;    Private set<adminrole> ars;    Public Admin ()    {        ars = new hashset<adminrole> ();    }    public void Add (Adminrole ar)    {        ars.add (AR);    }    @Id    @GeneratedValue Public    int getId ()    {        return Id;    }    public void setId (int id)    {        this.id = ID;    }    Public String getName ()    {        return name;    }    public void SetName (String name)    {        this.name = name;    }    @OneToMany (mappedby= "admin")---> Onetomany related to Adminrole, which is a class of adminrole that maintains many-to-one relationships, mappedby= "admin"    @ Lazycollection (Lazycollectionoption.extra) public    set<adminrole> Getars ()    {        return ars;    } Public    void Setars (set<adminrole> ars)    {        this.ars = ars;    }}

Role class:

@Entity @table (name= "T_role") public class role{    private int id;    private String name;    Private set<adminrole> ars;    Public Role ()    {        ars = new hashset<adminrole> ();    }    public void Add (Adminrole ar)    {        ars.add (AR);    }    @Id    @GeneratedValue Public    int getId ()    {        return Id;    }    public void setId (int id)    {        this.id = ID;    }    Public String getName ()    {        return name;    }    public void SetName (String name)    {        this.name = name;    }    @OneToMany (mappedby= "role")---> onetomany specifies that the class of Adminrole maintains a many-to-one association, mappedby= "role"    @LazyCollection ( Lazycollectionoption.extra) Public    set<adminrole> Getars ()    {        return ars;    }    public void Setars (set<adminrole> ars)    {        this.ars = ars;    }}

Adminrole class:

@Entity @table (name= "T_admin_role") public class adminrole{    private int id;    private String name;    Private admin admin;    private role role;    @Id    @GeneratedValue Public    int getId ()    {        return Id;    }    public void setId (int id)    {        this.id = ID;    }    Public String getName ()    {        return name;    }    public void SetName (String name)    {        this.name = name;    }    @ManyToOne---> Manytoone Association to admin    @JoinColumn (name= "aid") public    Admin getadmin ()    {        return admin;    }    public void setadmin (admin admin)    {        this.admin = admin;    }    @ManyToOne--->    @JoinColumn (name= "rid") public    Role getrole ()    {        return role;    }    public void Setrole (role role)    {        this.role = role;    }}

tip : When inserting through hibernate, whether it's a one-to-many or one-to-many, you just need to remember that the entity class declares the foreign key, which class maintains the relationship, and when the data is saved, The data for the party that maintains the association is always saved first, and then the data of the party that maintained the relationship, such as:

Person p = new person ();            P.setname ("Xiaoluo");            Session.save (p);                        Idcard card = new Idcard ();            Card.setno ("1111111111");            Card.setperson (p);            Session.save (card);
        

These are some summaries of how hibernate annotation annotations are configured to map relationships.

Original address: http://www.cnblogs.com/xiaoluo501395377/p/3374955.html;

Hibernate Note: http://zhaoke0427.blog.163.com/blog/static/11550518020107434726542/;

Hibernate annotation annotation way to handle mapping relationships

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.