简体   繁体   English

在Spring Data JPA中联接两个实体

[英]Joining Two Entities in Spring Data JPA

I have two tables in a Mysql database: Department and Contact. 我在Mysql数据库中有两个表:Department和Contact。 I connected with my application in the apllication.properties file. 我在apllication.properties文件中连接了我的应用程序。

This is my Database: 这是我的数据库:

在此处输入图片说明

pom.xml is as Follows: pom.xml如下所示:

<?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: 我可以使用百里香在表中显示第一个实体:部门:

在此处输入图片说明

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. 我想要做的是:当我单击行1中的“查看”按钮时,动态显示所有属于ICT的员工,对于PWD,则如此。

I have uploaded the project in github: https://github.com/sammizodev/Jpa_two_tables 我已经在github中上传了该项目: https : //github.com/sammizodev/Jpa_two_tables

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. 命名约定 :您应该看一下Java的命名约定 ,类属性应遵循驼峰式语法,忽略下划线的使用。

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: 上面的内容不需要影响您的数据库架构,因为您可以使用@Column在表字段和类属性之间进行映射,例如:

@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. 注意,order是许多数据库中的关键字,因此您可能需要更改它。

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. 宁静的约定 :我建议您看一下宁静的API设计 ,然后您可以了解如何构造应用程序以访问某些资源。

According to conventions, you have one resource(department) and you would need these URI: 根据约定,您只有一个资源(部门),因此需要以下URI:

  • URI: GET /department - /department/list.html - Render table of department URI: GET / department-/department / list.html-部门的渲染表
  • URI: GET /department/{id} - /department/show.html - Render a department with details(contact table). URI: GET / department / {id} - /department/ show.html-渲染具有详细信息的部门(联系表)。

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. 例如,您具有GET /departments_list来呈现您的部门列表,而您需要将其更改为GET /departments并且您的模板应命名为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. 然后,您将需要GET /departments/{id}来呈现部门详细信息,包括联系人列表。

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. 注意,您需要提供/home/contact/{departmentId}类的url,以便tymeleaf可以替换id属性,否则将作为参数接收。

On your controller you need to update the mapping to the contacts to include the id as a path variable: 在您的控制器上,您需要更新到联系人的映射,以将id包含为路径变量:

@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. 如果您的Department类加载了渴望的联系人,则可以在show.html模板中访问前端中的列表。

<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 . 另外,请记住在DemoControllerDemoController ContactService

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 使用where子句连接Spring Data JPA中的两个表实体 - Joining two table entities in Spring Data JPA with where clause Spring Data JPA +联接2个表 - Spring data jpa + joining 2 tables 两个JPA / Spring数据实体具有相同的结构但表不同 - Two JPA/Spring Data entities with identical structure but different tables 不同方案的两个实体之间的关系 - Spring Boot Data JPA - Relationship between two entities of different schemes - Spring Boot Data JPA Spring 数据 JPA:如何使用注释连接两个实体 - Spring Data JPA: How to join two entities using annotations 为什么在通过连接 JPA 中的两个不相关实体来使用投影获取数据时未设置投影字段? - Why projection fields are not getting set while fetching data using projection by joining two unrelated entities in JPA? 在 spring-boot 中加入两个实体 - Joining two entities in spring-boot 在spring数据JPA中联接两个表并从存储库中查询两个表数据 - Joining two table in spring data JPA and Querying two table data from repository Spring Data JPA- 有两个 JPA 实体引用一个不是实体的数据库表 - Spring Data JPA- Having two JPA entities that reference a database table that isnt an entity 带有 QueryDslPredicateExecutor 并加入集合的 Spring-Data-JPA - Spring-Data-JPA with QueryDslPredicateExecutor and Joining into a collection
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM