Many to many relationships doesn't shown in JSON. Spring + JPA - json

The relationships works fine, the tables are created and the data is inserted correctly. But when page loads in browser, many to many relationships doesn't shown.
But professions are not null:
Here is my entities:
#Entity
#Table(name = "users")
public class User {
#Id
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column(name = "login", nullable = true, length = 50)
private String login;
#Column(name = "pass", nullable = true, length = 50)
private String password;
#Column(name = "name", nullable = false, length = 50)
private String name;
....
public User() {
}
#ManyToMany(fetch = FetchType.EAGER)
#JoinTable(name="worker_profession", joinColumns =#JoinColumn(name="id_user", referencedColumnName="id"),
inverseJoinColumns = #JoinColumn(name="id_profession", referencedColumnName="id")
)
private Set<Profession> profession;
public Set<Profession> getProfession() {
return profession;
}
public void setProfession(Set<Profession> profession) {
this.profession = profession;
}
...
}
And:
#Entity
#Table(name = "profession")
public class Profession {
#Id
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#Column(name = "profession_name", nullable = false, length = 50)
private String professionName;
public Profession() {
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getProfessionName() {
return professionName;
}
public void setProfessionName(String professionName) {
this.professionName = professionName;
}
#ManyToMany(fetch = FetchType.EAGER, mappedBy = "profession")
private Set<User> users;
public Set<User> getUsers() {
return users;
}
public void setUsers(Set<User> users) {
this.users = users;
}
}
in UserController.class I have:
#RestController
#RequestMapping("/user")
public class UserController {
#Autowired
private UserRepository userRepository;
#RequestMapping(value = "", method = RequestMethod.GET)
#ResponseBody
public List<User> getAllUsers() {
return userRepository.findAll();
}
...
}
So, where is my mistake? Thanks.

Related

How can i mapping entities in spring boot jpa?

I'm new in Spring Boot JPA
I have questions in JPA Entity mappings.
there is 4 tables in my MySql DB
SPACE, PROJECT, ISSUE, MEMBER
SPACE is Big Project which contains multiple PROJECT.
PROJECT contains multiple ISSUE.
and MEMBER can join only 1 SPACE and multiple PROJECT which MEMBER belongs to SPACE.
MEMBER can write multiple ISSUE
in this situation, my ERD model is correct?
my ERD
and please check my jpa mappings.
If there's anything wrong, please point it out.
SPACE
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "space_no")
private Long spaceNo;
#NotEmpty
#Column(name = "space_name", unique=true, length = 100)
private String spaceName;
/** 1:N relation */
#OneToMany(mappedBy = "smsSpace")
private List<PmsProject> pmsProjects = new ArrayList<>();
PROJECT
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "project_no")
private Long projectNo;
#Column(name ="space_no")
private Long spaceNo;
#Column(name = "project_name", length = 100)
private String projectName;
/** 1:N relation */
#OneToMany(mappedBy = "pmsProject")
private List<ImsIssue> imsIssues = new ArrayList<>();
#OneToMany(mappedBy = "pmsProject")
private List<PmsProjectMember> projectMembers = new ArrayList<>();
/** N:1 relation */
#ManyToOne
#JoinColumn(name = "space_no", referencedColumnName = "space_no", insertable = false, updatable = false)
private SmsSpace smsSpace;
MEMBER
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "member_no")
private Long memberNo;
#Column(name = "mail_address", unique=true, length = 100)
private String mailAddress;
#Column(name = "name", length = 100)
private String name;
#Column(name = "keyword", length = 1000)
private String keyword;
#Column(name = "image", length = 1000)
private String image;
#Column(name = "password", length = 1000)
private String password;
#Column(name = "user_id", length = 50)
private String userId;
#Enumerated(EnumType.STRING)
private MemberRole role;
public void encodingPassword(String password) {
this.password = password;
}
/** 1:N realtion */
#OneToMany(mappedBy = "mmsMember")
private List<PmsProjectMember> projectMembers = new ArrayList<>();
ISSUE
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "issue_no")
private Long issueNo;
#Column(name ="project_no")
private Long projectNo;
#Column(name = "issue_name", length = 1000)
private String issueName;
#Column(name = "priority")
private Long priority;
#Column(name = "status", length = 20)
private String status;
#Column(name = "summary", length = 100)
private String summary;
#Column(name = "is_overdue")
private Long isOverdue;
#Column(name = "issue_type_cd")
private String issueTypeCd;
/** N:1 relation */
#ManyToOne
#JoinColumn(name = "project_no", referencedColumnName = "project_no", insertable = false, updatable = false)
private PmsProject pmsProject;
PROJECTMEMBER
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "group_no")
private Long groupNo;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "member_no")
private MmsMember mmsMember;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "project_no")
private PmsProject pmsProject;
I've been thinking about it for days, but I can't solve it because I lack knowledge. Please help me.
Assuming I got your situation right, you have A member that can have one Space and multiple project, space has multiple projects, every project can have more than one issue, every member can write more then one issue for each project.
Due to the suggestion the ERD you posted it's not corrected.
Here is the correct ERD
(I just wrote the Foreign Keys and Primary Keys, the rest its up to you)
And here you have all the entites:
Member
#Entity
#Table(name = "MEMBERS")
public class Member {
//members is the property name in Project entity.
#ManyToMany(mappedBy = "members")
Set<Project> projects;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY, generator = "native")
#Column(name = "MEMBER_ID")
private Long id;
#ManyToOne
#JoinColumn(name = "SPACE_ID")
private Space space;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Space getSpace() {
return space;
}
public void setSpace(Space space) {
this.space = space;
}
public Set<Project> getProjects() {
return projects;
}
public void setProjects(Set<Project> projects) {
this.projects = projects;
}
}
Space
#Entity
#Table(name = "SPACES")
public class Space {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY, generator = "native")
#Column(name = "SPACE_ID")
private Long id;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
Issue
#Entity
#Table(name = "ISSUES")
public class Issue {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY, generator = "native")
#Column(name = "ISSUE_ID")
private Long id;
#ManyToOne
#JoinColumn(name = "MEMBER_ID")
private Member member;
#ManyToOne
#JoinColumn(name = "PROJECt_ID")
private Project project;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Member getMember() {
return member;
}
public void setMember(Member member) {
this.member = member;
}
public Project getProject() {
return project;
}
public void setProject(Project project) {
this.project = project;
}
}
Project
#Entity
#Table(name = "PROJECTS")
public class Project {
#ManyToMany
#JoinTable(
name = "PROJECTS_MEMBERS",
joinColumns = #JoinColumn(name = "PROJECT_ID"),
inverseJoinColumns = #JoinColumn(name = "MEMBER_ID"))//Is referring to the id of the other Entity, in this case, members
Set<Member> members;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY, generator = "native")
#Column(name = "PROJECT_ID")
private Long id;
#ManyToOne
#JoinColumn(name = "SPACE_ID")
private Space space;
public Set<Member> getMembers() {
return members;
}
public void setMembers(Set<Member> members) {
this.members = members;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Space getSpace() {
return space;
}
public void setSpace(Space space) {
this.space = space;
}
}
You don't have to put necessarily both #ManyToOne and #OneToMany annotation, the back-reference could be useful in some use case, you have to see if you need it or not. Remember the back reference could cause problems with deserialization, creating a stack overflow by circular reference. You can avoid this, using transient keyword or various annotation (depending on the library you are using, Jackson, Gson, ecc..).
Be careful to don't use FetchType.EAGER randomly here's the why => Difference between FetchType LAZY and EAGER in Java Persistence API?

