(Turn) hibernate annotation annotation method to deal with the mapping relationship

http://www.cnblogs.com/xiaoluo501395377/p/3374955.html

 

In hibernate, there are usually two ways to configure the object-relational mapping relationship, one is based on xml, and the other is based on annotation. Configuration method, after I tried these two methods, I found that the method of using annotation can be more brief, so here is a simple record of configuring various mapping relationships through annotation. After hibernate4, the jar package of annotation has been integrated. 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 an entity object, we need to add the Entity 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;
    @Column(name="register_date") ---> The name attribute in Column corresponds to the field name of the database, and there are other attributes in it, such as length, nullable, etc.
    public Date getRegisterDate()
    {
        return registerDate;
    }
    public void setRegisterDate(Date registerDate)
    {
        this.registerDate = registerDate;
    }
    @Id ---> Defined as the primary key ID of the database (it is recommended not to introduce annotations on attributes, because attributes are private
                     , if the introduction of annotations will destroy its encapsulation characteristics, it is recommended to add annotations to the getter method)
    @GeneratedValue ----> ID generation strategy is automatically generated  
    public int getId()
    {
        return id;
    }
    public void setId(int id)
    {
        this.id = id;
    }
   ............
}

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

 

<!-- annotation-based configuration -->
        <mapping class="com.xiaoluo.bean.User"/>
<!-- Based on hbm.xml configuration file-->
        <mapping resource="com/xiaoluo/bean/User.hbm.xml"/>
 

 

This way we can write test classes to perform our CRUD operations.

Two, one-to-many mapping (one-to-many)

Here we define two entity classes, one is ClassRoom and the other is Student, which is a one-to-many relationship.

 

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="room") ---> OneToMany specifies a one-to-many relationship,
                                  mappedBy="room" specifies that the more party maintains the association relationship,
                                  mappedBy refers to the attribute that the more side depends on the side of 1,
                    (Note: If you do not specify who will maintain the relationship, the system will create an intermediate table for us)
    @LazyCollection(LazyCollectionOption.EXTRA)  --->  LazyCollection属性
       Set to EXTRA specifies that when the number of data is queried, only one count(*) statement will be issued to improve performance
    public Set<Student> getStudents()
    {
        return 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 room;
    
    @ManyToOne(fetch=FetchType.LAZY) ---> ManyToOne specifies a many-to-one relationship,
                                       The fetch=FetchType.LAZY property indicates that on the side with more
                                       Load objects by lazy loading (default is not lazy loading)
    @JoinColumn(name="rid") ---> specified by the name attribute of JoinColumn
                     The name of the foreign key rid (note: if we do not specify the name of the foreign key through JoinColum,
                     The system will declare a name for us)
    public ClassRoom getRoom()
    {
        return room;
    }
    public void setRoom(ClassRoom room)
    {
        this.room = room;
    }
    @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 age)
    {
        this.age = age;
    }
    
}

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

One-to-one relationship here defines a Person object and an IDCard object

 

Person class:

@Entity
@Table(name="t_person")
public class Person
{
    private int id;
    private String name;
    private IDCard card;
    
    @OneToOne(mappedBy="person") ---> specifies the relationship of OneToOne,
                                         mappedBy also specifies that the relationship is maintained by the other party
    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 specifies a one-to-one relationship,
                        In one-to-one, randomly designate one party to maintain the mapping relationship. Here, select IDCard for maintenance.
    @JoinColumn(name="pid") ---> Specify the name pid of the foreign key
    public Person getPerson()
    {
        return person;
    }
    public void setPerson(Person person)
    {
        this.person = person;
    }
}

Note : When judging who maintains the association relationship, you can check the foreign key, which entity class defines the foreign key, and which class is responsible for maintaining the association relationship .

 

4. Many-to-Many mapping (many-to-many mapping relationship)

There are usually two ways to deal with many-to-many here. One is to establish an intermediate table and then maintain the association relationship by any one of the many parties, and the other is to split the many-to-many into two pairs. multiple relationships

1. The association relationship is maintained by any one of the many parties through the intermediate table

 

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") ---> Indicates that the maintenance is performed by the Course side
    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 specifies a many-to-many relationship
    @JoinTable(name="t_teacher_course",joinColumns={ @JoinColumn(name="cid")}
    , inverseJoinColumns={ @JoinColumn(name = "tid") }) ---> because between many-to-many
               The direct relationship between the two tables will be maintained through an intermediate table, so it is declared through the JoinTable annotation,
               name is the name of the specified intermediate table, JoinColumns is an array of type @JoinColumn,
          Indicates the foreign key name of my side in the other party, our side is Course, so the name of the foreign key in the other party is rid,
   inverseJoinColumns is also an array of @JoinColumn type, which represents the foreign key name of the other party in my place.
                    The other party is Teacher, so the name of the foreign key on our side is tid
    public 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 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 is associated with the AdminRole class,
                           The many-to-one relationship is maintained by the AdminRole class, 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 the class AdminRole
                                         To maintain a many-to-one relationship, 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 is associated 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 is one-to-many, one-to-one or many-to-many, all you need to remember is that which entity class declares the foreign key, which class maintains the relationship, When saving data, always save the data of the party that does not maintain the association relationship first, and then save the data of the party that maintains the association 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);

The above is a summary of the hibernate annotation annotation method to configure the mapping relationship.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326942891&siteId=291194637