无法在 Spring JPA 休眠中获取关系

Posted

技术标签:

【中文标题】无法在 Spring JPA 休眠中获取关系【英文标题】:Cannot get the relations in Spring JPA hibrenate 【发布时间】:2014-09-21 12:53:25 【问题描述】:

我正在使用 Spring MVC/Security/JPA/Hibernate 开发一个 Web 应用程序。

我有一个与 UserRole 有 OneToMany 关系的 User 类。

@Entity
@Table(name = "user_accounts")
@SuppressWarnings("serial")
public class User extends SimpleBaseEntity<Long> implements Serializable 

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;

    @Column(name = "email", length = 100, nullable = false, unique = true)
    private String email;

    @Column(name = "first_name", length = 100,nullable = false)
    private String firstName;

    @Column(name = "last_name", length = 100, nullable = false)
    private String lastName;

    @Column(name = "password", length = 255)
    private String password;

    @OneToMany(fetch = FetchType.EAGER, cascade=CascadeType.ALL, mappedBy="user")
    @NotFound(action=NotFoundAction.IGNORE)
    private List<UserRole> roles;

    @Enumerated(EnumType.STRING)
    @Column(name = "sign_in_provider", length = 20)
    private SocialMediaService signInProvider;

    @Lob
    @Basic(fetch = FetchType.LAZY)
    @Column(name = "user_image", length=16777216)
    private byte[] userImage;


    ... skip


UserRole 类与 User 有 ManyToOne 关系。

@Entity
@Table(name = "user_roles")
@SuppressWarnings("serial")
public class UserRole implements Serializable 

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id", nullable = false, unique = true)
    private Long id;

    @Column(name = "user_id", length = 100, nullable = true)
    private String userId;

    @Enumerated(EnumType.STRING)
    @Column(name = "role", length = 20, nullable = false)
    private Role role;

    @ManyToOne
    @JoinColumn(name="user_id", referencedColumnName="email", insertable=false, updatable=false, nullable=false)
    @NotFound(action=NotFoundAction.IGNORE)
    private User user;

    ... skip


User Repository 界面非常简单。

public interface UserRepository extends JpaRepository<User, Long> 

    public User findByEmail(String email);


当我使用下面的代码 sn-p 使用存储库加载用户信息时,它会很好地检索 User 和 UserRole 数据。

User user = userRepository.findByEmail("some@email.com");  // OK both User and UserRole

这是日志文件。

Hibernate: 
    select
        user0_.id as id1_9_,
        user0_.creation_time as creation2_9_,
        user0_.modification_time as modifica3_9_,
        user0_.email as email4_9_,
        user0_.first_name as first_na5_9_,
        user0_.last_name as last_nam6_9_,
        user0_.password as password7_9_,
        user0_.sign_in_provider as sign_in_8_9_,
        user0_.user_image as user_ima9_9_ 
    from
        user_accounts user0_ 
    where
        user0_.email=?
Hibernate: 
    select
        roles0_.user_id as user_id3_9_1_,
        roles0_.id as id1_10_1_,
        roles0_.id as id1_10_0_,
        roles0_.role as role2_10_0_,
        roles0_.user_id as user_id3_10_0_ 
    from
        user_roles roles0_ 
    where
        roles0_.user_id=?
Hibernate: 
    select
        user0_.id as id1_9_1_,
        user0_.creation_time as creation2_9_1_,
        user0_.modification_time as modifica3_9_1_,
        user0_.email as email4_9_1_,
        user0_.first_name as first_na5_9_1_,
        user0_.last_name as last_nam6_9_1_,
        user0_.password as password7_9_1_,
        user0_.sign_in_provider as sign_in_8_9_1_,
        user0_.user_image as user_ima9_9_1_,
        roles1_.user_id as user_id3_9_3_,
        roles1_.id as id1_10_3_,
        roles1_.id as id1_10_0_,
        roles1_.role as role2_10_0_,
        roles1_.user_id as user_id3_10_0_ 
    from
        user_accounts user0_ 
    left outer join
        user_roles roles1_ 
            on user0_.email=roles1_.user_id 
    where
        user0_.email=?

但是,问题就在这里。

如果我使用 UserRepository 的 save(merge) 方法更新服务类中的用户信息,则相同的 findByEmail 方法不会检索 UserRole(roles) 信息,而只会检索用户信息。