How to add multiple entity in a single entity in jpa spring boot application

I am trying to add multiple entities in a single entity, I don't know this way possible or not please refer to my below code and help
the below code are the entity tables
#Entity
#Table(name = "agent_employee")
public class AgentEmployee extends Agent implements Serializable{
private static final long serialVersionUID = 1L;
#OneToMany // unidirectional
#JoinColumn(name = "employment_id", referencedColumnName = "id")
List<Employment> employmnet = new ArrayList<Employment>();
#OneToMany(
mappedBy = "agent",
cascade = CascadeType.ALL,
orphanRemoval = true
)
private Set<Officess> officess = new HashSet<>();
public List<Employment> getEmploymnet() {
return employmnet;
}
public void setEmploymnet(List<Employment> employmnet) {
this.employmnet = employmnet;
}
public Set<Officess> getOfficess() {
return officess;
}
public void setOfficess(Set<Officess> officess) {
this.officess = officess;
}
}
and Employment class is
#Data
#Entity
public class Employment {
#Id
#Column(nullable = false, unique = true)
private Long id;
private String empName;
private String location;
#Override
public String toString() {
return "Employment [id=" + id + ", empName=" + empName + ", location=" + location + "]";
}
}
and Offices class is
#Data
#Entity
#Table(name = "officess")
public class Officess implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String officeName;
#ManyToOne
#JoinColumn(name = "agent_emp")
private AgentEmployee agent;
}
And I have used spring boot repositories to all the respective entities
#GetMapping(path = "/add")
public #ResponseBody String addAgentEmployee() {
try {
AgentEmployee agemp = new AgentEmployee();
agemp.setFirstName("harish");
agemp.setLastName("kadsuru");
agemp.setEmail("hari**********is.net");
Employment emp1 = new Employment();
Employment emp2 = new Employment();
Employment emp3 = new Employment();
emp1.setId(501l);
emp2.setId(502l);
emp3.setId(503l);
emp1.setEmpName("junior engineer");
emp2.setEmpName("senior engineer");
emp3.setEmpName("team leader");
emp1.setLocation("bengaluru");
emp2.setLocation("mumbai");
emp3.setLocation("UAE");
List<Employment> emps = Arrays.asList(emp1, emp2, emp3);
employmentRepository.saveAll(emps);
agemp.setEmploymnet(emps);
agentEmployeeRepository.save(agemp);
return "saved";
} catch (Exception e) {
return "unable to save data due to exception";
}
}
#GetMapping("addOffice")
public #ResponseBody String addAgentEmployeeOffice() {
AgentEmployee emp;
Optional<AgentEmployee> agemp = agentEmployeeRepository.findById(27l);
if (agemp.isPresent()) {
emp = agemp.get();
}
else {
emp =new AgentEmployee();
emp.setFirstName("garish");
emp.setLastName("tumkur");
emp.setEmail("garish.kr#cyclotis.net");
}
log.info("###### {}",agemp);
Officess off1 = new Officess();
Officess off2 = new Officess();
Officess off3 = new Officess();
off1.setOfficeName("Google");
off2.setOfficeName("facebook");
off3.setOfficeName("Instagram");
Set<Officess> offices = emp.getOfficess();
offices.add(off1);
offices.add(off2);
offices.add(off3);
agentEmployeeRepository.save(emp);
log.info("######## {}", offices);
return "saved";
}
I don't think any problem with code, but I think I have a problem while saving the data. Kindly any body refer the correct way to analyse this problem.
Looks like your mapping is not correct. Also verify you have a EMPID column.
You don't need to use the #JoinTable annotation in your case.
As you are saving data you should use #PostMapping
StatusReport - removed private BigInteger EMPID; as it is used in joining
#Entity
#Table(name="statusreport")
public class StatusReport {
private BigInteger COMPLIANCEID;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private BigInteger STATUSRPTID;
private String COMMENTS;
private Date CREATEDDATE;
private BigInteger DEPARTMENT_ID;
#OneToOne
#JoinColumn(name = "EMPID")
private Employees employee;
//others methods
}
Employee - removed private BigInteger DEPARTMENT_ID; as it is used in joining
#Entity
public class Employees {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private BigInteger EMPID;
private String FIRSTNAME;
private String LASTNAME;
private Date DOB;
private String EMAIL;
#OneToOne
#JoinColumn(name = "DEPARTMENT_ID")
private Department department;
//others methods
}

