我正在使用@Queryspring 数据 jpa 存储库中的注释编写一些 hql 查询。我知道我可以使用存储库接口中的方法,但出于学习目的,我正在明确编写它们。
这是我的主课
@SpringBootApplication
public class Main implements CommandLineRunner {
@Autowired
PersonRepository personRepository;
public static void main( String[] args ) {
SpringApplication.run(Main.class, args);
}
/**
* if we delete the transactional annotation-> we get an exception
*/
@Override
@Transactional
public void run( String... args ) throws Exception {
saveOperation();
deleteOperationUsingHql();
}
private void saveOperation() {
Person p = new Person("jean", LocalDate.of(1977,12,12));
personRepository.save(p);
}
private void deleteOperationUsingHql() {
personRepository.deleteUsingHql(1L);
personRepository.flush();
Optional<Person> p = personRepository.findById(1L);
if (p.isPresent()){
System.out.println("still present");
}
}
}
我的 personRepository 界面
public interface PersonRepository extends JpaRepository<Person, Long> {
@Query(value = "select p from Person p where p.id=?1")
List<Person> getById( Long id);
@Modifying
@Query(value = "delete from Person p where p.id=:id")
void deleteUsingHql( Long id );
}
人物类
@Entity
@Table(name = "Person")
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private LocalDate date;
// constructors,getters...omitted for brievety
}
一切都运行良好,但是对于deleteOperationUsingHql(),即使我从数据库中删除了这个人,即使我将修改刷新到数据库,方法id=1仍然返回了那个人findById(1L)。我应该怎么做才能返回findById(1L)一个空的可选。
我的第二个问题是关于注释@Transactional,我知道它的详细工作原理,但我不知道为什么如果我们删除它,我们会得到以下异常
引起原因:javax.persistence.TransactionRequiredException:执行更新/删除查询
@Transactional有人可以解释为什么我在删除时遇到此异常。
www说
相关分类