0% found this document useful (0 votes)
9 views13 pages

JPA. Key

Jpa

Uploaded by

dinesh2562
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views13 pages

JPA. Key

Jpa

Uploaded by

dinesh2562
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 13

*Task Summary:*

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:*

1. Added `@OneToMany` annotation to the `Claim` entity's `items` field.

2. Specified `mappedBy = "claim"` to indicate the inverse association.

3. Added `cascade = CascadeType.ALL` and `orphanRemoval = true` for


cascading operations.

4. Created getters and setters for the `items` field.

5. No changes required in the `Item` entity.

6. Verified the bidirectional association using the


`bidirectionalAssociationTest` JUnit test.

*Key Code Changes:*

```

// Claim entity

@OneToMany(mappedBy = "claim", cascade = CascadeType.ALL,


orphanRemoval = true)

private List<Item> items;

```

*Result:* Bidirectional association established between `Claim` and `Item`


entities, enabling management of items from the owning claim.
Q: Project 1: (5 Task) Task 1: Persistence/JPA Mapping The original developer
did not consider that there would be a requirement to manage the list of
items from the owning Claim so only the Item to Claim association was
mapped using JPA. You are now asked to make this mapping bidirectional,
maintaining the existing many-to-one association from Item to Claim and
creating an appropriate inverse association from Claim to Item. Update the
expenses project located in /home/candidate/workspace/expenses as follows:
Update the Claim class (com.example.expenses.entity.Claim) to map the
association from Claim to Item (the items property). This is the inverse of the
existing association between Item and Claim as already mapped by
Item.claim. Testing your work Run the
com.example.expenses.JPATest.bidirectionalAssociationTest JUnit test to
check your work.

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:

*Step 1: Update Claim Entity*

```

// com/example/expenses/entity/Claim.java

@Entity

public class Claim {

// existing code...

@OneToMany(mappedBy = "claim", cascade = CascadeType.ALL,


orphanRemoval = true)

private List<Item> items;


// getters and setters

public List<Item> getItems() {

return items;

public void setItems(List<Item> items) {

this.items = items;

```

*Step 2: Update Item Entity (no changes needed)*

The `Item` entity already has the `@ManyToOne` association with `Claim`,
so no changes are required.

```

// com/example/expenses/entity/Item.java

@Entity

public class Item {

// existing code...

@ManyToOne

@JoinColumn(name = "claim_id")

private Claim claim;


// getters and setters

public Claim getClaim() {

return claim;

public void setClaim(Claim claim) {

this.claim = claim;

```

*Step 3: Run JUnit Test*

Run the `bidirectionalAssociationTest` JUnit test in `JPATest` to verify the


bidirectional association.

```

// com/example/expenses/JPATest.java

@RunWith(SpringJUnit4ClassRunner.class)

@ContextConfiguration(classes = JPAConfig.class)

public class JPATest {

// existing code...

@Test

public void bidirectionalAssociationTest() {

// test logic to verify bidirectional association


}

```

With these changes, the association between `Claim` and `Item` is now
bidirectional, and the JUnit test should pass.

Bidirectional Association:

A bidirectional association in JPA (Java Persistence API) allows two entities to


have a relationship where both entities can navigate to each other.

*Characteristics:*

1. Two entities are involved (e.g., `Claim` and `Item`).

2. Each entity has a reference to the other.

3. Both entities can navigate to each other.

*Annotations:*

1. `@OneToMany` (on the owner side, e.g., `Claim`).

2. `@ManyToOne` (on the inverse side, e.g., `Item`).

3. `mappedBy` attribute specifies the inverse relationship.

*Benefits:*

1. Simplifies navigation between related entities.

2. Enables fetching of associated entities.


3. Improves performance by reducing queries.

*Example:*

```

// Claim entity (owner side)

@Entity

public class Claim {

@OneToMany(mappedBy = "claim", cascade = CascadeType.ALL,


orphanRemoval = true)

private List<Item> items;

// getters and setters

// Item entity (inverse side)

@Entity

public class Item {

@ManyToOne

@JoinColumn(name = "claim_id")

private Claim claim;

// getters and setters

```

