簡體   English   中英

FetchType.Lazy 在 spring 引導中的 JPA 中不起作用

[英]FetchType.Lazy not working in JPA in spring boot

我有一個實體 Order.java 為:

package in.ashwin.onlinebookstore.entity;

import java.util.Date;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
import javax.persistence.Table;

@Entity
@Table(name="tbl_order")
public class Order {
    
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long order_id;
    
    @OneToOne(cascade = CascadeType.MERGE,fetch = FetchType.LAZY)
    @JoinColumn(name = "user_id", nullable = false)
    private User user;
    
    @Column(name="today_date")
    private Date todayDate;
    
    @Column(name="status")
    private String status;
    
    public Order(User user, Date todayDate) {
        
        this.user = user;
        this.todayDate = todayDate;
        this.status="pending";
    }

    public Long getOrder_id() {
        return order_id;
    }

    public void setOrder_id(Long order_id) {
        this.order_id = order_id;
    }

    public String getStatus() {
        return status;
    }

    

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public Date getTodayDate() {
        return todayDate;
    }

    public void setTodayDate(Date todayDate) {
        this.todayDate = todayDate;
    }
    
    public Order() {
        
    }

}

I have included Fetchtype as lazy between User and Order.Since,I have declared FetchType.LAZY while fetching Order then,I am still seeing user object called when I tested from postman.According to my understanfing,the object of FetchType.LAZY is only在需要時調用。如果沒有調用,則忽略它。

 @OneToOne(cascade = CascadeType.MERGE,fetch = FetchType.LAZY)
        @JoinColumn(name = "user_id", nullable = false)
        private User user;

我的 api 獲得所有訂單是:

@GetMapping("/getAllPendingOrders")
    @PreAuthorize("hasRole('USER') or hasRole('MODERATOR') or hasRole('ADMIN')")
    public ResponseEntity<?> getOrders(Pageable pageable) {
        
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        String user = auth.getName();
        UserDetailsImpl userDetails=(UserDetailsImpl)userdetailService.loadUserByUsername(user);
        
        Page<Order> orderList=orderRep.findByUserId(userDetails.getId(),pageable);
        if(orderList!=null) {
             return new ResponseEntity(orderList, HttpStatus.OK);
        }
        else {
             return new ResponseEntity("Noorders", HttpStatus.OK);
        }
       
        
    }

我從 POSTMAN 得到的回復是:

{
    "content": [
        {
            "order_id": 1,
            "user": {
                "id": 1,
                "username": "ashwin",
                "email": "ashwin@gmail.com",
                "password": "$2a$10$GoGUJh0Tzml5egBW5Wzbj.VLzfq4Z7YNCMnsOynLWufpQrWBdVLVi",
                "roles": [
                    {
                        "id": 2,
                        "name": "ROLE_MODERATOR"
                    },
                    {
                        "id": 1,
                        "name": "ROLE_USER"
                    }
                ]
            },
            "todayDate": "2020-07-02T17:09:45.057+0000",
            "status": "pending"
        },
        {
            "order_id": 2,
            "user": {
                "id": 1,
                "username": "ashwin",
                "email": "ashwin@gmail.com",
                "password": "$2a$10$GoGUJh0Tzml5egBW5Wzbj.VLzfq4Z7YNCMnsOynLWufpQrWBdVLVi",
                "roles": [
                    {
                        "id": 2,
                        "name": "ROLE_MODERATOR"
                    },
                    {
                        "id": 1,
                        "name": "ROLE_USER"
                    }
                ]
            },
            "todayDate": "2020-07-02T17:15:06.906+0000",
            "status": "pending"
        },
        {
            "order_id": 3,
            "user": {
                "id": 1,
                "username": "ashwin",
                "email": "ashwin@gmail.com",
                "password": "$2a$10$GoGUJh0Tzml5egBW5Wzbj.VLzfq4Z7YNCMnsOynLWufpQrWBdVLVi",
                "roles": [
                    {
                        "id": 2,
                        "name": "ROLE_MODERATOR"
                    },
                    {
                        "id": 1,
                        "name": "ROLE_USER"
                    }
                ]
            },
            "todayDate": "2020-07-02T17:16:36.373+0000",
            "status": "pending"
        },
        {
            "order_id": 4,
            "user": {
                "id": 1,
                "username": "ashwin",
                "email": "ashwin@gmail.com",
                "password": "$2a$10$GoGUJh0Tzml5egBW5Wzbj.VLzfq4Z7YNCMnsOynLWufpQrWBdVLVi",
                "roles": [
                    {
                        "id": 2,
                        "name": "ROLE_MODERATOR"
                    },
                    {
                        "id": 1,
                        "name": "ROLE_USER"
                    }
                ]
            },
            "todayDate": "2020-07-02T17:18:56.799+0000",
            "status": "pending"
        }
       
    ],
    "pageable": {
        "sort": {
            "sorted": false,
            "unsorted": true,
            "empty": true
        },
        "offset": 0,
        "pageNumber": 0,
        "pageSize": 20,
        "paged": true,
        "unpaged": false
    },
    "totalPages": 2,
    "last": false,
    "totalElements": 39,
    "size": 20,
    "number": 0,
    "sort": {
        "sorted": false,
        "unsorted": true,
        "empty": true
    },
    "numberOfElements": 20,
    "first": true,
    "empty": false
}

I am still seeing the user object in my JSON.USing, @JSONIgnore works,but since I have declared it as Fetchtype.Lazy why the USER object is coming when I am fetching Order object?I dont want the User object to appear,when我正在獲取訂單 object。

在對它進行顯式調用之前,不會初始化User實體數據並將其加載到 memory 中。 您的Order實體包含user字段。 因此,當序列化用戶調用的訂單數據獲取器並使用另一個查詢獲取用戶數據時。

如果您不想使用@JsonIgnore,請為沒有用戶字段的訂單創建響應 class 和 map 您的數據。

對我來說添加@JsonIgnore注釋有幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM