在Spring Data JPA中联接两个实体

时间:2019-03-22 10:32:30

标签: java eclipse spring-boot jpa-2.0

我在Mysql数据库中有两个表:Department和Contact。我在apllication.properties文件中连接了我的应用程序。

这是我的数据库:

enter image description here

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>

这是我的联系方式:

@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

这是我的部门课程:

@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

我可以使用百里香在表中显示第一个实体:部门

enter image description here

我想要做的是:当我单击行1的“查看”按钮等PWD时,动态显示所有属于ICT的员工。

我已将项目上传到github: https://github.com/sammizodev/Jpa_two_tables

1 个答案:

答案 0 :(得分:1)

以下是您发布的代码的代码回顾:

命名约定:您应该看看java naming conventions,类属性应遵循驼峰式语法,忽略下划线的使用。

上面不需要影响数据库架构,因为您可以使用@Column在表字段和类属性之间进行映射,例如:

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

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

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

注意,order是许多数据库中的关键字,因此您可能需要更改它。

有趣的约定:我建议您看看restful API design,然后您才能了解如何构造应用程序以访问某些资源。

根据约定,您只有一个资源(部门),并且需要以下URI:

  • URI:获取/部门- /department/list.html -部门的呈现表
  • URI: GET / department / {id} - /department/show.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
}

然后,您需要一个GET /departments/{id}才能呈现部门详细信息,包括联系人列表。

因此,在部门列表模板上,您应该建立链接,例如:

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

注意,您需要提供/home/contact/{departmentId}之类的url,以便tymeleaf可以替换id属性,否则将作为参数接收。

在您的控制器上,您需要更新到联系人的映射,以将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";
}

如果您的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>

另外,请记住将ContactService连接到您的DemoController

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