eclipse中搭建springboot學習(8)---JPA使用2(自定義sql)
PersonRepository
package com.example.demo1019.dao;
import javax.transaction.Transactional;
import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.jpa.repository.Query;
import com.example.demo1019.dto.PersonDTO;
public interface PersonRepository extends JpaRepository<PersonDTO, Long> {
其實Spring data 覺大部分的SQL都可以根據方法名定義的方式來實現,但是由於某些原因我們想使用自定義的SQL來查詢,springdata也是完美支援的;在SQL的查詢方法上面使用@Query註解,如涉及到刪除和修改在需要加上@Modifying.也可以根據需要新增 @Transactional對事物的支援,查詢超時的設定等
@Transactional @Modifying @Query("delete from PersonDTO where age= ?1") // sql中的表明必須是DTO的名字,而不是資料庫中表的名字 public void deleteByAge(int age); }
PersonService新增方法
public void deleteByAge(int age) { personRepository.deleteByAge(age); }
PersonController新增方法
/** * 按年紀刪除資料 * @param age * @return */ @RequestMapping("/deletePersonByAge/{age}") @ResponseBody public String deletePerson(@PathVariable("age") int age) { personService.deleteByAge(age); return "刪除成功"; }