Hibernate query on many to many mapping - java

I have been using many to many mapping here is my POJO classes.
Menu.java :
#Entity
#Table(name = "menu")
public class Menu {
#Id
#Column(name = "menuid")
#GeneratedValue
private int menuid;
#Column(name = "parentid")
private int parentid;
#Column(name = "menuname")
private String menuname;
#Column(name = "url")
private String url;
#Column(name = "status")
private String status;
#Column(name = "usertype")
private String usertype;
#Column(name = "isparent")
private boolean isParent;
private ArrayList<Menu> childMenu;
#ManyToMany(mappedBy="menus")
private List<User> users;
public Menu(Integer menuid){
this.menuid=menuid;
}
public Menu(){
}
User.java :
#Entity
#Table(name = "user")
public class User implements Serializable {
#Id
#Column(name = "userid")
#GeneratedValue
private Integer userId;
#Column(name = "OUTLET_ID")
private int outletId;
#Column(name = "NAME")
private String name;
#Column(name = "USERTYPE")
private String userType;
#Column(name = "LOGINID")
private String loginId;
#Column(name = "PASSWORD")
private String password;
#Column(name = "CREATEDDATE")
private String createdDate;
#Column(name = "CONTACTNUMBER")
private String contactNumber;
#Column(name = "EMAILID")
private String emailId;
#Column(name = "OUTLETTYPE")
private String outlettype;
#Transient
private String nsec;
#javax.persistence.Transient
ArrayList<Integer> menuid;
#javax.persistence.Transient
ArrayList<Long> clientid;
#javax.persistence.Transient
ArrayList<String> clientName;
#ManyToMany(fetch=FetchType.EAGER) #JsonIgnore
#JoinTable(name="user_menu",joinColumns={#JoinColumn(name="userid")},
inverseJoinColumns={#JoinColumn(name="menuid")})
public List<Menu> menus;
#ManyToMany(fetch=FetchType.EAGER) #JsonIgnore
#JoinTable(name="user_client",joinColumns={#JoinColumn(name="userid")},
inverseJoinColumns={#JoinColumn(name="outletid")})
public List<Client> clients;
public User() {
}
I have user,menu and third mapping table user_menu which is created automatically, I successfully get result when fire following query in mysql
select * from menu m inner join user_menu um on m.menuid = um.menuid where um.userid = 41;
I want to write this query in hibernate how to this stuff ???

Finally I find my answer, here is my hql query,
String sql = "select m.menuid as menuid,m.parentid as parentid,m.menuname as menuname,m.url as url,m.status as status,m.usertype as usertype,m.isParent as isParent,m.childMenu as childMenu from Menu m join m.users u where u.userId = "+userid +"";
q = session.createQuery(sql).setResultTransformer(Transformers.aliasToBean(Menu.class));

Related

SpringBoot microservice InvalidDefinitionException

I developed a microservice and when I go to get to postman ( http://localhost:8080/user/utenti/ ) I get this error InvalidDefinitionException No serializer found for class org.hibernate.proxy.pojo.bytebuddy.ByteBuddyInterceptor and no properties discovered create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) (through reference chain: java.util.ArrayList[0]->com.application.dto.UserDto["applicationRoleID"]->com.poste.anagrafica.entity.Role$HibernateProxy$N0iZZA2I["hibernateLazyInitializer"])
Can you help me please?
For clarity I enclose the schema of the database and the classes entity , dto and controller
The Entity classes
"""
#Entity
#Table(name = "USERS")
#Data
#NoArgsConstructor
#AllArgsConstructor
#Getter
#Setter
public class User implements Serializable {
#Id
#Column(name = "user_id", nullable = false)
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "created_date")
private LocalDateTime createdDate;
#Column(name = "deleted", nullable = false)
private Long number;
#Column(name = "modified_date")
private LocalDateTime modifiedDate;
#Column(name = "birth_place")
private String birthPlace;
#Column(name = "birthday")
private Date birthDay;
#Column(name = "canNominate")
private Long canNominate;
#Column(name = "email")
private String email;
#Column(name = "firstName")
private String firstName;
#Column(name= "fiscalCode")
private String fiscalCode;
#Column(name = "hiringDate")
private Date hiringDate;
#Column(name ="last_name")
private String lastName;
#Column(name = "matricola")
private String matricola;
#Column(name = "position")
private String position;
#Column(name = "registration_number")
private String registrationNumber;
#Column(name = "replaced")
private Long replaced;
#Column(name = "terminationDate")
private Date terminationDate;
#Column(name = "user_status")
private String userStatus;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "application_role_id")
private Role applicationRoleID;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "company_id")
private Company companyID;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "direction_id")
private Direction directions ;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "level_id")
private Levels levelID;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "referent_id")
private User referentID;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "role_id")
private Role roleID;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "task_id")
private EmployeeTask taskID;
}
"""
the UserDTO class
"""
#Data
public class UserDto {
private Long userId;
private LocalDateTime createdDate;
private Long number;
private LocalDateTime modifiedDate;
private String birthPlace;
private Date birthDay;
private Long canNominate;
private String email;
private String firstName;
private String fiscalCode;
private Date hiringDate;
private String lastName;
private String matricola;
private String position;
private String registrationNumber;
private Long replaced;
private Date terminationDate;
private String userStatus;
private Role applicationRoleID;
private Company companyID;
private Direction directions ;
private Levels levelID;
private User referentID;
private Role role;
private EmployeeTask taskID;
}
"""
the controller class
"""
#RestController
#RequestMapping("/user")
#Log
public class UserController {
private static final Logger logger = LoggerFactory.getLogger(UserController.class);
#Autowired
UserService userService;
#GetMapping(value = "/cerca/{registration_number}", produces = "application/json")
public ResponseEntity<List<UserDto>> listUserByRegistrationNumber(#PathVariable("registration_number") String registrationNumber)
throws ChangeSetPersister.NotFoundException
{
log.info("****** Ottengo l'user con numeroRegistrazione " + registrationNumber + " *******");
List<UserDto> user = userService.SelByRegistrationNumber(registrationNumber);
return new ResponseEntity<List<UserDto>>(user, HttpStatus.OK);
}
#GetMapping(value = "/utenti", produces = "application/json")
public ResponseEntity<List<UserDto>> listAllUsers ()throws ChangeSetPersister.NotFoundException{
List<UserDto> user = userService.SelTutti();
return new ResponseEntity<List<UserDto>>(user, HttpStatus.OK);
}
}
"""
the application.properties
"""
spring.datasource.url = jdbc:oracle:thin:#192.134.2.82:1521/orcl
spring.datasource.username =admin
spring.datasource.password =zzzx
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
# JPA settings
spring.jpa.database-platform=org.hibernate.dialect.Oracle12cDialect
spring.jpa.hibernate.use-new-id-generator-mappings=false
spring.jpa.hibernate.ddl-auto=update
spring.jpa.hibernate.naming.implicit- strategy=org.hibernate.boot.model.naming.ImplicitNamingStrategyLegacyJpaImpl
spring.jpa.hibernate.naming.physical-strategy=org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl
"""
You can try
spring.jackson.serialization.fail-on-empty-beans=false
in your application.properties.

get API in spring boot with one to many relation

I have two models that are having one to many relation (customers have many invoices)
so i create one - many relation on it, this is my customer class :
#Entity
#Table(name = "customer")
public class Customer {
#Id
#GeneratedValue(strategy= GenerationType.IDENTITY)
private int id;
#Column(name = "serial_number")
private long serialNumber;
#Column(name = "first_name")
private String firstName;
#Column(name = "last_name")
private String lastName;
#Column(name = "email")
private String email;
#Column(name = "mobile_number")
private String mobileNumber;
#Column(name = "is_deleted")
private boolean isDeleted;
#OneToMany
private Set <Invoice> invoices;
}
and this is invoices class :
#Entity
#Table(name = "invoice")
public class Invoice {
#Id
#GeneratedValue(strategy= GenerationType.IDENTITY)
private int id;
#Column(name = "serial_number")
private long serialNumber;
#Column(name = "status")
private String status;
#Column(name = "created_date")
private Timestamp createdDate;
#Column(name = "is_deleted")
private boolean isDeleted;
#ManyToOne
#JoinColumn(name = "customer_id")
private Customer customer;
}
and then i create GET API ( get customers ) but it's nor working and return this error :
nested exception is com.fasterxml.jackson.databind.JsonMappingException: could not extract ResultSet (through reference chain: java.util.ArrayList[0]->com.example.invoices.model.Customer["invoices"]), path=/customer/viewList}]
and this is my api :
public List<Customer> getAllCustomers() {
List<Customer> customers = cutomerRepository.findAll();
return customers;
}
and controller :
#GetMapping("/viewList")
public ResponseEntity<List<Customer>> getAllCustomers() {
List<Customer> customers = new ArrayList<>();
customers = customerService.getAllCustomers();
if (customers.isEmpty()) {
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
return new ResponseEntity<>(customers, HttpStatus.OK);
}
You have a Bidirectional relation and therefore an endless loop if json tries to deserialize the Object.
You can use #JsonIgnore to break the loop or use DTOs to return at the endpoint
#Entity
#Table(name = "invoice")
public class Invoice {
#Id
#GeneratedValue(strategy= GenerationType.IDENTITY)
private int id;
#Column(name = "serial_number")
private long serialNumber;
#Column(name = "status")
private String status;
#Column(name = "created_date")
private Timestamp createdDate;
#Column(name = "is_deleted")
private boolean isDeleted;
#ManyToOne
#JsonIgnore
#JoinColumn(name = "customer_id")
private Customer customer;
}
DTO would look something like this (I like to use records for this but since I don't know if you use Java 17 I still use class):
Customer:
#Data
public class CustomerDTO {
private final int id;
private final long serialNumber;
private final String firstName;
private final String lastName;
private final String email;
private final String mobileNumber;
private final boolean isDeleted;
private final Set <Invoice> invoices;
public static CustomerDTO fromModel(Customer customer) {
return new CustomerDTO(
customer.getId(),
customer.getSerialNumber(),
customer.getFirstName(),
customer.getLastName(),
customer.getEmail(),
customer.getMobileNumber(),
customer.isDeleted(),
customer.getInvoices()
.stream()
.map(InvoiceDTO::fromModel)
.collect(Collectors.toSet())
);
}
}
Invoice (here you don't show the customer again):
#Data
public class InvoiceDTO {
private final int id;
private final String status;
private final Timestamp createdDate;
private final boolean isDeleted;
public static InvoiceDTO fromModel(Invoice invoice) {
return new InvoiceDTO(
invoice.getId(),
invoice.getStatus(),
invoice.getCreatedDate(),
invoice.isDeleted()
);
}
}
Controller:
#GetMapping("/viewList")
public ResponseEntity<List<CustomerDTO>> getAllCustomers() {
List<CustomerDTO> customers = new ArrayList<>();
customers = customerService.getAllCustomers()
.stream()
.map(CustomerDTO::fromModel)
.toList() //Depending on Java Version .collect(Collectors.toList());
if (customers.isEmpty()) {
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
return new ResponseEntity<>(customers., HttpStatus.OK);
}
Do not open the entity class directly to the outside world
As DTO use for example:
public class InvoiceDTO {
private int id;
private long serialNumber;
private String status;
private Timestamp createdDate;
private boolean isDeleted;
private CustomerDTO customer;
}
See it applied in my GitHub repo FurnitureStoreApplication, example DTO classes in package dto:

Spring, Jpa : One To Many Error when the list contains values

I want to return a Profile Object in JSON containing a list of login details associated with a social network.
Everything works correctly when the "reseaux_sociaux" table is empty. For my status table I get my statuses in JSON format in my Profile object. However, when "reseaux_sociaux" contains values then I get the error below and my Profile object in JSON format is not returned...
(Logs)
https://cloudvyzor.com/logpad/?query&database=sandbox-7fb06b2c06f198a7c0e4ff7c74d659e0
Profil Class
#Entity
#Table(name = "Profil")
public class Profil {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long Id;
#ManyToOne(fetch = FetchType.LAZY, optional = false)
#JoinColumn(name = "IdComptes", nullable = false)
private Comptes IdComptes;
private String Avatar;
private String Banniere;
private String Pseudo;
private String MailPro;
private String Bio;
#ManyToMany(cascade = CascadeType.ALL,fetch = FetchType.EAGER)
#JoinTable(name = "Statut_Profil", joinColumns = #JoinColumn(referencedColumnName = "Id"),inverseJoinColumns = #JoinColumn(referencedColumnName ="Id"))
private List<Statut> Statut;
#OneToMany( mappedBy = "IdProfil")
#JsonManagedReference("id_profil")
private List<ReseauxSociaux> Reseaux;
public Profil(){}
public Profil(Long id, Comptes idComptes, String avatar, String banniere, String pseudo, String mailPro, String bio) {
Id = id;
IdComptes = idComptes;
Avatar = avatar;
Banniere = banniere;
Pseudo = pseudo;
MailPro = mailPro;
Bio = bio;
}
}
ReseauxSociaux Class
#Entity
#IdClass(ReseauxId.class)
public class ReseauxSociaux {
#Id
private int Id;
#Id
private Long IdProfil;
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "IdProfil", insertable = false, updatable = false)
#JsonBackReference("id_profil")
private Profil Profil;
#ManyToOne
#JoinColumn(name = "Id", insertable = false, updatable = false)
#JsonBackReference("id")
private Reseau Reseau;
private String Identifiant;
private ReseauxSociaux()
{}
public ReseauxSociaux(int id, Long idProfil, String identifiant) {
Id = id;
IdProfil = idProfil;
Identifiant = identifiant;
}
}
Reseau class
#Entity
public class Reseau {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int Id;
private String Nom;
private String Couleur;
//I tried it with and without and it made no difference
#OneToMany( mappedBy = "Id")
#JsonManagedReference("id")
private List<ReseauxSociaux> Reseaux;
public Reseau(){}
public Reseau(int id, String nom, String couleur) {
Id = id;
Nom = nom;
Couleur = couleur;
}
//Get Set
}
Profil Controller
#RestController
#RequestMapping("/profil")
public class ProfilController {
private final ProfilRepository profilRepository;
public ProfilController(ProfilRepository profilRepository) {
this.profilRepository = profilRepository;
}
#PostMapping("/getprofil/{idCompte}")
Profil GetProfil(#PathVariable("idCompte") Long idCompte)
{
Profil profil= profilRepository.findProfilById(idCompte);
return profil;
}
}
I finally succeeded... The cause of the problem remains unclear but I have two hypotheses: the first is the use of capital letters on variable names; the second is the use of a list with the onetomany with the same name in two entities.
Profil class
#Entity
#Table(name = "Profil")
public class Profil {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#ManyToOne(fetch = FetchType.LAZY, optional = false)
#JoinColumn(name = "idComptes", nullable = false)
#JsonBackReference("id_comptes")
private Comptes idComptes;
private String avatar;
private String banniere;
private String pseudo;
private String mailPro;
private String bio;
#ManyToMany(cascade = CascadeType.ALL,fetch = FetchType.EAGER)
#JoinTable(name = "statut_profil", joinColumns = #JoinColumn(referencedColumnName = "id"),inverseJoinColumns = #JoinColumn(referencedColumnName ="id"))
private List<Statut> statut;
#OneToMany( mappedBy = "idProfil")
#JsonManagedReference("id_profil")
private List<ReseauxSociaux> lstprofil;
public Profil(){}
public Profil(Long id, Comptes idComptes, String avatar, String banniere, String pseudo, String mailPro, String bio) {
this.id = id;
this.idComptes = idComptes;
this.avatar = avatar;
this.banniere = banniere;
this.pseudo = pseudo;
this.mailPro = mailPro;
this.bio = bio;
}
//get set
}
ReseauxSociaux class
#Entity
#IdClass(ReseauxId.class)
public class ReseauxSociaux {
#Id
private int id;
#ManyToOne
#JoinColumn(name = "id", insertable = false, updatable = false)
#JsonBackReference("id_reseau")
private Reseau reseau;
#Id
private Long idProfil;
#ManyToOne
#JoinColumn(name = "idProfil", insertable = false, updatable = false)
#JsonBackReference("id_profil")
private Profil profil;
private String identifiant;
private ReseauxSociaux()
{}
public ReseauxSociaux(int id, Reseau reseau, Long idProfil, String identifiant) {
this.id = id;
this.reseau = reseau;
this.idProfil = idProfil;
this.identifiant = identifiant;
}
}
Reseau class
#Entity
public class Reseau {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String nom;
private String couleur;
#OneToMany( mappedBy = "id")
#JsonManagedReference("id_reseau")
private List<ReseauxSociaux> lstreseau;
public Reseau(){}
public Reseau(int id, String nom, String couleur) {
this.id = id;
this.nom = nom;
this.couleur = couleur;
}
}

Update Spring Embedded Entity throws Stack Overflow Entity

I am currently trying to update a Record which contains an Embedded Entity. When trying this, i am getting the following Error:
Request processing failed; nested exception is java.lang.RuntimeException: java.lang.StackOverflowError
When i create the Entity, everything is working fine.
This is what i have right now:
My Main Entity:
#Entity(name = "Account")
#Table(name = "account")
#DynamicUpdate
#NoArgsConstructor
#AllArgsConstructor
#Getter
#Setter
public class Account extends Auditable<String> {
#Id
#Column(name = "Id")
private String id;
#Column(
name = "Description",
length = 512)
private String description;
#Column(
name = "AnnualRevenue",
length = 18)
private String annualRevenue;
#Embedded
#AttributeOverrides(value = {
#AttributeOverride(name = "city", column = #Column(name = "billingAddressCity")),
#AttributeOverride(name = "country", column = #Column(name = "billingAddressCountry")),
#AttributeOverride(name = "latitude", column = #Column(name = "billingAddressLatitude")),
#AttributeOverride(name = "longitude", column = #Column(name = "billingAddressLongitude")),
#AttributeOverride(name = "postalCode", column = #Column(name = "billingAddressPostalCode")),
#AttributeOverride(name = "state", column = #Column(name = "billingAddressState")),
#AttributeOverride(name = "street", column = #Column(name = "billingAddressStreet"))
})
private Address billingAddress;
#Column(name = "Industry")
private String industry;
#Column(name = "IsDeleted")
private boolean isDeleted;
#Column(
name = "Employees",
length = 8
)
private int employees;
#Column(name = "Name")
private String name;
#Column(name = "Phone")
private String phone;
#Column(name = "Type")
private String type;
#Column(name = "Website")
private String website;
#OneToMany(
orphanRemoval = true,
fetch = FetchType.LAZY,
cascade = {
CascadeType.ALL
}
)
#JsonIgnoreProperties("account")
private final List<Contact> contacts = new ArrayList<>();
}
Here, i am using an Embedded Entity for the Address which looks like this:
#Embeddable
#NoArgsConstructor
#AllArgsConstructor
#Getter
#Setter
public class Address {
private String city;
private String country;
private Double latitude;
private Double longitude;
private String postalCode;
private String state;
private String street;
}
Furthermore, the Account can have multiple Contacts which is is defined like this:
#Entity(name = "Contact")
#Table(name = "contact")
#NoArgsConstructor
#AllArgsConstructor
#Getter
#Setter
#JsonInclude
public class Contact extends Auditable<String> {
#Id
#Column(name = "Id")
private String id;
#Column(name = "Department")
private String department;
#Column(
name = "Email"
)
private String email;
#Column(name = "FirstName")
private String firstName;
#Column(name = "Name")
private String name;
#Column(name = "Salutation")
private String salutation;
#ManyToOne
#JoinColumn(
name = "accountId",
nullable = false,
referencedColumnName = "Id",
foreignKey = #ForeignKey(
name = "AccountContactFK"
)
)
#JsonIgnoreProperties("contacts")
private Account account;
}
For the Account, i am using the DTO Principle to map the Fields which looks like this:
DTO for Creation:
#Getter
#Setter
public class AccountCreationDTO {
private String description;
private String annualRevenue;
private Address billingAddress;
private String industry;
private boolean isDeleted;
private int employees;
private String name;
private String phone;
private String type;
private String website;
}
DTO for Update:
#Getter
#Setter
public class AccountUpdateDTO {
#Id
private String id;
private String description;
private String annualRevenue;
#Embedded
private Address billingAddress;
private String industry;
private boolean isDeleted;
private int employees;
private String name;
private String phone;
private String type;
private String website;
}
And here is my Controller:
#RestController
#RequestMapping("/api/v1")
#RequiredArgsConstructor
#Slf4j
public class AccountController {
private final AccountRepository accountRepository;
#RequestMapping(value = "/createAccount", method = RequestMethod.POST)
public Account createObject(#RequestBody #DTO(AccountCreationDTO.class) Account account) {
//account.setBillingAddress(account.getBillingAddress());
//this.addressRepository.save(account.getBillingAddress());
Account createdAccount = this.accountRepository.saveAndFlush(account);
log.info("Created Account: {}", createdAccount);
return createdAccount;
}
#PutMapping(value = "/updateAcc")
public ResponseEntity<Account> updateAccount(#DTO(AccountUpdateDTO.class) Account account) {
Account updatedAccount = this.accountRepository.saveAndFlush(account);
log.info("Updated Account: {}", updatedAccount);
return ResponseEntity.ok().body(updatedAccount);
}
}

