Spring Boot 3.3 Spring Boot 整合JPA-原生SQL支持
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.transaction.Transactional;
@Component
public class NativeSQLRunner implements ApplicationRunner {
@PersistenceContext
private EntityManager entityManager;
@Override
@Transactional
public void run(ApplicationArguments args) {
// 执行原生SQL查询
String sql = "SELECT * FROM user";
List<Object[]> resultList = entityManager.createNativeQuery(sql).getResultList();
resultList.forEach(row -> {
// 处理查询结果
for (Object field : row) {
System.out.print(field.toString() + " ");
}
System.out.println();
});
// 执行原生SQL更新
sql = "UPDATE user SET status = 'inactive' WHERE status = 'active'";
int updateCount = entityManager.createNativeQuery(sql).executeUpdate();
System.out.println("Number of users updated: " + updateCount);
}
}
这段代码使用了Spring Boot的ApplicationRunner
接口,在应用启动完成后执行了一些原生SQL查询和更新操作。它展示了如何使用EntityManager
来创建和执行原生SQL语句,并处理查询结果。注意,这里的@Transactional
注解确保了操作在同一个事务内进行,并且在操作完成后,事务会根据执行结果进行提交或回滚。
评论已关闭