Recently, I'm studying object-oriented design. When using a domain object, the existence of a convenient class in the database seems to be troublesome, I was hoping to receive the value obtained from the database directly in the form of a domain object: frowning2:
I'm still studying, so I tried using MyBatis as one solution, I would like to know if there is a good way to get the value from the database: bow:
Get the MeetingRoom class using MyBatis
public class MeetingRoom {
private int id;
private String name;
...
}
@Mapper
public interface MeetingRoomMapper {
MeetingRoom findById(int roomId);
}
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.spring.tutorial.MeetingRoomMapper">
<select id="findById" resultType="com.spring.tutorial.MeetingRoom">
SELECT
room_id as id,
room_name as name
FROM
meeting_room
WHERE
room_id = #{room_id}
</select>
</mapper>
If you specify the return value of findById of Mapper class and MeetingRoom for ResultType of Mapper file, it will be returned in the form of MeetingRoom. Also, since the column name and property name must match, it is specified in the AS clause.
Change the ID of MeetingRoom from int type to Id class.
public class MeetingRoom {
//Change to value object
private Id id;
private String name;
...
}
public class Id {
private static final int MIN = 1;
private Integer value;
Id(int value) {
if (value < MIN) throw new IllegalArgumentException("Illegal value. value:" + value);
this.value = value;
}
...
}
Set the Id class and MeetingRoom class using ResultMap.
<resultMap id="IdMap" type="com.spring.tutorial.Id" >
<id property="value" column="room_id" />
</resultMap>
<resultMap id="MeetingRoomMap" type="com.spring.tutorial.MeetingRoom">
<result property="name" column="room_name" />
<association property="id" resultMap="IdMap"/>
</resultMap>
<select id="findById" resultMap="MeetingRoomMap">
SELECT * FROM meeting_room WHERE room_id = #{room_id}
</select>
Change the ResultType of SELECT to ResultMap and specify the ResultMap of MeetingRoom. Use ** association ** to use ResultMap within ResultMap. When there is a result in the property of the same object, be careful because an error will occur if you do not describe the association below: point_up_2_tone1:
The content of element type "resultMap" must match "(constructor ?, id *, result *, association *, collection *, discriminator?)".
MyBatis is good because you don't have to increase the number of convenient classes in the database: relaxed:
Principles of system design useful in the field mybatis --Mapper XML file
Recommended Posts