天天看點

SpringData中的@Transactional和@Modifying的作用

**

SpringData中自定義方法删除整表資料出現報錯問題

**

@Test
	public void test08(){
		ApplicationContext context=
				new ClassPathXmlApplicationContext("applicationContext.xml");
		StuRepository proxy=context.getBean(StuRepository.class);
		proxy.delete();
	}		
           

隻加@Query注解

public interface StuRepository extends Repository<Student, Integer>{
	@Query(nativeQuery=true,value="delete from stu")
	void delete();
}
           

會報錯

Hibernate: 
    delete 
    from
        stu
一月 16, 2021 6:59:45 下午 org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 0, SQLState: S1009
一月 16, 2021 6:59:45 下午 org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Can not issue data manipulation statements with executeQuery().
           

這裡需要注意必須加上@Transactional(開啟事務)和@Modifying(通知jpa這是一個delete操作,允許修改)

@Transactional
	@Modifying
	@Query(nativeQuery=true,value="delete from stu")
	void delete();
           

執行成功

mysql> select * from stu;
+----+------+-------------+
| id | age  | name        |
+----+------+-------------+
|  1 |   23 | wanghanxuan |
|  2 |   23 | rose        |
|  3 |   18 | tim         |
|  4 |   35 | jim         |
|  5 |   30 | jary        |
+----+------+-------------+
5 rows in set (0.00 sec)

mysql> select * from stu;
Empty set (0.00 sec)