I want to create a spring boot rest controller with this specification :
Customers of an electricity and gas supply company can choose to receive their monthly bills either by email or by regular mail, neither or both.
My goal is to create java hibernate entities to manage these customers and their choices of sending bills.
A utility customer is identified by their email and can have multiple choice change events that change the customer choice status.
Each choice made by a customer generates a choice change event.
A choice change event relates to a customer. A customer can have multiple choice events.
Here are my java entities.
#Entity
#Table(name = "customers")
public class Customer {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#Email(message="this field must respect the email format !")
private String email;
#ManyToOne
private Choices choices;
}
#Entity
#Table(name = "choices")
public class Choices {
#Id
private String id;
#Column(name = "email")
private boolean isThisChoice;
#OneToOne
private Customer customer;
}
The resulting customer with id 24587 (GET request):
{
"id": "24587",
"email": "tartampion",
"choices": [
{
"id": "regular mail",
"isThisChoice": false
},
{
"id": "email",
"isThisChoice": true
}
]
}
Must I have an entity of management of event of choice of the customer
Here you have to use Many to Many Mapping.
Because one customer can have many choices and one choice can be opted by many customers.
package com.umesh.entity;
import com.fasterxml.jackson.annotation.JsonManagedReference;
import org.hibernate.annotations.LazyCollection;
import org.hibernate.annotations.LazyCollectionOption;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
#Entity
#Table(name="customer")
public class Customer {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="id")
private int id;
#Column(name="email")
private String email;
#ManyToMany(fetch=FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE, CascadeType.DETACH, CascadeType.REFRESH })
#JoinTable(
name="customer_choice",
joinColumns=#JoinColumn(name="customer_id"),
inverseJoinColumns=#JoinColumn(name="choice_id")
)
#LazyCollection(LazyCollectionOption.FALSE)
private List<Choice> choices;
public void Customer(){}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public List<Choice> getChoices() {
return choices;
}
public void setChoices(List<Choice> choices) {
this.choices = choices;
}
public void addChoices(Choice choice){
if(choices == null){
choices = new ArrayList<>();
choices.add(choice);
}
choices.add(choice);
}
}
package com.umesh.entity;
import org.hibernate.annotations.LazyCollection;
import org.hibernate.annotations.LazyCollectionOption;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
#Entity
#Table(name="choice")
public class Choice {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name="id")
private int id;
#Column(name="choice")
private String choice;
#ManyToMany(fetch=FetchType.LAZY, cascade = { CascadeType.PERSIST, CascadeType.MERGE, CascadeType.DETACH, CascadeType.REFRESH })
#JoinTable(
name="customer_choice",
joinColumns=#JoinColumn(name="choice_id"),
inverseJoinColumns=#JoinColumn(name="customer_id")
)
#LazyCollection(LazyCollectionOption.FALSE)
private List<Customer> customers;
public void Choics(){}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getChoice() {
return choice;
}
public void setChoice(String choice) {
this.choice = choice;
}
public List<Customer> getCustomers() {
return customers;
}
public void setCustomers(List<Customer> customers) {
this.customers = customers;
}
public void addCustomers(Customer customer){
if(customers == null){
customers = new ArrayList<>();
customers.add(customer);
}
customers.add(customer);
}
}
Did you mean a model more like:
#Entity
#Table(name = "customers")
public class Customer {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#Email(message="this field must respect the email format !")
private String email;
#ElementCollection
#CollectionTable(name="Choices")
#MapKeyColumn(name="CHOICE") //an "EMAIL" or "MAIL" string. You can use an enum instead if you want, but I wouldn't for upgrade reasons.
#Column(name="enabled")
private Map<String, Boolean> choices;
}
This will give you a Map of choices, resulting in JSON more like:
{
"id": "24587",
"email": "tartampion",
"choices": {
"MAIL": false,
"EMAIL": true
}
}
It should be much more expandable if you get other options and combinations in the future.
Similarly, you can use the same table structure with "Choices" as an entity:
#Entity
#Table(name = "customers")
public class Customer {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#Email(message="this field must respect the email format !")
private String email;
#OneToMany(mappedBy = "customer")
#MapKey(name="type") //don't need this if you want just a list
private Map<String, Choice> choices;
}
#Entity
#Table(name = "choices")
public class Choice {
#Id
#OneToOne
private Customer customer;
#Id
#Enumerated(EnumType.STRING)
private ChoiceType type;
#Column(name="enabled")
private boolean enabled;
}
#IdClass(EmployeeId.class)
public class ChoiceId implements Serializable {
private Integer customer;
private ChoiceType type;
}
public enum ChoiceType {
MAIL,
EMAIL;
}
Related
I have a JSON like this.
{
"productName":"soap",
"pQty":10,
"price" : 100,
"customerList":[
{
"name":"dasun",
"email":"lakmal#gmail.com",
"gender":"male"
},
{
"name":"BM",
"email":"BM#gmail.com",
"gender":"male"
}
]
}
I want to save this data into two separet tables called Product and Customer which having 1 to many relationship same as JSON`s appears.
I tried to save data using #OnetoMany but I couldn't. So I created entities like this.
#Data
#Entity
public class Product {
#Id
#GeneratedValue(strategy= GenerationType.AUTO)
#Column(name = "product_id",updatable = false, nullable = false)
private Long pId;
private String productName;
private int pQty;
private int price;
#ManyToOne
#JoinColumn(name = "customer_id")
private Customer customer;
}
Customer Entity
#Data
#Entity
public class Customer {
#Id
#GeneratedValue(strategy= GenerationType.AUTO)
#Column(name = "customer_id",updatable = false, nullable = false)
private Long custId;
private String name;
private String email;
private String gender;
}
My Rest Controller
#PostMapping(path = "/save/product",produces = MediaType.APPLICATION_JSON_VALUE)
public Iterable<Product> saveProduct(#RequestBody Product product){
Iterable<Product> response = automantionApiService.saveProduct(product);
return response;
}
My Repositories
#Repository
public interface ProductRepository extends JpaRepository<Product,Long> {
}
#Repository
public interface CustomerRepository extends JpaRepository<Customer,Long> {
}
This is where I want your attention. here what I`m doing is iterating request and trying to create new data rows as same as the request and save to DB.
#Override
public Iterable<Product> saveProduct(Product product) {
Product product1 = new com.adl.dte.core.model.Product();
product1.setProductName(product.getProductName());
product1.setPQty(product.getPQty());
product1.setPrice(product.getPrice());
Customer customer = new Customer();
List<Customer> customerList = new ArrayList<>();
if(!product.getCustomerList().isEmpty()){
product.getCustomerList().forEach( listOfCust ->{
customer.setName(listOfCust.getName());
customer.setEmail(listOfCust.getEmail());
customer.setGender(listOfCust.getGender());
customerRepository.save(customer);
product1.setCustomer(customer);
productRepository.save(product1);
});
}
return productRepository.findAll();
}
But my problem is only the last customer will be saved to the Db who named "BM". same as the response like this.
[
{
"productName": "soap",
"price": 100,
"customer": {
"custId": 5,
"name": "BM",
"email": "BM#gmail.com",
"gender": "male"
},
"pqty": 0,
"pid": 6
}
]
My target is to save each and every customer to the customer table and mapped with Person.
What I got wrong here?
Thanks.
First off, fix the relationship as follow
#Data
#Entity
public class Product {
#Id
#GeneratedValue(strategy= GenerationType.AUTO)
#Column(name = "product_id",updatable = false, nullable = false)
private Long pId;
private String productName;
private int pQty;
private int price;
#OneToMany
private List<Customer> customerList;
}
Product entity will change as below
#Data
#Entity
public class Customer {
#Id
#GeneratedValue(strategy= GenerationType.AUTO)
#Column(name = "customer_id",updatable = false, nullable = false)
private Long custId;
private String name;
private String email;
private String gender;
#ManyToOne
private Product product;
}
then change your saveProduct as below
#Override
public Iterable<Product> saveProduct(Product product) {
Product product1 = new com.adl.dte.core.model.Product();
product1.setProductName(product.getProductName());
product1.setPQty(product.getPQty());
product1.setPrice(product.getPrice());
product1.setCustomerList(product.getCustomerList());
product.getCustomerList().forEach(cust -> cust.setProduct(product1));
productRepository.save(product);
return productRepository.findAll();
}
You have some problems:
First, define a Customer list (List<Customer> customers) in your Product entity bean. Then add customers to it with the addCustomer method.
Also use for each customer a own new Customer object and don't use one Customer and update the values.
Saving each Customer is not necessary. Saving the Product object/entity should be enough.
The values are saved to the database when the transaction is committed and closed. Spring handles this for you.
I have used spring boot with hibernate. And swagger to generate the dtos and the api interface.
There are two entities. The project entity is the parent and application entity is the child. Have create a onetomany relationship. But when i try to persist. I see not applications getting added for a project.
Project Entity:
#Entity
#Table(name="ProjectEntity")
public class ProjectEntity {
#Id
#Column(name = "ProjectGuid", length = 36, nullable = false, unique = true)
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
#Column(name = "Name")
private String name;
#OneToMany(mappedBy="projectApp", cascade = CascadeType.ALL)
private List<ApplicationEntity> apps=new ArrayList<>();
public ProjectEntity() {
}
public ProjectEntity(Long id, String name) {
this.id = id;
this.name = name;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<ApplicationEntity> getApps() {
return apps;
}
public void setApps(List<ApplicationEntity> apps) {
this.apps = apps;
}
}
Application Entity:
#Entity
#Table(name="ApplicationEntity")
public class ApplicationEntity {
#Id
#Column(name = "Name", length = 36, nullable = false, unique = true)
private String name;
private String repositoryUrl;
#ManyToOne
#Cascade(org.hibernate.annotations.CascadeType.SAVE_UPDATE)
#JoinColumn(name = "ProjectGuid")
private ProjectEntity projectApp;
public ApplicationEntity() {
}
public ApplicationEntity(String name, String repositoryUrl) {
this.name = name;
this.repositoryUrl = repositoryUrl;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRepositoryUrl() {
return repositoryUrl;
}
public void setRepositoryUrl(String repositoryUrl) {
this.repositoryUrl = repositoryUrl;
}
public ProjectEntity getProjectApp() {
return projectApp;
}
public void setProjectApp(ProjectEntity projectApp) {
this.projectApp = projectApp;
}
}
Controller operation:
ProjectEntity project = projectService.getProject(projectName);
List<ApplicationEntity> appList = new ArrayList<>();
ApplicationEntity appEntity = new ApplicationEntity(app.getName(), app.getRepositoryUrl());
applicationRepository.save(appEntity);
appList.add(appEntity);
project.setApps(appList);
projectRepository.save(project);
You need to set the id of the ProjectEntity on the owning side (which is the ApplicationEntity)
appEntity.setProjectApp(project);
Otherwise hibernate (and your database) does not know to which parent a ApplicationEntity belongs.
Here is an example many to one relation with spring data jpa :
#Data
#MappedSuperclass
public class BaseEntity {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
}
#Data
#Entity
public class Question extends BaseEntity{
private String questionText;
private int anketId;
private int subjectId;
#OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, orphanRemoval = true, mappedBy = "question")
List<Answer> answers;
}
#Data
#Entity
public class Answer extends BaseEntity{
private String answerText;
private String code;
private int score;
private int priority;
private boolean isValidAnswer;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "question_id", referencedColumnName = "id", insertable = false, updatable = false)
private Question question;
}
#DataJpaTest
public class QuestionRepositoryTest {
#Autowired
TestEntityManager entityManager;
#Autowired
QuestionRepository sut;
#Test
public void it_should_create_question_wiht_answers() {
Question question = new Question();
question.setSubjectId(1);
question.setAnketId(1);
question.setQuestionText("test question");
Answer answer = new Answer();
answer.setAnswerText("answer");
answer.setCode("1a");
answer.setPriority(0);
answer.setValidAnswer(true);
question.setAnswers(Arrays.asList(answer));
entityManager.persistAndFlush(question);
List<Question> questionList = sut.findAll();
assertThat(questionList).containsExactly(question);
assertThat(questionList.get(0).getAnswers().size()).isGreaterThan(0);
}
}
I would like to have a One-to-many relationship between 2 Entities, Consumer and Policy. One consumer should have several policies.
This is an example of a Consumer JSON object I would like to have:
{
id : 1,
name : "Peter",
endpoint: "123.456.778",
policies: [
{
id : 1,
name: "policy 01"
},
{
id : 2,
name: "policy 02"
}
]
}
This is what I have so far:
Policy Entity
#Entity
public class Policy {
#Id
#GeneratedValue
#Column(name = "id")
private Integer id;
#Column(name = "name")
private String name;
//getters and setters
}
Consumer Entity
#Entity
public class Consumer {
#Id
#GeneratedValue
#Column(name = "consumer_id")
private Integer id;
#Column(name = "name")
private String name;
#Column(name = "endpoint")
private String endpoint;
#OneToMany
#JoinColumn(??)
private List<Policy> policies;
//getters and setters
}
It's not that hard I think, but im trying now for several hours and can't get it done. I'm new to Spring, so if someone is able to help me, I would be very thankfull!
#Entity
public class Consumer {
#OneToMany(mappedBy = "consumer")
private List<Policy> policies;
}
#Entity
public class Policy {
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn("consumer_id")
private Consumer consumer;
}
fetch = FetchType.LAZY is not necessary, but desirable.
I have provided some basics here
what is #JoinColumn and how it is used in Hibernate
If you want to a Policy don't have a Consumer:
You can use a join table
#Entity
public class Consumer {
#OneToMany
private List<Policy> policies;
}
#Entity
public class Policy {
}
A unidirectional relation (a Policy table will have consumer_id column, but a Policy class doesn't have a Consumer)
#Entity
public class Consumer {
#OneToMany
#JoinColumn("consumer_id")
private List<Policy> policies;
}
#Entity
public class Policy {
}
Also, keep in mind, that if you want to use a Policy as tabular data (from a dictionary) you will need #ManyToMany.
Try this code :)
Your Consumer Class
#Entity
public class Consumer {
#Id
#GeneratedValue
#Column(name = "consumer_id")
private Integer id;
#Column(name = "name")
private String name;
#Column(name = "endpoint")
private String endpoint;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "idPolicy")
private List<Policy> policies;
public Consumer() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEndpoint() {
return endpoint;
}
public void setEndpoint(String endpoint) {
this.endpoint = endpoint;
}
public List<Policy> getPolicies() {
return policies;
}
public void setPolicies(List<Policy> policies) {
this.policies = policies;
}
}
Be aware that in the mapped by, you should use the name of the column that references Policy in your database, so if it's no policyId, use the name you gave to it
Your Policy Class
#Entity
public class Policy {
#Id
#GeneratedValue
#Column(name = "id")
private Integer id;
#Column(name = "name")
private String name;
#ManyToOne(optional = false)
private Consumer consumer;
public Policy() {
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
I'm trying to generate Hibernate mapping to my H2 database.
I have 2 tables for test, called users and users_groups.
They look like:
users table:
user_id integer PK
login varchar
password varchar
user_group_id integer FK
users_groups
user_group_id integer PK
name varchar
And the problem is that hibernate generate entities like that:
#Entity
public class Users {
private int userId;
private int userGroupId;
#Id
#Column(name = "USER_ID", nullable = false)
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
#Basic
#Column(name = "USER_GROUP_ID", nullable = false)
public int getUserGroupId() {
return userGroupId;
}
public void setUserGroupId(int userGroupId) {
this.userGroupId = userGroupId;
}
#Entity
#Table(name = "USERS_GROUPS", schema = "PUBLIC", catalog = "DATABASE")
public class UsersGroups {
private int userGroupId;
#Id
#Column(name = "USER_GROUP_ID", nullable = false)
public int getUserGroupId() {
return userGroupId;
}
public void setUserGroupId(int userGroupId) {
this.userGroupId = userGroupId;
}
So no relation annotations are generated, like #OneToMany or #ManyToMany etc. What am I doing wrong? Thanks for your help.
p.s. I want it to generate mapping like
Users class with field of UserGroup type
If the classes were auto generated like this check your relation in the database between the two tables and make sure you choose the right schema your mapping is completely wrong the for example :-
1-the auto generated classes your mapping are missing some columns, class User doesn't contain password and login columns and class UsersGroups doesn't contain name column.
2- class User doesn't have #table annotation
They should look something like this :-
Class UserGroups
#Entity
#Table(name = "USERS_GROUPS", schema = "PUBLIC", catalog = "DATABASE")
public class UsersGroups implements java.io.Serializable {
private int userGroupId;
private String name;
private Set<Users> users = new HashSet<Users>(0);
public UsersGroups() {
}
#Id
#GeneratedValue(strategy = IDENTITY) //this to make the id auto increment
#Column(name = "user_group_id", nullable = false)
public int getUserGroupId() {
return userGroupId;
}
public void setUserGroupId(int userGroupId) {
this.userGroupId = userGroupId;
}
// if name column is not unique / nullable remove values from annotation
#Column(name = "name", unique = true, nullable = false, length = 10)
public String getName() {
return this.name;
}
public void setName(String name) {
this.name= name;
}
#OneToMany(fetch = FetchType.EAGER, mappedBy = "users_groups")
public Set<Users> getUsers() {
return this.users;
}
public void setUsers(Set<Users> users) {
this.users= users;
}
}
Class Users
#Entity
#Table(name = "users", schema ="PUBLIC" , catalog ="DATABASE")
public class Users implements java.io.Serializable {
private Integer userId;
private UsersGroups usersGroups;
private String password;
private String login;
public Users() {
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "user_id", unique = true, nullable = false)
public Integer getUserId() {
return this.userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "user_group_id", nullable = false)
public UsersGroups getUsersGroups() {
return this.usersGroups;
}
public void setUsersGroups(UsersGroups usersGroups) {
this.usersGroups = usersGroups;
}
#Column(name = "password",length = 10)
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
#Column(name = "login",length = 10)
public String getLogin() {
return this.login;
}
public void setLogin(String login) {
this.login = login;
}
}
Check this full example for one to many mapping
I followed this tutorial to implement in my domain model a many-to-many relationship with an extra column. It works great but I'm unable to create a criteria to query a field within the left side of my relation.
Taking this code
#Entity
#Table( name = "projects")
public class Project implements Cloneable, Serializable{
private Long id;
private String name;
private Set<ProjectOrganization> projectOrganizations = new HashSet<ProjectOrganization>(0);
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(nullable = false)
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
#Column(name = "name", length = 255, nullable = false)
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
#OneToMany(fetch = FetchType.EAGER, mappedBy = "pk.project")
#Cascade(value = { CascadeType.ALL })
public Set<ProjectOrganization> getProjectOrganizations() {
return this.projectOrganizations;
}
public void setProjectOrganizations(Set<ProjectOrganization> organizationProjects) {
this.projectOrganizations = organizationProjects;
}
}
#Entity
#Table(name = "projects_has_organizations")
#AssociationOverrides({ #AssociationOverride(name = "pk.project", joinColumns = #JoinColumn(name = "projects_id")),
#AssociationOverride(name = "pk.organization", joinColumns = #JoinColumn(name = "organizations_id"))
})
public class ProjectOrganization implements Cloneable, Serializable {
private ProjectOrganizationPK pk = new ProjectOrganizationPK();
private OrganizationRolesEnum role;
public ProjectOrganization() {
}
#Transient
public Organization getOrganization() {
return getPk().getOrganization();
}
public void setOrganization(Organization organization) {
getPk().setOrganization(organization);
}
#EmbeddedId
public ProjectOrganizationPK getPk() {
return pk;
}
public void setPk(ProjectOrganizationPK pk) {
this.pk = pk;
}
#Transient
public Project getProject() {
return getPk().getProject();
}
public void setProject(Project project) {
getPk().setProject(project);
}
#Enumerated(EnumType.STRING)
#Column(nullable = false, length = 50)
public OrganizationRolesEnum getRole() {
return role;
}
public void setRole(OrganizationRolesEnum role) {
this.role = role;
}
}
#Embeddable
public class ProjectOrganizationPK implements Cloneable, Serializable {
/** Generated serial version UID */
private static final long serialVersionUID = -4534322563105003365L;
private Organization organization;
private Project project;
#ManyToOne
public Organization getOrganization() {
return organization;
}
public void setOrganization(Organization organization) {
this.organization = organization;
}
#ManyToOne
public Project getProject() {
return project;
}
public void setProject(Project project) {
this.project = project;
}
}
#Entity
#Table(name = "organizations")
public class Organization implements Cloneable, Serializable {
private Long id;
private String name;
private Set<ProjectOrganization> projectOrganizations = new HashSet<ProjectOrganization>(0);
public Organization() {
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(nullable = false)
#Override
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
#Column(name = "name", nullable = false, length = 255)
#NotNull(message = "A name is required!")
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
#OneToMany(fetch = FetchType.EAGER, mappedBy = "pk.organization")
public Set<ProjectOrganization> getProjectOrganization() {
return this.projectOrganizations;
}
public void setProjectOrganization(Set<ProjectOrganization> projectOrganizations) {
this.projectOrganizations = projectOrganizations;
}
}
I want is to create a criteria to select a Project which has an organization with a requested name.
final Criteria crit = getSession().createCriteria(Project.class);
crit.createCriteria("projectOrganizations", "projectOrganization").
createAlias("pk.organization", "organization").
add( Restrictions.like("organization.name", "TEST"));
But when i run this code i have this error
2012-10-19 10:38:43,095 ERROR [org.hibernate.util.JDBCExceptionReporter] Unknown column 'organizati2_.name' in 'where clause'
and the sql query generated by hibernate is incomplete, doesn't join projects_has_organizations.organization with organization.id.. So it can't find column organization.name
SELECT
....
FROM
projects this_
INNER JOIN projects_has_organizations projectorg1_ ON this_.id = projectorg1_.projects_id
WHERE
projectorg1_.role =?
AND organizati2_. NAME LIKE ?
ORDER BY
this_.publish_date DESC
What's wrong with this code? How can i build query using criteria ?
I suspect that the problem is due to lazy fetching, try explicitly telling hibernate to eagerly fetch the property you need. This is done with the method
.setFetchMode("propertyName", FetchMode.EAGER)
So, in otherwords, try eagerly fetch the organisation property :)