Mybatis的Mapper.xml中定义了对数据库的增删改查等sql操作语句。
这些语句中,既要对应数据库中各个表的字段,又要对应Java类中的属性,之前常常搞不清楚,刚刚在写项目的过程中,突然茅塞顿开。
结合实例:
UserTrackModel.java:
@Alias("userTrackModel") public class UserTrackModel extends BaseModel { public static final String COND_USER_ID = "userId"; private int userId; private Date dateStart; private Date dateEnd; private CompanyModel company; private String position; private String comment; ......(getset) }
UserTrackMapper.java:
@Mapper public interface UserTrackMapper { List<UserTrackModel> queryList(UserTrackModel userTrackModel); }
UserMapper.xml
<mapper namespace="com.hsys.mappers.UserTrackMapper"> <resultMap id="companyResultMap" type="companyModel" > <id column="c_id" property="id"/> <result column="c_name" property="name"/> </resultMap> <resultMap id="userTrackResultMap" type="userTrackModel" > <id column="u_id" property="id"/> <result column="u_user_id" property="userId"/> <result column="u_date_start" property="dateStart"/> <result column="u_date_end" property="dateEnd"/> <result column="u_comment" property="comment"/> <result column="u_position" property="position"/> <association property="company" resultMap="companyResultMap"/> </resultMap> <select id="queryList" resultMap="userTrackResultMap"> select u.c_id as u_id, u.c_date_start as u_date_start, u.c_date_end as u_date_end, u.c_comment as u_comment, u.c_position as u_position, c.c_id as c_id, c.c_name as c_name from user_track_tbl as u left join company_tbl as c on u.c_company_id = c.c_id <where> <if test="cond.userId != null"></if> u.c_user_id = #{userId} </where> </select>
UserTrackService.java
@Service public class UserTrackService { @Autowired private UserTrackMapper userTrackMapper; public List<UserTrackModel> queryList(UserTrackModel userTrackModel){ return userTrackMapper.queryList(userTrackModel); } public List<UserTrackModel> queryByUid(int userId){ UserTrackModel userTrack = new UserTrackModel(); userTrack.setUserId(userId); userTrack.setCond(UserTrackModel.COND_USER_ID, userId); List<UserTrackModel> userTracks = queryList(userTrack); return userTracks; } }
UserTrackBusiness.java
@Component public class UserTrackBusiness { @Autowired private UserTrackService userTrackService; public List<UserTrackModel> queryList(UserTrackModel userTrackModel){ return userTrackService.queryList(userTrackModel); } }