在Springboot中如何直接执行SQL语句

时间:2025-01-22 08:02:42

使用MyBatis或MyBatis-Plus

若使用框架集成了MyBatis-Plus,你可以通过Mapper接口来执行自定义的SQL语句。

a. 在Mapper接口中定义方法。

public interface YourEntityMapper extends BaseMapper<YourEntity> {
    @Select("SELECT * FROM your_table WHERE some_column = #{someValue}")
    List<YourEntity> selectBySomeColumn(@Param("someValue") String someValue);
}

b. 在Service层调用Mapper方法。

@Service
public class YourEntityServiceImpl extends ServiceImpl<YourEntityMapper, YourEntity> implements IYourEntityService {
    public List<YourEntity> selectBySomeColumn(String someValue) {
        return baseMapper.selectBySomeColumn(someValue);
    }
}