Mark As Completed Discussion

Entity-Relationship Mapping

In low level design, entity-relationship mapping is a crucial step that involves mapping objects from our system to database entities and establishing relationships between these entities. By mapping objects to database entities, we can effectively store and retrieve data in a structured manner.

To understand entity-relationship mapping, let's use an example related to a payment application.

Consider the following entities in our payment application:

  • User: Represents a user of the application and has attributes such as user_id, name, and email.
  • Account: Represents a user's account and has attributes such as account_id, user_id (foreign key), and balance.
  • Transaction: Represents a transaction made by a user and has attributes such as transaction_id, account_id (foreign key), amount, and timestamp.

To establish relationships between these entities, we can use foreign keys. In our example, the user_id attribute in the Account entity is a foreign key that references the user_id attribute in the User entity. Similarly, the account_id attribute in the Transaction entity is a foreign key that references the account_id attribute in the Account entity.

By establishing these relationships, we can create a logical connection between the entities in our database. For example, we can retrieve all transactions made by a specific user by joining the User, Account, and Transaction tables using the foreign keys.

Let's take a look at an example of entity-relationship mapping using Java code:

TEXT/X-JAVA
1class User {
2  int user_id;
3  String name;
4  String email;
5}
6
7class Account {
8  int account_id;
9  int user_id;
10  double balance;
11}
12
13class Transaction {
14  int transaction_id;
15  int account_id;
16  double amount;
17  Date timestamp;
18}
19
20// Create a user
21User user = new User();
22user.user_id = 1;
23user.name = "John Doe";
24user.email = "john@example.com";
25
26// Create an account
27Account account = new Account();
28account.account_id = 1;
29account.user_id = user.user_id;
30account.balance = 1000.0;
31
32// Create a transaction
33Transaction transaction = new Transaction();
34transaction.transaction_id = 1;
35transaction.account_id = account.account_id;
36transaction.amount = 50.0;
37transaction.timestamp = new Date();