Anyone who wants to learn about JPA needs to know about the concept of Object Relational Mapping. So what is it actually?
Suppose, you are working on an application and your application uses a table named users in the database. The structure of this table is as follows:
1 2 3 4 5 6 7 8 |
CREATE TABLE `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(45) NOT NULL, `date_of_birth` date DEFAULT NULL, `email` varchar(45) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; create database coffee; |
When we learned about JDBC, in order to get all the data in this users table, we had to write the code to connect to the database and use the SELECT statement as below:
1 |
SELECT * FROM users; |
Then, you have to browse each line of the results to get the data you want.
In addition to the different database types, such as MySQL, Oracle, … have the same query purpose but the syntax is completely different depending on the type of database.
But now we do not have to be so hard anymore!
Object Relational Mapping is a programming technique that allows us to manipulate databases via Java objects. We will map the tables and columns of our database table to its objects and attributes. The relationship between the tables and columns is also reflected in the objects to which it is mapped.
As you can see in the example above, we can map the users table to an object named Users. As follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 |
@Entity @Table(name = "users") public class Users { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Integer id; @Column(name = "name") private String name; @Column(name = "date_of_birth") private Date dateOfBirth; @Column(name = "email") private String email; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getDateOfBirth() { return dateOfBirth; } public void setDateOfBirth(Date dateOfBirth) { this.dateOfBirth = dateOfBirth; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } } |
As you can see, the id column in the users table is mapped to the id attribute in the Users object, which is the same for the other columns.
And now you can use the Users object above to manipulate the database without regard to the type of database which you are using. That someone else worried, the JDBC Driver 😀