Carolina Ponce
Carolina Ponce

Reputation: 43

Avoid jpa fetch eager with join table

I have the next classes:

A class User:

@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 class Role:

@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:

@Service
public class UserService implements IUserService{

    @Autowired
    UserRepository repository;

    public User findUserByLdapId(String loginName) {

        return repository.findUserByLdapId(loginName);
    }
}

Repository:

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

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


}

Controller:

@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);

    };
}

As you can see I have a role in a user and a list of roles. The one called uType would be something like a main role, and the list, secondary roles. I know that this role will appear twice but I don't care about it at all.

I would like to have the main role fetched eager and the list of roles fetched lazy, on demand, is it possible?

So a json would looks like:

{
    "user": {
        "userId": 1,
        "fullName": "Carolina Ponce",
        "ldapId": "f8cygqn",
        "email": "[email protected]",
        "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": ""
    }
}

Thanks in advance!

Upvotes: 1

Views: 1667

Answers (1)

Augusto
Augusto

Reputation: 29927

I'm not sure if I understand your questions correctly as Jpa/Hibernate does this by default. All *ToOne relationships are eager by default, while all *ToMany are lazy by default.

From the docs of @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

And from the docs of @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

Upvotes: 1

Related Questions