5. Getting Started with MyBatis
class Person {
Integer id;
String name;
}
<resultMap type="Person" id="PersonMap">
<id property="id" column="person_id"/>
<result property="name" column="person_name"/>
</resultMap>
6. Getting Started with MyBatis
<select id="getPersonById" parameterType="int"
resultType= "Person">
select * from person where person_id=#{id}
</select>
public Person getById(Integer id) {
return session.selectOne("getPersonById", id);
}
9. $ vs #
• ${id} вставляет подстроку
select * from ${schema}.users
-> select * from secur.users
• #{id} создает параметризованный запрос
select * from secur.users where id=#{id}
-> select * from secur.users where id=#{id}
10. Где использовать $?
• Где нельзя использовать параметр
• select * from users order by ${field}
• Для конфигурационных настроек
• select * from ${schema}.users
• Одна константа на всё приложение
<configuration>
<properties>
<property name="schema" value="secur"/>
</properties>
</configuration>
13. Аудит: Общий предок
public class AuditableEntity {
private String createdByUser;
private String updatedByUser;
private Date createdDatetime;
private Date updatedDatetime;
private int version;
}
19. Оптимистическая блокировка
<update id="updatePerson">
update person set
name = #{name},
record_version = record_version + 1
where record_version = #{record_version}
</update>
int updated = session.update(“updatePerson”, person);
if (updated == 0)
throw new OptimisticLockingFailureException();
22. Сортировка
• Необходимо знать маппинг
• ПолеОбъекта -> СтолбецТаблицы
• Уже есть готовый маппинг
<resultMap type="Person" id="PersonMap">
<id property="id" column="person_id"/>
<result property="name" column="person_name"/>
</resultMap>
23. Сортировка
MappedStatement ms = config.getMappedStatement(statement);
for (ResultMapping m :
ms.getResultMaps().get(0)
.getPropertyResultMappings()) {
if (m.getProperty().equals(userEnteredSortField))
return m.getColumn();
}