SMALL PIECES, CLEAR IDEAS

用一段代码,说明一个想法.

可阅读、可复制的小例子。结合文章理解背景,再放进自己的实践。

JAVA / EXAMPLE

用预编译 SQL 防止注入

用 #{} 占位符传参,MyBatis 会生成预编译 SQL,把参数当字符串处理,避免拼接注入。

EmpMapper.java
@Select("select * from emp where id = #{id}")
public Emp getById(Integer id);

@Select("select * from emp where name like concat('%',#{name},'%') "
        + "and gender = #{gender} "
        + "and entrydate between #{begin} and #{end} "
        + "order by update_time desc")
public List<Emp> search(String name, Integer gender,
                        LocalDate begin, LocalDate end);
JAVA / EXAMPLE

用 @Transactional 声明事务边界

在类或方法上标注 @Transactional,事务参数与 XML 配置一致:隔离级别、传播行为、只读。

AccountServiceImpl.java
@Service("accountService")
@Transactional(isolation = Isolation.REPEATABLE_READ)
public class AccountServiceImpl implements AccountService {

    @Autowired
    private AccountDao accountDao;

    @Transactional(isolation = Isolation.READ_COMMITTED,
                   propagation = Propagation.REQUIRED)
    public void transfer(String outMan, String inMan, double money) {
        accountDao.out(outMan, money);
        accountDao.in(inMan, money);
    }
}
JAVA / EXAMPLE

时间类型怎么选

按精度与需求选择:LocalDate 对 DATE、LocalDateTime 对 DATETIME、Instant 对时间戳。

TimeTypes.java
LocalDate date = LocalDate.now();               // 年-月-日
LocalTime time = LocalTime.now();               // 时:分:秒.纳秒
LocalDateTime datetime = LocalDateTime.now();   // 日期 + 时间
Instant instant = Instant.now();                // UTC 瞬时点

// 数据库映射:DATE -> LocalDate, TIME -> LocalTime,
// DATETIME/TIMESTAMP -> LocalDateTime,
// TIMESTAMP WITH TIME ZONE -> ZonedDateTime / OffsetDateTime