Use of #OneToMany or #ManyToMany targeting an unmapped class, unresolved Hibernate error

I am trying to implement Spring Oauth2. All has been good until I keep on getting this error and could not resolve it.
import lombok.Data;
import java.util.List;
import javax.persistence.*;
#Entity #Table( name = "role") #Data
public class Role {
#Id #GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
#Column(name = "name")
private String name;
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 List<Permission> getPermissions() {
return permissions;
}
public void setPermissions(List<Permission> permissions) {
this.permissions = permissions;
}
#ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
#JoinTable(name = "permission_role", joinColumns = { #JoinColumn( name = "role_id", referencedColumnName = "id")},
inverseJoinColumns = { #JoinColumn(name = "permission_id", referencedColumnName = "id") })
private List<Permission> permissions;
}
The User Model
import lombok.Data;
import javax.management.relation.Role;
import javax.persistence.*;
import java.util.List;
#Entity #Table(name = "user") #Data
public class User {
public User(){}
public User( User user ){
this.username = user.getUsername();
this.password = user.getPassword();
this.email = user.getEmail();
this.enabled = user.isEnabled();
this.accountNonExpired = user.isAccountNonExpired();
this.accountNonLocked = user.isAccountNonLocked();
this.credentialsNonExpired = user.isCredentialsNonExpired();
this.role = user.getRole();
}
#Id
#GeneratedValue( strategy = GenerationType.AUTO)
private Integer id;
#Column(name = "username")
private String username;
#Column(name = "password")
private String password;
#Column(name = "email")
private String email;
#Column(name = "enabled")
private boolean enabled;
#Column(name = "accountNonExpired")
private boolean accountNonExpired;
#Column(name = "accountNonLocked")
private boolean accountNonLocked;
#Column(name = "credentialsNonExpired")
private boolean credentialsNonExpired;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public boolean isAccountNonExpired() {
return accountNonExpired;
}
public void setAccountNonExpired(boolean accountNonExpired) {
this.accountNonExpired = accountNonExpired;
}
public boolean isAccountNonLocked() {
return accountNonLocked;
}
public void setAccountNonLocked(boolean accountNonLocked) {
this.accountNonLocked = accountNonLocked;
}
public boolean isCredentialsNonExpired() {
return credentialsNonExpired;
}
public void setCredentialsNonExpired(boolean credentialsNonExpired) {
this.credentialsNonExpired = credentialsNonExpired;
}
public List<Role> getRole() {
return role;
}
public void setRole(List<Role> role) {
this.role = role;
}
#ManyToMany( fetch = FetchType.EAGER, cascade = CascadeType.ALL)
#JoinTable( name = "role_user", joinColumns = { #JoinColumn( name = "user_id", referencedColumnName = "id")},
inverseJoinColumns = { #JoinColumn( name = "role_id", referencedColumnName = "id") })
private List<Role> role;
}
I am trying to implement ManyToMany relationship between the 2 Models
I kept on getting this error
Caused by: org.hibernate.AnnotationException: Use of #OneToMany or #ManyToMany targeting an unmapped class: io.christdoes.authentication.model.User.role[javax.management.relation.Role]
at org.hibernate.cfg.annotations.CollectionBinder.bindManyToManySecondPass(CollectionBinder.java:1274) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
at org.hibernate.cfg.annotations.CollectionBinder.bindStarToManySecondPass(CollectionBinder.java:811) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
at org.hibernate.cfg.annotations.CollectionBinder$1.secondPass(CollectionBinder.java:736) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
at org.hibernate.cfg.CollectionSecondPass.doSecondPass(CollectionSecondPass.java:54) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processSecondPasses(InFlightMetadataCollectorImpl.java:1696) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processSecondPasses(InFlightMetadataCollectorImpl.java:1664) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:287) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:904) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:935) ~[hibernate-core-5.3.10.Final.jar:5.3.10.Final]
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:57) ~[spring-orm-5.1.9.RELEASE.jar:5.1.9.RELEASE]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365) ~[spring-orm-5.1.9.RELEASE.jar:5.1.9.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:390) ~[spring-orm-5.1.9.RELEASE.jar:5.1.9.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:377) ~[spring-orm-5.1.9.RELEASE.jar:5.1.9.RELEASE]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341) ~[spring-orm-5.1.9.RELEASE.jar:5.1.9.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1837) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1774) ~[spring-beans-5.1.9.RELEASE.jar:5.1.9.RELEASE]
... 16 common frames omitted

