- Java EE 8 High Performance
- Romain Manni Bucau
- 330字
- 2021-06-30 19:14:24
The persistence layer
Our data model will be simple: a quote will be linked to a customer. This means that a customer can see a set of quotes, and quotes can be seen by a set of customers. In terms of use cases, we want to be able to monetize our API and make the customers pay to access some quote prices. To do so, we will need a sort of whitelist of quotes per customer.
JPA uses a descriptor called persistence.xml, placed in the META-INF repository of resources (or WEB-INF), which defines how EntityManager, which is a class that allows the manipulation of our model, will be instantiated. Here is what it looks like for our application:
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_2.xsd"
version="2.2">
<persistence-unit name="quote">
<class>com.github.rmannibucau.quote.manager.model.Customer</class>
<class>com.github.rmannibucau.quote.manager.model.Quote</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="avax.persistence.schema
-generation.database.action" value="create"/>
</properties>
</persistence-unit>
</persistence>
The link between the database and the Java code is done through entities. An entity is a plain old java object (POJO) that is decorated with the javax.persistence annotations. They mainly define the mapping between the database and the Java model. For instance, @Id marks a Java field that must match the database identifier.
Here is an example of our Quote entity:
@Entity
public class Quote {
@Id
@GeneratedValue
private long id;
private String name;
private double value;
@ManyToMany
private Set<Customer> customers;
// getters/setters
}
This simple model implicitly defines a QUOTE table with three columns, ID, NAME, and VALUE (the casing can depend on the database), and a table to manage the relationship with the CUSTOMER table, which is named QUOTE_CUSTOMER by default.
In the same spirit, our Customer entity just defines an identifier and name as columns and also the reverse relationship to the Quote entity:
@Entity
public class Customer {
@Id
@GeneratedValue
private long id;
private String name;
@ManyToMany(mappedBy = "customers")
private Set<Quote> quotes;
// getters/setters
}
What is important here is to notice the relationships in the model. We will deal with this later on.
- 電腦組裝與系統安裝
- pcDuino開發實戰
- Linux設備驅動開發詳解(第2版)
- Linux系統架構與運維實戰
- Hands-On DevOps with Vagrant
- 奔跑吧 Linux內核(入門篇)
- Linux自動化運維:Shell與Ansible(微課版)
- AutoCAD 2014中文版從入門到精通
- 深入淺出Node.js
- iOS 8開發指南
- 分布式高可用架構之道
- Advanced Infrastructure Penetration Testing
- Learn SwiftUI
- Linux網絡操作系統項目教程(RHEL 7.4/CentOS 7.4)(第3版)(微課版)
- Learning Continuous Integration with Jenkins(Second Edition)