第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

使用 spring data jpa 存儲(chǔ)庫在 Hql 查詢后刷新()

使用 spring data jpa 存儲(chǔ)庫在 Hql 查詢后刷新()

catspeake 2023-06-21 15:37:52
我正在使用@Queryspring 數(shù)據(jù) jpa 存儲(chǔ)庫中的注釋編寫一些 hql 查詢。我知道我可以使用存儲(chǔ)庫接口中的方法,但出于學(xué)習(xí)目的,我正在明確編寫它們。這是我的主課@SpringBootApplicationpublic 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}一切都運(yùn)行良好,但是對于deleteOperationUsingHql(),即使我從數(shù)據(jù)庫中刪除了這個(gè)人,即使我將修改刷新到數(shù)據(jù)庫,方法id=1仍然返回了那個(gè)人findById(1L)。我應(yīng)該怎么做才能返回findById(1L)一個(gè)空的可選。我的第二個(gè)問題是關(guān)于注釋@Transactional,我知道它的詳細(xì)工作原理,但我不知道為什么如果我們刪除它,我們會(huì)得到以下異常引起原因:javax.persistence.TransactionRequiredException:執(zhí)行更新/刪除查詢@Transactional有人可以解釋為什么我在刪除時(shí)遇到此異常。
查看完整描述

1 回答

?
www說

TA貢獻(xiàn)1775條經(jīng)驗(yàn) 獲得超8個(gè)贊

即使我從數(shù)據(jù)庫中刪除了這個(gè)人,即使我將修改刷新到數(shù)據(jù)庫中,id=1 的人仍然由 findById(1L) 方法返回

這很正常,因?yàn)槟褂貌樵儊韯h除人員,而不是實(shí)際使用存儲(chǔ)庫(以及 EntityManager)刪除方法。查詢完全繞過會(huì)話緩存,因此 Hibernate 不知道此人已被刪除,并返回其緩存中的實(shí)例。解決方案:不要使用查詢。替代解決方案,刪除后清除緩存(例如通過將注釋clearAutomatically的標(biāo)志設(shè)置Modifying為 true)。

有人可以解釋為什么在刪除 @Transactional 時(shí)我會(huì)收到此異常。

因?yàn)?when@Transactional被刪除,在執(zhí)行該方法之前,SPring 沒有啟動(dòng)任何事務(wù),從錯(cuò)誤消息中可以看出,刪除查詢必須在事務(wù)內(nèi)部執(zhí)行。


查看完整回答
反對 回復(fù) 2023-06-21
  • 1 回答
  • 0 關(guān)注
  • 158 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號