The idea is:
Here is a small example:
Many-to-many core table, third-party table. table:
create table thrid(one_id int not null,two_id int not null,constranit FK_one_id froeign key(one_id) reference one(id_in_one),constraint FK_two_id foreign key(two_id) reference two(id_in_two));
Here we use the primary keys of the two tables as foreign keys for this third party. This makes it easy to build relationships.
To comply with the JavaBean naming specification, if there are parameters or not, the constructor attributes are private. If you access the common setter and getter, you must remember to include a set set in multiple tables.
This mapping file can be said to be the core of Hibernate. Note that this file should be placed in the same directory as the entity class, that is, it will be better to facilitate search and operation.
Use plug-in to generate or refer to templates to make modifications. The most core is the set tag and the many-to-many tag inside, as follows:
Employees mapping file configuration (multiple)
<?xml version="1.0"?><!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="cn.itcast.h_hbm_oneToMany"> <class name="Employee" table="employee"> <id name="id"> <generator></generator> </id> <property name="name"></property> <!-- department attribute, Department type, represents many-to-one between Employee and Department --> <many-to-one name="department" column="departmentId"></many-to-one> </class></hibernate-mapping>
and department mapping file
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping package="cn.itcast.h_hbm_oneToMany"> <class name="Department" table="department"> <id name="id"> <generator></generator> </id> <property name="name"></property> <!-- Employees attribute, Set collection, expresses the one-to-many inverse attribute of Department and Employee: true indicates whether it has given up maintaining the association relationship, and the default is false. --> <set name="employees" inverse="true"> <key column="departmentId"></key> <one-to-many/> </set> </class></hibernate-mapping>
After configuring the above steps, we can write our "DAO" layer code normally, but with the Hibernate Session artifact, all we need to do is to make related API calls in the DAO layer. This will be a very, very easy task.
The above is the entire content of this article about the hibernate multi-table operation example code, I hope it will be helpful to everyone. Interested friends can continue to refer to other related topics on this site. If there are any shortcomings, please leave a message to point it out. Thank you friends for your support for this site!