ManytoMany creating 2 tables

I have two classes cards and tags. I want a many to many relationship between them and store the cardId and tagId in one table. When i create the database from the code it creates 2 different table with one to many relationship. tag_cards and card_tags. What am i doing wrong here? I want one single table with many to many relationship.
import javax.faces.bean.ManagedBean;
import javax.persistence.*;
import java.util.Set;
#ManagedBean(name = "addToCardBean")
#javax.persistence.Table(name = "cards")
#Entity
public class Card implements java.io.Serializable{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
public int id;
#Column(name="username",nullable = false)
private String username;
#Column(name="text",nullable = false)
private String text;
#Column(name="author")
private String author;
#Column(name="title")
private String title;
#Column (name="source")
private String source;
#Column(name="facebookID" ,columnDefinition="BigInt(20) default '0'")
private long facebookID;
#ElementCollection(targetClass = Tag.class)
private Set<Tag> tags;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public long getFacebookID() {
return facebookID;
}
public void setFacebookID(long facebookID) {
this.facebookID = facebookID;
}
#ManyToMany(mappedBy = "cards")
public Set<Tag> getTags() {
return tags;
}
public void setTags(Set<Tag> tags) {
this.tags = tags;
}
}
import javax.faces.bean.ManagedBean;
import javax.persistence.*;
import java.util.Set;
#Entity
#Table(name="tag")
#ManagedBean(name="tagBean")
public class Tag implements java.io.Serializable{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
public Integer id;
#Column(name = "tagName", nullable = false)
private String tagName;
#ElementCollection(targetClass = Card.class)
private Set<Card> cards;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getTagName() {
return tagName;
}
public void setTagName(String tagName) {
this.tagName = tagName;
}
#ManyToMany(cascade = CascadeType.ALL)
#JoinTable(
name = "cards_tags",
joinColumns = #JoinColumn(name = "id"),
inverseJoinColumns = #JoinColumn(name = "id")
)
public Set<Card> getCards() {
return cards;
}
public void setCards(Set<Card> cards) {
this.cards = cards;
}
}
You are facing this issue because you have used the annotations both at the field and method(getter) level i.e you have mixed both.
#Column(name = "tagName", nullable = false)
private String tagName;
and
#ManyToMany(cascade = CascadeType.ALL)
#JoinTable(
name = "cards_tags",
joinColumns = #JoinColumn(name = "id"),
inverseJoinColumns = #JoinColumn(name = "id")
)
public Set<Card> getCards() {
return cards;
}
You have to either use them only on field or only on method(getter). Do not mixup the two.
Why you are ending up with two tables is because the field annotations are getting considered and the many to many mapping is on the getter method which is not being considered.
One way is just use at field level. If annotating at field, change to the following(you need to modify the other entity class as well):
#ManyToMany(cascade = CascadeType.ALL)
#JoinTable(
name = "cards_tags",
joinColumns = #JoinColumn(name = "id"),
inverseJoinColumns = #JoinColumn(name = "id")
)
#ElementCollection(targetClass = Card.class)
private Set<Card> cards;
You need to make changes in both classes. Move the annotations from getter to field as described above. Or you have to make changes so that all annotations are on getter instead of field.
Additional links:
https://softwareengineering.stackexchange.com/questions/258541/where-to-put-jpa-annotations-field-or-getter
the difference between anotating a field and its getter method JPA

