春データを返すのヌルとの双方向の関係で@Transactional

P.Juchimowicz:

私は春のデータと(試験後の自動ロールバック用)@Transactionalのアノテーションを使用しています。私はアカウントとユーザー(所有側)の間の単純な双方向の関係を持っています:

@Entity
@Table(name = "ACCOUNT_T")
public class AccountEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String email;
    private String password;
    private String verificationCode;
    private Boolean active = false;

    @OneToOne(mappedBy = "account", fetch = FetchType.EAGER, 
              cascade = {CascadeType.MERGE, CascadeType.PERSIST,
                         CascadeType.DETACH, CascadeType.REFRESH})
    private UserEntity user;
}

@Entity
@Table(name = "USER_T")
public class UserEntity {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;
    private String surname;
    private String phone;
    private LocalDate birthDate;

    @OneToOne(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER)
    @JoinColumn(name = "account_id")
    private AccountEntity account;
}

私はJpaRepositoriesを使用していますが、フェッチを熱心に設定されています。私は、データベースからオブジェクトを取得するときに、なぜ時々私は彼らの子オブジェクト-nullが返され得ることができません。それは私がオブジェクトを追加した側からによって異なります。私はJunit5を使用して簡単なテストを書かれています:

@ExtendWith(SpringExtension.class)
@SpringBootTest
@Transactional
class UserAndAccountRepositoriesTest {

    void testA() {
        UserEntity userEntity = new UserEntity();
        setUserProperties(userEntity);
        AccountEntity accountEntity = new AccountEntity();
        setAccountProperties(accountEntity); //just setting values for fields
        accountEntity.setUser(userEntity);
        accountRepository.save(accountEntity);

        accountRepository.findAll().get(0).getUser(); //returns user
        userRepository.findAll().get(0).getAccount(); //returns null,but should return account related to that user
    }

    void testB() {
        UserEntity userEntity = new UserEntity();
        setUserProperties(userEntity);
        AccountEntity accountEntity = new AccountEntity();
        setAccountProperties(accountEntity);
        accountEntity.setUser(userEntity);
        accountRepository.save(accountEntity);

        accountRepository.findAll().get(0).getUser(); //again returns null,but shouldn't
        userRepository.findAll().get(0).getAccount(); //returns account
    }
}

なければ@Transactionalすべてが正常に動作します-私はNULLを取得しておりません。何が私が間違っているのでしょうか?

buræquete:

あなたは明示的に定義するための関係の両側を設定する必要があると思います。追加してみてくださいuserEntity.setAccount(accountEntity)、あなたのセットアップケースの間に、これは問題を解決するでしょう。

Hibernateはあなたを助ける、あなたが設定理由だけ負いませんa -> b、それが設定されますb <- a他のエンティティ以内にあなたのために。

それはなしでうまくいくかもしれない理由は、@Transactionalあなたが使用しているどんなデータソースにあなたの設定データをコミットしている注釈なし、それである、そして何も終わりにロールバックされていない、とあなたはどんなことなく、データを選択しているためidfindAll、あなたは前のユーザーを取得しています/すでになしの関係&いくつか、あなたが取得しているため、ランダムエラーでいくつかの、コミットされたentitesを占めています。

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=188372&siteId=1