*Types of Bidirectional Associations:*

1. One-to-One (1:1)
2. One-to-Many (1:N)

3. Many-to-Many (M:N)

*Best Practices:*

1. Define the owner side carefully.

2. Use `mappedBy` to avoid duplicate relationships.

3. Consider cascading operations and orphan removal.

By establishing bidirectional associations, you can create robust and efficient


relationships between entities in your JPA-based applications.

Bidirectional Association with Database Table Explanation:

Consider two entities: `Claim` and `Item`, with a bidirectional one-to-many


relationship.

*Database Tables:*

```

CREATE TABLE CLAIM (

CLAIM_ID INT PRIMARY KEY,

CLAIM_NAME VARCHAR(255)

);

CREATE TABLE ITEM (

ITEM_ID INT PRIMARY KEY,

CLAIM_ID INT,
ITEM_NAME VARCHAR(255),

FOREIGN KEY (CLAIM_ID) REFERENCES CLAIM(CLAIM_ID)

);

```

*Entity Relationship Diagram (ERD):*

```

+---------------+

| CLAIM |

+---------------+

| CLAIM_ID (PK) |

| CLAIM_NAME |

+---------------+

| 1:N

+---------------+

| ITEM |

+---------------+

| ITEM_ID (PK) |

| CLAIM_ID (FK) |

| ITEM_NAME |

+---------------+

```
*JPA Entities:*

```

// Claim entity (owner side)

@Entity

public class Claim {

@Id

@GeneratedValue(strategy = GenerationType.IDENTITY)

private Long claimId;

private String claimName;

@OneToMany(mappedBy = "claim", cascade = CascadeType.ALL,


orphanRemoval = true)

private List<Item> items;

// getters and setters

// Item entity (inverse side)

@Entity

public class Item {

@Id

@GeneratedValue(strategy = GenerationType.IDENTITY)

private Long itemId;

private String itemName;

@ManyToOne

@JoinColumn(name = "CLAIM_ID")
private Claim claim;

// getters and setters

```

*Bidirectional Association:*

1. `Claim` entity has a one-to-many relationship with `Item` entities.

2. `Item` entity has a many-to-one relationship with `Claim` entity.

3. `CLAIM_ID` foreign key in `ITEM` table establishes the relationship.

*Benefits:*

1. Simplifies navigation between related entities.

2. Enables fetching of associated entities.

3. Improves performance by reducing queries.

*Example Use Case:*

```

// Create a Claim

Claim claim = new Claim("My Claim");

em.persist(claim);

// Create an Item

Item item = new Item("My Item", claim);

em.persist(item);
// Navigate from Claim to Item

List<Item> items = claim.getItems();

// Navigate from Item to Claim

Claim claim = item.getClaim();

```

2. Task 2 Bean validation

Here are the updated classes with Bean Validation annotations:

*Class 1: Claim*

```

@Entity

public class Claim {

@NotNull

@Past

private Date claimedOn;

@Size(max = 120)

private String purpose;

// getters and setters

```
*Class 2: Type*

```

@Entity

public class Type {

@Pattern(regexp = "\\d{3}:\\d{5}")

private String code;

// getters and setters

```

*Class 3: Item*

```

@Entity

public class Item {

@Past(message = "only past data is allowed")

private Date incurred;

@DecimalMax(value = "999.99")

@Digits(integer = 3, fraction = 2)

private BigDecimal amount;

// getters and setters


}

``]

Explanation:

* `@NotNull` ensures that the field cannot be null.

* `@Size(max = 120)` ensures that the purpose string does not exceed 120
characters.

* `@Pattern(regexp = "\\d{3}:\\d{5}")` ensures that the type code matches


the specified pattern (3 digits, colon, 5 digits).

* `@Past` ensures that the date is in the past.

* `@DecimalMax(value = "999.99")` and `@Digits(integer = 3, fraction =


2)` ensure that the amount does not exceed 3 integral digits and 2 fractional
digits.

Run the `com.example.expenses.ValidationTest` JUnit test to verify your


work.

```

You might also like