在Spring Boot 框架中,若要执行SQL 语句实现与数据库进行交互的操作。你可以使用Spring Data JPA、MyBatis 或MyBatis-Plus 等ORM(对象关系映射)框架来执行SQL语句。
以下是Spring Boot 框架中执行SQL语句的方法:
-
使用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); } }
-
使用JdbcTemplate
框架也支持Spring的JdbcTemplate来执行原生SQL语句。
a. 在你的Service层注入JdbcTemplate。
@Autowired private JdbcTemplate jdbcTemplate;
b. 使用JdbcTemplate执行SQL语句。
public List<Map<String, Object>> executeSql(String sql) { return jdbcTemplate.queryForList(sql); }
-
直接在Mapper XML文件中写SQL
若依框架中MyBatis的Mapper接口通常会有对应的XML文件,你可以在这个文件中编写SQL语句。
<select id="selectBySomeColumn" resultType="YourEntity"> SELECT * FROM your_table WHERE some_column = #{someValue} </select>
-
使用MyBatis-Plus的自定义方法
MyBatis-Plus支持自定义SQL方法,你可以在Mapper接口中继承BaseMapper,并定义自己的方法,然后在对应的XML文件中编写SQL语句。
-
注意事项
- 执行SQL语句时,注意防止SQL注入攻击,使用预编译的SQL语句或ORM框架提供的参数绑定机制。
- 对于复杂的SQL语句,建议先在数据库管理工具中测试,确保SQL语句的正确性。
- 确保你的数据库连接配置正确,包括URL、用户名、密码等。
请根据你的实际需求选择合适的方法来执行SQL语句。