User oldUser = userRepository.findByEmail("some@email.com");  // OK both User and UserRole(roles)

// ... some modifications of "oldUser"

userService.updateUser(oldUser);  // This is Transactional and the table record is updated OK.

User newUser = userRepository.findByEmail("some@email.com");  // UserRole(roles) data is null

休眠日志文件如下。

# findByEmail oldUser
Hibernate: 
    select
        user0_.id as id1_9_,
        user0_.creation_time as creation2_9_,
        user0_.modification_time as modifica3_9_,
        user0_.email as email4_9_,
        user0_.first_name as first_na5_9_,
        user0_.last_name as last_nam6_9_,
        user0_.password as password7_9_,
        user0_.sign_in_provider as sign_in_8_9_,
        user0_.user_image as user_ima9_9_ 
    from
        user_accounts user0_ 
    where
        user0_.email=?
Hibernate: 
    select
        roles0_.user_id as user_id3_9_1_,
        roles0_.id as id1_10_1_,
        roles0_.id as id1_10_0_,
        roles0_.role as role2_10_0_,
        roles0_.user_id as user_id3_10_0_ 
    from
        user_roles roles0_ 
    where
        roles0_.user_id=?
Hibernate: 
    select
        user0_.id as id1_9_1_,
        user0_.creation_time as creation2_9_1_,
        user0_.modification_time as modifica3_9_1_,
        user0_.email as email4_9_1_,
        user0_.first_name as first_na5_9_1_,
        user0_.last_name as last_nam6_9_1_,
        user0_.password as password7_9_1_,
        user0_.sign_in_provider as sign_in_8_9_1_,
        user0_.user_image as user_ima9_9_1_,
        roles1_.user_id as user_id3_9_3_,
        roles1_.id as id1_10_3_,
        roles1_.id as id1_10_0_,
        roles1_.role as role2_10_0_,
        roles1_.user_id as user_id3_10_0_ 
    from
        user_accounts user0_ 
    left outer join
        user_roles roles1_ 
            on user0_.email=roles1_.user_id 
    where
        user0_.email=?

    # Update User
    update
        user_accounts 
    set
        modification_time=?,
        email=?,
        first_name=?,
        last_name=?,
        password=?,
        sign_in_provider=?,
        user_image=? 
    where
        id=?

# findByEmail newUser
Hibernate: 
    select
        user0_.id as id1_9_,
        user0_.creation_time as creation2_9_,
        user0_.modification_time as modifica3_9_,
        user0_.email as email4_9_,
        user0_.first_name as first_na5_9_,
        user0_.last_name as last_nam6_9_,
        user0_.password as password7_9_,
        user0_.sign_in_provider as sign_in_8_9_,
        user0_.user_image as user_ima9_9_ 
    from
        user_accounts user0_ 
    where
        user0_.email=?

有人可以帮我吗?

提前致谢。

【问题讨论】:

你开启延迟加载了吗? 如果您感到困惑,请查看我写的教程here。它包含有关如何配置不同类型的关系的示例,以及如何配置延迟加载和一堆其他方便的东西,如果你正在学习 hibernate,它们会有所帮助。 @vipincp 一些列是通过延迟加载获取的,但角色列不是。它应该由我通过注释定义的 EAGER 类型获取。我错了吗? 【参考方案1】:

终于找到了缺少关系列表数据的原因。

这是我的交易设置错误。

“updateUser(oldUser)”方法不是事务性的。

在我将其更改为事务性之后,一切正常。

User oldUser = userRepository.findByEmail("some@email.com");  // OK both User and UserRole(roles)

// ... some modifications of "oldUser"

userService.updateUser(oldUser);  // This was not Transactional and it was the reason of the problem.

User newUser = userRepository.findByEmail("some@email.com");  // UserRole(roles) data is null

【讨论】:

以上是关于无法在 Spring JPA 休眠中获取关系的主要内容,如果未能解决你的问题,请参考以下文章

休眠 JPA 错误

使用@Query和休眠更新spring数据jpa中的布尔值

Spring Boot JPA多对多关系-Rest Web Service无法返回子对象

带有休眠应用程序的 Spring Boot 无法启动

Spring Boot JPA多对多关系-Rest Web Service无法获取Get All中的所有子属性

Spring Boot Jpa:默认休眠?