JPA. Key
JPA. Key
Update the existing one-way association between `Item` and `Claim` entities
to a bidirectional association, allowing management of the list of items from
the owning `Claim`. Modify the `Claim` entity to include a list of `Item`
objects.
*Solution Summary:*
```
// Claim entity
```
Hint: Not all tests in JPATest will pass as some of them relate to later tasks.
Solution1
To update the `Claim` class and make the association between `Claim` and
`Item` bidirectional, follow these steps:
```
// com/example/expenses/entity/Claim.java
@Entity
// existing code...
return items;
this.items = items;
```
The `Item` entity already has the `@ManyToOne` association with `Claim`,
so no changes are required.
```
// com/example/expenses/entity/Item.java
@Entity
// existing code...
@ManyToOne
@JoinColumn(name = "claim_id")
return claim;
this.claim = claim;
```
```
// com/example/expenses/JPATest.java
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = JPAConfig.class)
// existing code...
@Test
```
With these changes, the association between `Claim` and `Item` is now
bidirectional, and the JUnit test should pass.
Bidirectional Association:
*Characteristics:*
*Annotations:*
*Benefits:*
*Example:*
```
@Entity
@Entity
@ManyToOne
@JoinColumn(name = "claim_id")
```
1. One-to-One (1:1)
2. One-to-Many (1:N)
3. Many-to-Many (M:N)
*Best Practices:*
*Database Tables:*
```
CLAIM_NAME VARCHAR(255)
);
CLAIM_ID INT,
ITEM_NAME VARCHAR(255),
);
```
```
+---------------+
| CLAIM |
+---------------+
| CLAIM_ID (PK) |
| CLAIM_NAME |
+---------------+
| 1:N
+---------------+
| ITEM |
+---------------+
| ITEM_ID (PK) |
| CLAIM_ID (FK) |
| ITEM_NAME |
+---------------+
```
*JPA Entities:*
```
@Entity
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Entity
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@ManyToOne
@JoinColumn(name = "CLAIM_ID")
private Claim claim;
```
*Bidirectional Association:*
*Benefits:*
```
// Create a Claim
em.persist(claim);
// Create an Item
em.persist(item);
// Navigate from Claim to Item
```
*Class 1: Claim*
```
@Entity
@NotNull
@Past
@Size(max = 120)
```
*Class 2: Type*
```
@Entity
@Pattern(regexp = "\\d{3}:\\d{5}")
```
*Class 3: Item*
```
@Entity
@DecimalMax(value = "999.99")
@Digits(integer = 3, fraction = 2)
``]
Explanation:
* `@Size(max = 120)` ensures that the purpose string does not exceed 120
characters.
```