解决JPA懒加载的办法

本文介绍了一对多关系在Java实体类中的实现方法,包括使用@ToString()注解优化多对一的显示方式,以及如何通过不同策略解决一对多关联问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

方案1:

    1.1、在多的一方的类上加上@ToString()注解,重写toString方法

    1.2、在代码中获取一的时候主动调用多的toString()方法:

uopUser.getUserChannelRelationList().toString();

方案2:

    2.1、在代码中主动get多的一方的唯一主键:uopUser.getUserChannelRelationList().get[0].getId();


1、一对多的类

import lombok.*;

import javax.persistence.*;
import java.util.List;

@ToString()
@Entity
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "uop_user")
public class UopUser {

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

    private String userName;

    /**
     * 渠道
     */
    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY,mappedBy = "uopUser")
    private List<UserChannelRelation> userChannelRelationList;

    /**
     * 工业分类
     */
    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY,mappedBy = "uopUser")
    private List<UserCategoryRelation> userCategoryRelationList;

    /**
     *  分部
     */
    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY,mappedBy = "uopUser")
    private List<UserERPOrganizationFBRelation> userERPOrganizationFBRelationList;

    /**
     *  经营部门
     */
    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY,mappedBy = "uopUser")
    private List<UserERPOrganizationJYRelation> userERPOrganizationJYRelationList;


}

2、多的一方

import com.alibaba.fastjson.annotation.JSONType;
import com.efivestar.weaf.security.domain.ManageUser;
import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.*;
import org.springframework.validation.annotation.Validated;

import javax.persistence.*;
import java.util.Date;

@ToString(exclude = "uopUser")
@JSONType(ignores = "uopUser")
@Entity
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
@Table(name = "user_channel_relation")
public class UserChannelRelation {

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

    /**
     * 用户
     */
    @JsonIgnore
//    @JsonBackReference
    @ManyToOne
    @JoinColumn(name = "uop_user_id")
    private UopUser uopUser;

    /**
     * 渠道
     */
    @JsonIgnore
    @OneToOne(fetch = FetchType.LAZY)
    private Channel channel;

    /**
     * 可选状态
     */
    @Column(nullable = true)
    @Builder.Default
    private boolean checkFlag = false;

    /**
     * 修改时间
     */
    @Column(name = "update_time")
    private Date updateTime;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值