Spring JPA Join two tables without third class

Is there a way to join two tables in Spring JPA without using association class.
I have two MySQL DB tables :
employees(id,.....,department_id)
departments(id,.....)
And I'm searching for a way to join these tables using only my employee and department classes.
Currently, I managed to join two tables but with the third association class.
My current implementation is:
Employee class:
#Entity(name = "Employee")
#Table(name = "employees")
#JsonInclude(Include.NON_NULL)
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#JsonIgnore
#Column(name = "employee_id")
private Long employeeId;
#Column(name = "first_name")
private String firstName;
#Column(name = "last_name")
private String lastName;
#Column(name = "phone_number")
private String phoneNumber;
#Column(name = "hire_date")
private Double hireDate;
#Column(name = "job_id")
private Long jobId;
#Column(name = "salary")
private Double salary;
#Column(name = "commission_pct")
private Double commissionPct;
#Column(name = "employees")
private Long employees;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "id", insertable = false, updatable = false)
#Fetch(FetchMode.JOIN)
private Department department;
}
Department class:
#Entity(name = "Department")
#Table(name = "departments")
#JsonInclude(Include.NON_NULL)
public class Department implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "department_name")
private String departmentName;
#Column(name = "department_id")
private long departmentId;
#Column(name = "manager_id")
private Double managerId;
#Column(name = "location_id")
private Double locationId;
}
Association class:
public class DeptEmpDto {
private long departmentId;
private String departmentName;
private Double managerId;
private Double locationId;
private long employeeId;
private String firstName;
private String lastName;
private String phoneNumber;
private Double hireDate;
private Long jobId;
private Double salary;
private Double commissionPct;
}
Repository:
public interface IEmployeeRepository extends JpaRepository<Employee, Long> {
#Query("SELECT new com.concretepage.entity.DeptEmpDto(d.departmentId,d.departmentName,d.managerId,d.locationId,e.employeeId,e.firstName,e.lastName,e.phoneNumber,e.hireDate,e.jobId,e.salary,e.commissionPct FROM Employee e INNER JOIN Department d ON d.id = e.jobId")
List<DeptEmpDto> fetchEmpDeptDataInnerJoin();
You can use it in Employee class
#ManyToMany(fetch = FetchType.EAGER)
#JoinTable(
name = "DeptEmp",
joinColumns = #JoinColumn(name = "emp_id",referencedColumnName = "id"),
inverseJoinColumns = #JoinColumn(name = "dep_id",referencedColumnName = "id")
)
private Set<Departments> departments = new HashSet<>();
Look at this about JPA
Logically an employee can't work in two departements so your relationship is correct
But you can do that with a #ManyToMany annotation.

Categories

Resources