Hibernate Select query returns null foreign object

I have the following entities defined:
Restaurante:
#Entity
#Table(name = "restaurantes")
public class Restaurante implements Serializable {
private int id;
private Set<Menu> menus = new HashSet<>(0);
public Restaurante() {
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "restaurante_id", unique = true, nullable = false)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#JsonIgnore
#OneToMany(mappedBy = "restaurante")
public Set<Menu> getMenus() {
return menus;
}
public void setMenus(Set<Menu> menus) {
this.menus = menus;
}
}
And menu:
#Entity
#Table(name = "menus")
public class Menu implements Serializable {
private int id;
private Restaurante restaurante;
public Menu() {
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "menu_id", unique = true, nullable = false)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#JsonIgnore
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "restaurante_id", nullable = false)
public Restaurante getRestaurante() {
return restaurante;
}
public void setRestaurante(Restaurante Restaurante) {
this.restaurante = restaurante;
}
}
And when I perform the following query:
public Menu getMenuById(Integer id) throws HibernateException, IndexOutOfBoundsException {
session = HibernateSessionService.getSessionFactory().openSession();
criteria = session.createCriteria(Menu.class)
.add(Restrictions.eq("id", id));
return (Menu) criteria.list().get(0);
}
The property restaurante is null.
There is a restaurante loaded in the database with the Id I'm using, and there are several menus loaded with that foreign key as well.
Can someone give me advice or help me?
Thanks in advance!