Joining Two Entities in Spring Data JPA Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 00:00UTC (8:00pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!How can I concatenate two arrays in Java?How do I join two lists in Java?How to solve “Plugin execution not covered by lifecycle configuration” for Spring Data Maven BuildsWhat's the difference between @Component, @Repository & @Service annotations in Spring?Why is subtracting these two times (in 1927) giving a strange result?Spring-boot error using Apache Derby as embedded databaseSpring Boot sending List Model from jsp formSpring boot java.lang.IllegalStateExceptionInvocation of init method failed; nested exception is java.lang.NoClassDefFoundError: javassist/bytecode/ClassFilePlace holder not working in application.yml

How to write the following sign?

Most bit efficient text communication method?

Has negative voting ever been officially implemented in elections, or seriously proposed, or even studied?

What is the meaning of 'breadth' in breadth first search?

Should I use a zero-interest credit card for a large one-time purchase?

How often does castling occur in grandmaster games?

How to react to hostile behavior from a senior developer?

Is there a kind of relay that only consumes power when switching?

Is it a good idea to use CNN to classify 1D signal?

Can a new player join a group only when a new campaign starts?

What would you call this weird metallic apparatus that allows you to lift people?

Maximum summed subsequences with non-adjacent items

Denied boarding although I have proper visa and documentation. To whom should I make a complaint?

How would a mousetrap for use in space work?

Do any jurisdictions seriously consider reclassifying social media websites as publishers?

Take 2! Is this homebrew Lady of Pain warlock patron balanced?

Why weren't discrete x86 CPUs ever used in game hardware?

Sum letters are not two different

How to play a character with a disability or mental disorder without being offensive?

How come Sam didn't become Lord of Horn Hill?

Why do we need to use the builder design pattern when we can do the same thing with setters?

What is "gratricide"?

Morning, Afternoon, Night Kanji

Central Vacuuming: Is it worth it, and how does it compare to normal vacuuming?



Joining Two Entities in Spring Data JPA



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 23, 2019 at 00:00UTC (8:00pm US/Eastern)
Data science time! April 2019 and salary with experience
The Ask Question Wizard is Live!How can I concatenate two arrays in Java?How do I join two lists in Java?How to solve “Plugin execution not covered by lifecycle configuration” for Spring Data Maven BuildsWhat's the difference between @Component, @Repository & @Service annotations in Spring?Why is subtracting these two times (in 1927) giving a strange result?Spring-boot error using Apache Derby as embedded databaseSpring Boot sending List Model from jsp formSpring boot java.lang.IllegalStateExceptionInvocation of init method failed; nested exception is java.lang.NoClassDefFoundError: javassist/bytecode/ClassFilePlace holder not working in application.yml



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








0















I have two tables in a Mysql database: Department and Contact. I connected with my application in the apllication.properties file.



This is my Database:



enter image description here



pom.xml is as Follows:



<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo1</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo1</name>
<description>Demo project for Spring Boot</description>

<properties>
<java.version>1.8</java.version>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

</project>


This is my contact class:



@Entity
@Table(name="contact")
public class Contact {

@Id
@Column(name="contact_id")
private int Contact_id;

@Column(name="emp_name")
private String Emp_name;

@Column(name="mobile")
private String Mobile;


@Column(name="landline_office")
private String Landline_office;

@Column(name="landline_res")
private String Landline_res;

@Column(name="fax")
private String Fax;

@Column(name="email")
private String Email;

@ManyToOne(cascade= CascadeType.PERSIST,CascadeType.MERGE,
CascadeType.DETACH,CascadeType.REFRESH)
@JoinColumn(name="department_dept_id")
private Department department;

... constructors and getters and setters


This is my department class:



@Entity
@Table(name="department")
public class Department {

@Id
@Column(name="dept_id")
private int Dept_id;

@Column(name="dept_name")
private String Dept_name;

@Column(name="order")
private String Order;

@Column(name="home")
private int Home;

@OneToMany(mappedBy="department",
cascade= CascadeType.PERSIST,CascadeType.MERGE,
CascadeType.DETACH,CascadeType.REFRESH)
private List<Contact> contacts;

public Department()



...getters and setters and constructors


I can display the first entity: Department in table using thymeleaf:



enter image description here



What I want to do is: Dynamically display all employees belonging to ICT when i click View button in row 1 and so for PWD.



I have uploaded the project in github:
https://github.com/sammizodev/Jpa_two_tables










share|improve this question
























  • Thank you very much. But it is not my homework. Im really new to java that is all. I have tried writting many simple apps with one table. Its just a hobby.

    – Sam
    Mar 22 at 12:30


















0















I have two tables in a Mysql database: Department and Contact. I connected with my application in the apllication.properties file.



This is my Database:



enter image description here



pom.xml is as Follows:



<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo1</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo1</name>
<description>Demo project for Spring Boot</description>

<properties>
<java.version>1.8</java.version>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

</project>


This is my contact class:



@Entity
@Table(name="contact")
public class Contact {

@Id
@Column(name="contact_id")
private int Contact_id;

@Column(name="emp_name")
private String Emp_name;

@Column(name="mobile")
private String Mobile;


@Column(name="landline_office")
private String Landline_office;

@Column(name="landline_res")
private String Landline_res;

@Column(name="fax")
private String Fax;

@Column(name="email")
private String Email;

@ManyToOne(cascade= CascadeType.PERSIST,CascadeType.MERGE,
CascadeType.DETACH,CascadeType.REFRESH)
@JoinColumn(name="department_dept_id")
private Department department;

... constructors and getters and setters


This is my department class:



@Entity
@Table(name="department")
public class Department {

@Id
@Column(name="dept_id")
private int Dept_id;

@Column(name="dept_name")
private String Dept_name;

@Column(name="order")
private String Order;

@Column(name="home")
private int Home;

@OneToMany(mappedBy="department",
cascade= CascadeType.PERSIST,CascadeType.MERGE,
CascadeType.DETACH,CascadeType.REFRESH)
private List<Contact> contacts;

public Department()



...getters and setters and constructors


I can display the first entity: Department in table using thymeleaf:



enter image description here



What I want to do is: Dynamically display all employees belonging to ICT when i click View button in row 1 and so for PWD.



I have uploaded the project in github:
https://github.com/sammizodev/Jpa_two_tables










share|improve this question
























  • Thank you very much. But it is not my homework. Im really new to java that is all. I have tried writting many simple apps with one table. Its just a hobby.

    – Sam
    Mar 22 at 12:30














0












0








0








I have two tables in a Mysql database: Department and Contact. I connected with my application in the apllication.properties file.



This is my Database:



enter image description here



pom.xml is as Follows:



<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo1</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo1</name>
<description>Demo project for Spring Boot</description>

<properties>
<java.version>1.8</java.version>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

</project>


This is my contact class:



@Entity
@Table(name="contact")
public class Contact {

@Id
@Column(name="contact_id")
private int Contact_id;

@Column(name="emp_name")
private String Emp_name;

@Column(name="mobile")
private String Mobile;


@Column(name="landline_office")
private String Landline_office;

@Column(name="landline_res")
private String Landline_res;

@Column(name="fax")
private String Fax;

@Column(name="email")
private String Email;

@ManyToOne(cascade= CascadeType.PERSIST,CascadeType.MERGE,
CascadeType.DETACH,CascadeType.REFRESH)
@JoinColumn(name="department_dept_id")
private Department department;

... constructors and getters and setters


This is my department class:



@Entity
@Table(name="department")
public class Department {

@Id
@Column(name="dept_id")
private int Dept_id;

@Column(name="dept_name")
private String Dept_name;

@Column(name="order")
private String Order;

@Column(name="home")
private int Home;

@OneToMany(mappedBy="department",
cascade= CascadeType.PERSIST,CascadeType.MERGE,
CascadeType.DETACH,CascadeType.REFRESH)
private List<Contact> contacts;

public Department()



...getters and setters and constructors


I can display the first entity: Department in table using thymeleaf:



enter image description here



What I want to do is: Dynamically display all employees belonging to ICT when i click View button in row 1 and so for PWD.



I have uploaded the project in github:
https://github.com/sammizodev/Jpa_two_tables










share|improve this question
















I have two tables in a Mysql database: Department and Contact. I connected with my application in the apllication.properties file.



This is my Database:



enter image description here



pom.xml is as Follows:



<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.3.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example</groupId>
<artifactId>demo1</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>demo1</name>
<description>Demo project for Spring Boot</description>

<properties>
<java.version>1.8</java.version>
</properties>

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>

</project>


This is my contact class:



@Entity
@Table(name="contact")
public class Contact {

@Id
@Column(name="contact_id")
private int Contact_id;

@Column(name="emp_name")
private String Emp_name;

@Column(name="mobile")
private String Mobile;


@Column(name="landline_office")
private String Landline_office;

@Column(name="landline_res")
private String Landline_res;

@Column(name="fax")
private String Fax;

@Column(name="email")
private String Email;

@ManyToOne(cascade= CascadeType.PERSIST,CascadeType.MERGE,
CascadeType.DETACH,CascadeType.REFRESH)
@JoinColumn(name="department_dept_id")
private Department department;

... constructors and getters and setters


This is my department class:



@Entity
@Table(name="department")
public class Department {

@Id
@Column(name="dept_id")
private int Dept_id;

@Column(name="dept_name")
private String Dept_name;

@Column(name="order")
private String Order;

@Column(name="home")
private int Home;

@OneToMany(mappedBy="department",
cascade= CascadeType.PERSIST,CascadeType.MERGE,
CascadeType.DETACH,CascadeType.REFRESH)
private List<Contact> contacts;

public Department()



...getters and setters and constructors


I can display the first entity: Department in table using thymeleaf:



enter image description here



What I want to do is: Dynamically display all employees belonging to ICT when i click View button in row 1 and so for PWD.



I have uploaded the project in github:
https://github.com/sammizodev/Jpa_two_tables







java eclipse spring-boot jpa-2.0






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 22 at 19:52









Thomas Fritsch

5,566122236




5,566122236










asked Mar 22 at 10:32









SamSam

11




11












  • Thank you very much. But it is not my homework. Im really new to java that is all. I have tried writting many simple apps with one table. Its just a hobby.

    – Sam
    Mar 22 at 12:30


















  • Thank you very much. But it is not my homework. Im really new to java that is all. I have tried writting many simple apps with one table. Its just a hobby.

    – Sam
    Mar 22 at 12:30

















Thank you very much. But it is not my homework. Im really new to java that is all. I have tried writting many simple apps with one table. Its just a hobby.

– Sam
Mar 22 at 12:30






Thank you very much. But it is not my homework. Im really new to java that is all. I have tried writting many simple apps with one table. Its just a hobby.

– Sam
Mar 22 at 12:30













1 Answer
1






active

oldest

votes


















1














Here is a code review of the code you post:



Naming conventions: You should take a look at java naming conventions, class attributes should follow camel case syntax, use of underscore is disregard.



Above does not need to impact your database schema, as you can use @Column to do the mapping between your table field and class attribute, for instance:



@Id
@Column(name="dept_id")
private int id;

@Column(name="dept_name")
private String name;

@Column(name="dept_order")
private String Order;


Notice, order is a keyword in many database, so you may need to change it.



Restful Conventions: I would suggest you to take a look at restful API design, then you can understand how to structure your application to access certain resources.



According to conventions, you have one resource(department) and you would need these URI:



  • URI: GET /department - /department/list.html - Render table of department

  • URI: GET /department/id - /department/show.html - Render a department with details(contact table).

For instance, you have GET /departments_list to render your department list, you would need instead to change it to GET /departments and your template should be named list.html.



@GetMapping("/departments")
public String listDepartments(Model model)
List<Department> departments = departmentService.findAll();
model.addAttribute("departments",departments);
return "/departments/list"; // Your current thymeleaf template



Then you would need a GET /departments/id in order to render the department details including the list of contacts.



So on your department list template you should build the link like:



<a th:href="@/home/contact/departmentId(departmentId=$tempDepartment.dept_id)"
class="btn btn-info btn-sm">View</a>


Notice, you need to provide the url like /home/contact/departmentId so tymeleaf can replace the id property, otherwise you will received as a parameter.



On your controller you need to update the mapping to the contacts to include the id as a path variable:



@GetMapping("/departments/id")
public String listContacts(@PathVariable("id") int theId, Model theModel)
Department department = departmentService.findById(theId);
theModel.addAttribute("department",department);
return "/departments/show";



If your Department class loads contacts eager, you could access the list in your front-end in a show.html template.



<tr th:each="contact : $department.contacts"> 
<td th:text="$contact.contact_id" />
<td th:text="$contact.emp_name" />
<td th:text="$contact.mobile" />
<td th:text="$contact.landline_office" />
</tr>


Also, remember to wire the ContactService at your DemoController.



public DemoController(DepartmentService departmentService, ContactService contactService) 
this.departmentService = departmentService;
this.contactService = contactService;






share|improve this answer

























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55297689%2fjoining-two-entities-in-spring-data-jpa%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














    Here is a code review of the code you post:



    Naming conventions: You should take a look at java naming conventions, class attributes should follow camel case syntax, use of underscore is disregard.



    Above does not need to impact your database schema, as you can use @Column to do the mapping between your table field and class attribute, for instance:



    @Id
    @Column(name="dept_id")
    private int id;

    @Column(name="dept_name")
    private String name;

    @Column(name="dept_order")
    private String Order;


    Notice, order is a keyword in many database, so you may need to change it.



    Restful Conventions: I would suggest you to take a look at restful API design, then you can understand how to structure your application to access certain resources.



    According to conventions, you have one resource(department) and you would need these URI:



    • URI: GET /department - /department/list.html - Render table of department

    • URI: GET /department/id - /department/show.html - Render a department with details(contact table).

    For instance, you have GET /departments_list to render your department list, you would need instead to change it to GET /departments and your template should be named list.html.



    @GetMapping("/departments")
    public String listDepartments(Model model)
    List<Department> departments = departmentService.findAll();
    model.addAttribute("departments",departments);
    return "/departments/list"; // Your current thymeleaf template



    Then you would need a GET /departments/id in order to render the department details including the list of contacts.



    So on your department list template you should build the link like:



    <a th:href="@/home/contact/departmentId(departmentId=$tempDepartment.dept_id)"
    class="btn btn-info btn-sm">View</a>


    Notice, you need to provide the url like /home/contact/departmentId so tymeleaf can replace the id property, otherwise you will received as a parameter.



    On your controller you need to update the mapping to the contacts to include the id as a path variable:



    @GetMapping("/departments/id")
    public String listContacts(@PathVariable("id") int theId, Model theModel)
    Department department = departmentService.findById(theId);
    theModel.addAttribute("department",department);
    return "/departments/show";



    If your Department class loads contacts eager, you could access the list in your front-end in a show.html template.



    <tr th:each="contact : $department.contacts"> 
    <td th:text="$contact.contact_id" />
    <td th:text="$contact.emp_name" />
    <td th:text="$contact.mobile" />
    <td th:text="$contact.landline_office" />
    </tr>


    Also, remember to wire the ContactService at your DemoController.



    public DemoController(DepartmentService departmentService, ContactService contactService) 
    this.departmentService = departmentService;
    this.contactService = contactService;






    share|improve this answer





























      1














      Here is a code review of the code you post:



      Naming conventions: You should take a look at java naming conventions, class attributes should follow camel case syntax, use of underscore is disregard.



      Above does not need to impact your database schema, as you can use @Column to do the mapping between your table field and class attribute, for instance:



      @Id
      @Column(name="dept_id")
      private int id;

      @Column(name="dept_name")
      private String name;

      @Column(name="dept_order")
      private String Order;


      Notice, order is a keyword in many database, so you may need to change it.



      Restful Conventions: I would suggest you to take a look at restful API design, then you can understand how to structure your application to access certain resources.



      According to conventions, you have one resource(department) and you would need these URI:



      • URI: GET /department - /department/list.html - Render table of department

      • URI: GET /department/id - /department/show.html - Render a department with details(contact table).

      For instance, you have GET /departments_list to render your department list, you would need instead to change it to GET /departments and your template should be named list.html.



      @GetMapping("/departments")
      public String listDepartments(Model model)
      List<Department> departments = departmentService.findAll();
      model.addAttribute("departments",departments);
      return "/departments/list"; // Your current thymeleaf template



      Then you would need a GET /departments/id in order to render the department details including the list of contacts.



      So on your department list template you should build the link like:



      <a th:href="@/home/contact/departmentId(departmentId=$tempDepartment.dept_id)"
      class="btn btn-info btn-sm">View</a>


      Notice, you need to provide the url like /home/contact/departmentId so tymeleaf can replace the id property, otherwise you will received as a parameter.



      On your controller you need to update the mapping to the contacts to include the id as a path variable:



      @GetMapping("/departments/id")
      public String listContacts(@PathVariable("id") int theId, Model theModel)
      Department department = departmentService.findById(theId);
      theModel.addAttribute("department",department);
      return "/departments/show";



      If your Department class loads contacts eager, you could access the list in your front-end in a show.html template.



      <tr th:each="contact : $department.contacts"> 
      <td th:text="$contact.contact_id" />
      <td th:text="$contact.emp_name" />
      <td th:text="$contact.mobile" />
      <td th:text="$contact.landline_office" />
      </tr>


      Also, remember to wire the ContactService at your DemoController.



      public DemoController(DepartmentService departmentService, ContactService contactService) 
      this.departmentService = departmentService;
      this.contactService = contactService;






      share|improve this answer



























        1












        1








        1







        Here is a code review of the code you post:



        Naming conventions: You should take a look at java naming conventions, class attributes should follow camel case syntax, use of underscore is disregard.



        Above does not need to impact your database schema, as you can use @Column to do the mapping between your table field and class attribute, for instance:



        @Id
        @Column(name="dept_id")
        private int id;

        @Column(name="dept_name")
        private String name;

        @Column(name="dept_order")
        private String Order;


        Notice, order is a keyword in many database, so you may need to change it.



        Restful Conventions: I would suggest you to take a look at restful API design, then you can understand how to structure your application to access certain resources.



        According to conventions, you have one resource(department) and you would need these URI:



        • URI: GET /department - /department/list.html - Render table of department

        • URI: GET /department/id - /department/show.html - Render a department with details(contact table).

        For instance, you have GET /departments_list to render your department list, you would need instead to change it to GET /departments and your template should be named list.html.



        @GetMapping("/departments")
        public String listDepartments(Model model)
        List<Department> departments = departmentService.findAll();
        model.addAttribute("departments",departments);
        return "/departments/list"; // Your current thymeleaf template



        Then you would need a GET /departments/id in order to render the department details including the list of contacts.



        So on your department list template you should build the link like:



        <a th:href="@/home/contact/departmentId(departmentId=$tempDepartment.dept_id)"
        class="btn btn-info btn-sm">View</a>


        Notice, you need to provide the url like /home/contact/departmentId so tymeleaf can replace the id property, otherwise you will received as a parameter.



        On your controller you need to update the mapping to the contacts to include the id as a path variable:



        @GetMapping("/departments/id")
        public String listContacts(@PathVariable("id") int theId, Model theModel)
        Department department = departmentService.findById(theId);
        theModel.addAttribute("department",department);
        return "/departments/show";



        If your Department class loads contacts eager, you could access the list in your front-end in a show.html template.



        <tr th:each="contact : $department.contacts"> 
        <td th:text="$contact.contact_id" />
        <td th:text="$contact.emp_name" />
        <td th:text="$contact.mobile" />
        <td th:text="$contact.landline_office" />
        </tr>


        Also, remember to wire the ContactService at your DemoController.



        public DemoController(DepartmentService departmentService, ContactService contactService) 
        this.departmentService = departmentService;
        this.contactService = contactService;






        share|improve this answer















        Here is a code review of the code you post:



        Naming conventions: You should take a look at java naming conventions, class attributes should follow camel case syntax, use of underscore is disregard.



        Above does not need to impact your database schema, as you can use @Column to do the mapping between your table field and class attribute, for instance:



        @Id
        @Column(name="dept_id")
        private int id;

        @Column(name="dept_name")
        private String name;

        @Column(name="dept_order")
        private String Order;


        Notice, order is a keyword in many database, so you may need to change it.



        Restful Conventions: I would suggest you to take a look at restful API design, then you can understand how to structure your application to access certain resources.



        According to conventions, you have one resource(department) and you would need these URI:



        • URI: GET /department - /department/list.html - Render table of department

        • URI: GET /department/id - /department/show.html - Render a department with details(contact table).

        For instance, you have GET /departments_list to render your department list, you would need instead to change it to GET /departments and your template should be named list.html.



        @GetMapping("/departments")
        public String listDepartments(Model model)
        List<Department> departments = departmentService.findAll();
        model.addAttribute("departments",departments);
        return "/departments/list"; // Your current thymeleaf template



        Then you would need a GET /departments/id in order to render the department details including the list of contacts.



        So on your department list template you should build the link like:



        <a th:href="@/home/contact/departmentId(departmentId=$tempDepartment.dept_id)"
        class="btn btn-info btn-sm">View</a>


        Notice, you need to provide the url like /home/contact/departmentId so tymeleaf can replace the id property, otherwise you will received as a parameter.



        On your controller you need to update the mapping to the contacts to include the id as a path variable:



        @GetMapping("/departments/id")
        public String listContacts(@PathVariable("id") int theId, Model theModel)
        Department department = departmentService.findById(theId);
        theModel.addAttribute("department",department);
        return "/departments/show";



        If your Department class loads contacts eager, you could access the list in your front-end in a show.html template.



        <tr th:each="contact : $department.contacts"> 
        <td th:text="$contact.contact_id" />
        <td th:text="$contact.emp_name" />
        <td th:text="$contact.mobile" />
        <td th:text="$contact.landline_office" />
        </tr>


        Also, remember to wire the ContactService at your DemoController.



        public DemoController(DepartmentService departmentService, ContactService contactService) 
        this.departmentService = departmentService;
        this.contactService = contactService;







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Mar 22 at 20:42

























        answered Mar 22 at 20:18









        Cristian ColoradoCristian Colorado

        1,57821322




        1,57821322





























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55297689%2fjoining-two-entities-in-spring-data-jpa%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

            Swift 4 - func physicsWorld not invoked on collision? The Next CEO of Stack OverflowHow to call Objective-C code from Swift#ifdef replacement in the Swift language@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?dispatch_after - GCD in Swift?Swift Beta performance: sorting arraysSplit a String into an array in Swift?The use of Swift 3 @objc inference in Swift 4 mode is deprecated?How to optimize UITableViewCell, because my UITableView lags

            Access current req object everywhere in Node.js ExpressWhy are global variables considered bad practice? (node.js)Using req & res across functionsHow do I get the path to the current script with Node.js?What is Node.js' Connect, Express and “middleware”?Node.js w/ express error handling in callbackHow to access the GET parameters after “?” in Express?Modify Node.js req object parametersAccess “app” variable inside of ExpressJS/ConnectJS middleware?Node.js Express app - request objectAngular Http Module considered middleware?Session variables in ExpressJSAdd properties to the req object in expressjs with Typescript