简体   繁体   中英

How to fetch data from two tables in hibernate with spring rest api and return in single object to url

I am using Spring restful api with hibernate. And am fetching data from two tables using two entity classes named Employee and Second. I want to get the result in a list from both tables and want to return that in a single json object.

Here is my DAO class

// Method to get the result from employee table
@SuppressWarnings("unchecked")
public List<Employee> getEntityList() throws Exception {
session = sessionFactory.openSession();
    tx = session.beginTransaction();
    List<Employee> employeeList = session.createCriteria(Employee.class)
            .list();
tx.commit();
    session.close();
    return employeeList;
}

// Method to get the result from second table
@SuppressWarnings("unchecked")
public List<Second> getSecondList() throws Exception {
session = sessionFactory.openSession();
    tx = session.beginTransaction();
    List<Second> secondList = session.createCriteria(Second.class)
            .list();
    tx.commit();
    session.close();
    return secondList;
}

My service class

@Autowired
DataDao dataDao;
public List<Employee> getEntityList() throws Exception {
    return dataDao.getEntityList();
}

public List<Second> getSecondList() throws Exception {
    return dataDao.getSecondList();
}

Here is my RestController

@RequestMapping(value = "/list", method = RequestMethod.GET)
public @ResponseBody
List<Employee> getEmployee() {
    List<Employee> employeeList = null;
    try {
            employeeList = dataServices.getEntityList();
    } catch (Exception e) {
            e.printStackTrace();
    }
    return employeeList;
}

Here the data is coming from only one table employee but i want to get data from second table too and want to return that data in employeeList. W

What should i do please suggest me. Thanx in advance

I think you probably need this kind of example

@RestController

public class EmployeeRestController {


    @RequestMapping(value = "/employees")
    public Wrapper getEmployees() {

        Wrapper wrapper = getWrapper();
        return wrapper;

    }

    public Wrapper getWrapper() {
        Wrapper wrapper = new Wrapper();
        List<Employee> employees = getEmployee();
        List<Organizations> organizations = getOrg();

        wrapper.setEmployees(employees);
        wrapper.setOrganizations(organizations);

        return wrapper;
    }

    public List<Employee> getEmployee() {
        Employee employee1 = new Employee(101, "abc", "abc", "SE");
        Employee employee2 = new Employee(102, "def", "def", "SE");
        Employee employee3 = new Employee(103, "xyz", "xyz", "SE");

        List<Employee> employees = new ArrayList<Employee>();


        employees.add(employee1);
        employees.add(employee2);
        employees.add(employee3);

        return employees;
    }

    public List<Organizations> getOrg() {

        Organizations organizations1 = new Organizations();
        organizations1.setName("Google");
        Organizations organizations2 = new Organizations();
        organizations2.setName("Facebook");
        Organizations organizations3 = new Organizations();
        organizations3.setName("Apple");

        List<Organizations> organizations = new ArrayList<Organizations>();
        organizations.add(organizations1);
        organizations.add(organizations2);
        organizations.add(organizations3);

        return organizations;

    }
}


public class Wrapper {

    private List<Employee> employees;
    private List<Organizations> organizations;
    public List<Employee> getEmployees() {
        return employees;
    }
    public void setEmployees(List<Employee> employees) {
        this.employees = employees;
    }
    public List<Organizations> getOrganizations() {
        return organizations;
    }
    public void setOrganizations(List<Organizations> organizations) {
        this.organizations = organizations;
    }
}

Here Organization and Employee are two bean classes which are set into the wrapper classes.

So in your case, you get those two different object from two table and wrap them up in one Wrapper class and send it back.

I hope this might help you!!

@java developer.

The issue is you cannot collect queries output as a single fetch. You need to create a separate value object class which map to results from both the queries iteratively.

Then you need to map this value object class as a return type for spring rest API. The sample example is shown below: The client class is composing profile and adviser from two different tables. Also please take note how parseClientSpreadsheet method is setting clientprofiles and clientadvisors.

public class Client extends ReportModel {

    private static final long serialVersionUID = 2292996835674522338L;
    private ClientProfile profile;
    private List<Advisor> advisor;

    public ClientProfile getProfile() {
        return profile;
    }
    public void setProfile(ClientProfile profile) {
        this.profile = profile;
    }
    public List<Advisor> getAdvisor() {
        return advisor;
    }
    public void setAdvisor(List<Advisor> advisor) {
        this.advisor = advisor;
    }
}


@RequestMapping(method = RequestMethod.GET, value = "/list")
    public List<Client> getClients() {

        List<Client> clients;

        // Call the client service and load client data from the database and
        // return the list of clients.
        try {           
            clients = clientService.getClients();           
        } catch (Exception e) {
            file_error_logger.error("Exception while reading clients", e);
            throw e;
        }

        if (logger.isDebugEnabled()) logger.debug("Get client details successful.");

        return clients;
    }

public List<Client> parseClientSpreadsheet(String clientDetailsFilePath,
        int numberOfSheets) throws ClientDataNotFoundException {

    List<Client> clientList = new ArrayList<Client>();

        // if the row is valid, parse the data
        if (isValidRow(row, lastColumn,
                ClientDataConstants.CLIENT_REQUIRED_COLUMNS)) {
            ClientProfile clientProfile;
            List<Advisor> advisorList = new ArrayList<Advisor>();
            Client client = new Client();

            // Set client profile object values
            clientProfile = setClientProfileObject(row);

            // set Advisor list
            advisorList = setAdvisorList(row, lastColumn);

            // set Client object
            String[] additionalRecipients = row
                    .getCell(
                            Integer.parseInt(reportMailerConfigurationService
                                    .getPropertyValue(ClientDataConstants.ADDITIONAL_RECIPIENTS_CELLNUMBER)))
                    .toString().split(";");

            List<String> additionalRecipientsList = new ArrayList<String>();

            // max 4 additional recipients are allowed. So if more are
            // found, take 4 in array and ignore the rest
            for (int i = 0; i < additionalRecipients.length; i++) {
                if (!additionalRecipients[i].isEmpty()) {
                    additionalRecipientsList.add(additionalRecipients[i]);
                    if (additionalRecipientsList.size() == 4) {
                        break;
                    }
                }
            }

            client.setProfile(clientProfile);
            client.setAdvisor(advisorList);
            client.setadditional_recipients(additionalRecipientsList);

            // add the client in the collection
            clientList.add(client);
        } 
    }
    return clientList;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM