避免通过联接表渴望获取JPA

时间:2019-05-27 13:41:11

标签: java jpa

我上下一节课:

A类用户:

@Entity
@JsonRootName(value = "user")
@Table(name = "web_users", schema = "t_dw_comercial")
public class User {


   @Id
   private int userId;

   private String fullName;

   private String ldapId;

   private String email;


   @ManyToOne
    @JoinColumn(name= "u_type", nullable=false)
    private Role uType;

    private String deleteFlag;

    private String typeAccess;

    @OneToMany(fetch=FetchType.LAZY)
    @JoinTable(name="web_users_roles",
    joinColumns = {@JoinColumn(name="user_id")},
    inverseJoinColumns = {@JoinColumn(name="role_id")}
    )
    private List<Role> roles;

}

A类角色:

@Entity
@JsonRootName(value = "roles")
@Table(name = "web_roles", schema = "t_dw_comercial")
public class Role {

   @Id
   private int roleId;

   private String roleName;

   @OneToMany 
   @JoinTable(name="web_users_roles",
        joinColumns = {@JoinColumn(name="user_id")},
        inverseJoinColumns = {@JoinColumn(name="role_id")})
   private List<Section> sections = new ArrayList<Section>();


}

服务:

@Service
public class UserService implements IUserService{

    @Autowired
    UserRepository repository;

    public User findUserByLdapId(String loginName) {

        return repository.findUserByLdapId(loginName);
    }
}

存储库:

@Repository
public interface UserRepository extends CrudRepository<User, Long>{

    @Query("SELECT u FROM User u where u.ldapId= ?1")
public User findUserByLdapId(String loginName);


}

控制器:

@Controller
@RestController
public class UserController {

    @Autowired
    private IUserService userService;

    @CrossOrigin
    @RequestMapping(value = "/dashboard", params = {"user"}, method = RequestMethod.GET,  produces = "application/json")
    public ResponseEntity<User>  getUser(@RequestParam(value = "user") String ldapId) {

        User user =  userService.findUserByLdapId(ldapId);

        if(user == null)
            return new ResponseEntity<>(HttpStatus.NO_CONTENT);

        return new ResponseEntity<>(user, HttpStatus.OK);

    };
}

如您所见,我在用户中有一个角色,并且有一个角色列表。称为uType的角色将类似于主要角色,而列表则是次要角色。我知道这个角色会出现两次,但是我一点也不在乎。

我想让主要角色渴望获得,而角色列表则可以根据需要懒惰获取,

所以json看起来像:

{
    "user": {
        "userId": 1,
        "fullName": "Carolina Ponce",
        "ldapId": "f8cygqn",
        "email": "carolina@blabla.com",
        "uType": {
            "roleId": 1,
            "roleName": "Admin",
            "sections": [
                {
                    "sectionId": 2,
                    "sectionName": "Admin",
                    "components": []
                },
                {
                    "sectionId": 1,
                    "sectionName": "Dashboard",
                    "components": [
                        {
                            "componentId": 2,
                            "componentName": "Provincia",
                            "jsonArray": [
                                {
                                    "ID": "6",
                                    "NAME": "BUENOS AIRES"
                                }
                            ]
                        },
                        {
                            "componentId": 1,
                            "componentName": "Rubros",
                            "jsonArray": [
                                {
                                    "ID": "1",
                                    "NAME": "Automotriz"
                                },
                                {
                                    "ID": "31",
                                    "NAME": "Universidades"
                                }
                            ]
                        }
                    ]
                }
            ]
        },
        "deleteFlag": "",
        "typeAccess": ""
    }
}

谢谢!

1 个答案:

答案 0 :(得分:1)

我不确定我是否正确理解您的问题,因为Jpa / Hibernate默认情况下会这样做。默认情况下,所有* ToOne关系都是渴望的,而所有* ToMany关系都是默认懒惰的。

摘自@OneToMany的文档。

public abstract FetchType fetch

    (Optional) Whether the association should be lazily loaded or must be eagerly
    fetched. The EAGER strategy is a requirement on the persistence provider runtime 
    that the associated entities must be eagerly fetched. The LAZY strategy is a 
    hint to the persistence provider runtime.

Default:
    javax.persistence.FetchType.LAZY

并且来自@ManyToOne

的文档
public abstract FetchType fetch

   (Optional) Whether the association should be lazily loaded or must be eagerly 
   fetched. The EAGER strategy is a requirement on the persistence provider runtime
   that the associated entity must be eagerly fetched. The LAZY strategy is a hint 
   to the persistence provider runtime.

Default:
   javax.persistence.FetchType.EAGER