How to configure one-to-many and many-to-one relationsh…
The configuration of one-to-many and many-to-one relationships in MyBatis requires the use of two tags:
The steps for configuring a one-to-many relationship are as follows:
- Create two entities, one representing the one side and the other representing the many side.
- In one side’s entity class, include a collection property to store multiple entity objects from the other side.
- selection
- assortment
- real estate
- type of
- choose
- Assortment or group of items.
- Choose
The steps for configuring a one-to-many relationship are as follows:
- Create two entity classes, one representing the many side and the other representing the one side.
- Add an entity object property in the class of the one with the many side to store an entity object of the one side.
- – Organization
- – organization
- real estate
- Type of Java programming language
- column – a vertical structure used for support or decoration in a building
- –
- choose
Example setup:
Example of configuring a one-to-many relationship:
<resultMap id="userMap" type="User">
<id property="id" column="id"/>
<result property="name" column="name"/>
<collection property="orders" ofType="Order" select="getOrdersByUserId" column="id"/>
</resultMap>
<select id="getUserById" parameterType="int" resultMap="userMap">
SELECT * FROM user WHERE id = #{id}
</select>
<select id="getOrdersByUserId" parameterType="int" resultMap="orderMap">
SELECT * FROM orders WHERE user_id = #{userId}
</select>
Example of configuring a one-to-many relationship:
<resultMap id="orderMap" type="Order">
<id property="id" column="id"/>
<result property="name" column="name"/>
<association property="user" javaType="User" column="user_id" select="getUserById"/>
</resultMap>
<select id="getOrderById" parameterType="int" resultMap="orderMap">
SELECT * FROM orders WHERE id = #{id}
</select>
<select id="getUserById" parameterType="int" resultMap="userMap">
SELECT * FROM user WHERE id = #{id}
</select>
These examples assume there are two tables: user and orders, where the foreign key column in the orders table is user_id.