Composite Key with JPA and Hibernate

Composite Key with JPA and Hibernate

In this article let discuss on

How to map Composite Key  with JPA and Hibernate

Domain Model

A relational database composite key contains two or more columns which together for the primary key of a given table.

Composite Key with JPA and Hibernate

In the diagram above, the employee table has a Composite Key, which consists of two columns:

    • company_id
    • employee_number

Every Employee can also have a Phone, which uses the same composite key to reference its owning Employee.

Composite Primary Key with JPA and Hibernate

To map this database table mapping, we need to isolate the compound key into an @Embeddable first:

@Embeddable
public class EmployeeId implements Serializable {
 
    @Column(name = "company_id")
    private Long companyId;
 
    @Column(name = "employee_number")
    private Long employeeNumber;
 
    public EmployeeId() {
    }
 
    public EmployeeId(Long companyId, Long employeeId) {
        this.companyId = companyId;
        this.employeeNumber = employeeId;
    }
 
    public Long getCompanyId() {
        return companyId;
    }
 
    public Long getEmployeeNumber() {
        return employeeNumber;
    }
 
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof EmployeeId)) return false;
        EmployeeId that = (EmployeeId) o;
        return Objects.equals(getCompanyId(), that.getCompanyId()) &&
                Objects.equals(getEmployeeNumber(), that.getEmployeeNumber());
    }
 
    @Override
    public int hashCode() {
        return Objects.hash(getCompanyId(), getEmployeeNumber());
    }
}

The JPA specification says that all entity identifiers should be serializable and implement equals and hashCode.

So, an Embeddable that is used as a composite identifier must be Serializable and implement equals and hashCode.

The Employee mapping looks as follows:


@Entity(name = "Employee")
@Table(name = "employee")
public class Employee {
 
    @EmbeddedId
    private EmployeeId id;
 
    private String name;
 
    public EmployeeId getId() {
        return id;
    }
 
    public void setId(EmployeeId id) {
        this.id = id;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
}


The @EmbeddedId is used to instruct Hibernate that theEmployeeentity uses a compound key.

The Phone mapping is rather straightforward as well:


@Entity(name = "Phone")
@Table(name = "phone")
public class Phone {
 
    @Id
    @Column(name = "`number`")
    private String number;
 
    @ManyToOne
    @JoinColumns({
        @JoinColumn(
            name = "company_id",
            referencedColumnName = "company_id"),
        @JoinColumn(
            name = "employee_number",
            referencedColumnName = "employee_number")
    })
    private Employee employee;
 
    public Employee getEmployee() {
        return employee;
    }
 
    public void setEmployee(Employee employee) {
        this.employee = employee;
    }
 
    public String getNumber() {
        return number;
    }
 
    public void setNumber(String number) {
        this.number = number;
    }
}

The Phone uses the number as an entity identifier since every phone number and the @ManyToOne mapping uses the two columns that are part of the compound key.

Mapping relationships using the Composite Key

We can even map relationships using the information provided within the Composite Key itself. In this particular example, the company_id references a Company entity which looks as follows:

@Entity(name = "Company")
@Table(name = "company")
public class Company {
 
    @Id
    private Long id;
 
    private String name;
 
    public Long getId() {
        return id;
    }
 
    public void setId(Long id) {
        this.id = id;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof Company)) return false;
        Company company = (Company) o;
        return Objects.equals(getName(), company.getName());
    }
 
    @Override
    public int hashCode() {
        return Objects.hash(getName());
    }
}

We can have the Composite Key mapping referencing the Company entity within the Employee entity:

@Entity(name = "Employee")
@Table(name = "employee")
public class Employee {
 
    @EmbeddedId
    private EmployeeId id;
 
    private String name;
 
    @ManyToOne
    @JoinColumn(name = "company_id",insertable = false, updatable = false)
    private Company company;
 
    public EmployeeId getId() {
        return id;
    }
 
    public void setId(EmployeeId id) {
        this.id = id;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
}

Notice that the @ManyToOne association instructs Hibernate to ignore inserts and updates issued on this mapping since the company_idis controlled by the @EmbeddedId.

 

Mapping a relationships inside @Embeddable

But that’s not all. We can even move the @ManyToOne inside the @Embeddable itself:

@Embeddable
public class EmployeeId implements Serializable {
 
    @ManyToOne
    @JoinColumn(name = "company_id")
    private Company company;
 
    @Column(name = "employee_number")
    private Long employeeNumber;
 
    public EmployeeId() {
    }
 
    public EmployeeId(Company company, Long employeeId) {
        this.company = company;
        this.employeeNumber = employeeId;
    }
 
    public Company getCompany() {
        return company;
    }
 
    public Long getEmployeeNumber() {
        return employeeNumber;
    }
 
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (!(o instanceof EmployeeId)) return false;
        EmployeeId that = (EmployeeId) o;
        return Objects.equals(getCompany(), that.getCompany()) &&
                Objects.equals(getEmployeeNumber(), that.getEmployeeNumber());
    }
 
    @Override
    public int hashCode() {
        return Objects.hash(getCompany(), getEmployeeNumber());
    }
}

Now, the Employee mapping will no longer require the extra @ManyToOne association since it’s offered by the entity identifier:

@Entity(name = "Employee")
@Table(name = "employee")
public class Employee {
 
    @EmbeddedId
    private EmployeeId id;
 
    private String name;
 
    public EmployeeId getId() {
        return id;
    }
 
    public void setId(EmployeeId id) {
        this.id = id;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
}

The persistence logic changes as follows:

Company company = doInJPA(entityManager -> {
    Company _company = new Company();
    _company.setId(1L);
    _company.setName("vladmihalcea.com");
    entityManager.persist(_company);
    return _company;
});
 
doInJPA(entityManager -> {
    Employee employee = new Employee();
    employee.setId(new EmployeeId(company, 100L));
    employee.setName("Vlad Mihalcea");
    entityManager.persist(employee);
});
 
doInJPA(entityManager -> {
    Employee employee = entityManager.find(
        Employee.class,
        new EmployeeId(company, 100L)
    );
    Phone phone = new Phone();
    phone.setEmployee(employee);
    phone.setNumber("012-345-6789");
    entityManager.persist(phone);
});
 
doInJPA(entityManager -> {
    Phone phone = entityManager.find(Phone.class, "012-345-6789");
    assertNotNull(phone);
    assertEquals(new EmployeeId(company, 100L), phone.getEmployee().getId());
});

Conclusion

Knowing how to map a Composite Key with JPA and Hibernate is very important because this is the way you’d map a many-to-many association.

As demonstrated in this blog post, such a mapping is not complicated at all.

WeCanCode-Author

WeCanCode-Author

August 05, 2021

Java & C#.NET Developer with 10++ years of IT experience.

Planning to learn ReactJS or Angular or Flutter.!

Load BLOB images from SQL and display in JSP page using Java Servlet

Load BLOB images from SQL and display in JSP page using Java Servlet

In this article let discuss on

Load BLOB images from SQL and display in JSP page using Java Servlet

we will guide you how to write code for displaying images stored in database on a JSP page within Java web application. Suppose that the images are stored in the database in BLOB format (Binary Large Object), and your application needs to display the images on web pages without saving the images somewhere on the server’s disk.

Generally, here are the key steps to implement:

  1. Retrieve the image data from the database as an array of bytes, by using JDBC. If you are using Hibernate, this can be done transparently by the framework.
  2. Encode the image’s binary data to String representation in Base64 format.
  3. Display the image on a JSP page using <IMG> tag with image source is the base64 string.

Now, let’s see how to integrate these steps into a typical request-response workflow of a Java web application based on Servlet and JSP. The database we use for the example is MySQL.

Lets see how to integrate request-response of  a Java web application using Servlet and JSP.

The database we use for the example is MySQL.

1. The Database

Suppose that we have a table named user_tbl that has a column called image which is of type LONGBLOB (this type can store files up to 4GB):

user_tbl blob jdbc 

So our ultimate goal is to retrieve image data from this column and display the image on a web page.

2. The Java Model Class

Java model class for the table needs to have a field to store the base64 string representation of the image.

For example:

package live.wecancode.blobdemo;

public class User {

private String username;
private String email;
private String profileImg;

public String getProfileImg() {
return profileImg;
}

public void setProfileImg(String profileImg) {
this.profileImg= profileImg;
}
// other fields...  getters and setters…
}

The field’s setter setProfileImg() will be called by a DAO class that retrieves the image binary data and converts it to a base64 string.

The field’s getter getProfile() will be called by a JSTL tag in the JSP page in order to show the image.

If you are using Hibernate, the profileImg column must be mapped similar to the below sample code.

For example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
package live.wecancode.blobdemo;
 
public class User {
 
private String username;
private String email;
private String profileImg;
private byte[] image;   
 
@Column(name="image")
public byte[] getImage() {
return this.image;
}
    public String getProfileImg() {
return profileImg;
}
 
public void setProfileImg(String profileImg) {
this.profileImg= profileImg;
}
// other fields...  getters and setters…
}

3. The DAO Class

In the DAO class, we write some additional code for retrieving the image’s binary data and converting it to a base64 string. Given a ResultSet object named result, the following code reads the image column into a byte array, and then converts it to a String in base64 format:

Blob blob = result.getBlob("image");

InputStream inputStream = blob.getBinaryStream();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int bytesRead = -1;

while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}

byte[] imageBytes = outputStream.toByteArray();

String base64Image = Base64.getEncoder().encodeToString(imageBytes);

inputStream.close();
outputStream.close();

The Base64 class can be found in the java.util package.

And the following is sample code of a DAO class – UserDAO:

package live.wecancode.blobdemo.dao;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Base64;

public class UserDAO {
String databaseURL = "jdbc:mysql://localhost:3306/userdb";
String user = "root";
String password = "pass";

public User get(int id) throws SQLException, IOException {
User user = null;

String sql = "SELECT * FROM user_tbl WHERE user_id = ?";

try (Connection connection = DriverManager.getConnection(databaseURL, user, password)) {
PreparedStatement statement = connection.prepareStatement(sql);
statement.setInt(1, id);
ResultSet result = statement.executeQuery();

if (result.next()) {
user = new User();
String username = result.getString("username");
String email = result.getString("email");
Blob blob = result.getBlob("image");

InputStream inputStream = blob.getBinaryStream();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int bytesRead = -1;

while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}

byte[] imageBytes = outputStream.toByteArray();
String base64Image = Base64.getEncoder().encodeToString(imageBytes);

inputStream.close();
outputStream.close();

user.setUsername(username);
book.setEmail(email);
book.setProfileImg(base64Image);
}

} catch (SQLException | IOException ex) {
ex.printStackTrace();
throw ex;
}

return user;
}
}

As you can see, the get(int id) method finds a row in the user_tbl table that associates with the specified id. If the row is found, a new User object is created and populated its information: such as username, email and profileImg.

4. The Servlet Class

In the Servlet class, it receives request from the user with the specified userID, then it calls the DAO to retrieve the User object, which is then stored as a request attribute. Finally the servlet forwards the processing to a destination JSP page.

Here is sample code of the servlet class:

package live.wecancode.blobdemo.servlets;

import java.io.IOException;
import java.sql.SQLException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/viewuser")
public class GetUserServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

public GetUserServlet() {
super();
}

protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
int userId = Integer.parseInt(request.getParameter("id"));
UserDAO dao = new UserDAO();

try {
User user = dao.get(userId);

request.setAttribute("user", user);

String page = "/index.jsp";
RequestDispatcher requestDispatcher = request.getRequestDispatcher(page);
requestDispatcher.forward(request, response);
} catch (SQLException ex) {
throw new ServletException(ex);
}

}
}

5. Display Image in the JSP Page

To display the image represented by a base64 String, use the <IMG> tag with the following syntax:

For PNG image type:

<img src=”data:image/png;base64,[base_64_String_goes_here]” />

For JPG/JPEG image type:

<img src=”data:image/jpg;base64,[base_64_String_goes_here]” />

And here is code of a sample JSP page that uses JSTL tags mixed with HTML tags:

<!--  userdetail.jsp -->
&lt;%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %&gt;
&lt;%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%&gt;

</pre>
<h2><c:out value="${user.username}"></c:out></h2>
<h3><c:out value="${user.email}"></c:out></h3>
<img src="data:;base64,${user.profileImg}" width="240" height="300" />
<!-- Use this if the image type is PNG

<img src="data:image/png;base64,${user.profileImg}" width="240" height="300"/>

-->
<pre>

6. Test Image Display

Suppose that the user_tbl table contains some rows with image data. To test if the image gets displayed in the JSP page or not, call the Java Servlet by typing the following URL in a web browser:

http://localhost:8080/Userdetail/viewuser?id=1

WeCanCode-Author

WeCanCode-Author

August 05, 2021

Java & C#.NET Developer with 10++ years of IT experience.

Planning to learn ReactJS or Angular or Flutter.!

Difference between Entity vs Model

Difference between Entity vs Model

Difference between Entity vs Model

Entity: An entity represents a single instance of your domain object saved into the database as a record. It has some attributes that we represent as columns in our tables.

Model: A model typically represents a real world object that is related to the problem or domain space. In programming, we create classes to represent objects. These classes, known as models, have some properties and methods (defining objects behaviour).

ViewModel: The term ViewModel originates from the MVVM (Model View ViewModel) design pattern. There are instances in which the data to be rendered by the view comes from two different objects. In such scenarios, we create a model class which consists of all properties required by the view. It’s not a domain model but a ViewModel because, a specific view uses it. Also, it doesn’t represent a real world object.

DataModel: In order to solve a problem, objects interact with each other. Some objects share a relationship among them and consequently, form a data model that represents the objects and the relationship between them.

In an application managing customer orders, for instance, if we have a customer and order object then these objects share a many to many relationship between them. The data model is eventually dependent on the way our objects interact with each other. In a database, we see the data model as a network of tables referring to some other tables.

 

Pro Tip:

In any programming language always hide your entity object to the client. use model and mapper to share the object to the client.

WeCanCode-Author

WeCanCode-Author

August 05, 2021

Java & C#.NET Developer with 10++ years of IT experience.

Planning to learn ReactJS or Angular or Flutter.!

Python Classes – Objects – Modules & Functions

Python Classes – Objects – Modules & Functions

Python Classes – Objects – Modules & Functions

Let us see Python Classes, Objects, Modules and Functions

  1. Classes and Objects
  2. Modules
  3. Functions

Watch on YouTube: https://youtu.be/YUz1XDbJDlI

Learn Python in Tamil | பைதான் மொழியைக் கற்றுக்கொள்ளுங்கள் – Python type casting and operators.

Classes & Objects

Python is an object-oriented programming language. Almost everything in Python is an object, with its properties and methods. A Class is like an object constructor, or a “blueprint” for creating objects.

Creating Class

class MyClass:
    empid = 1001
    empname = "John"

Creating object for the class

obj1 = MyClass()
print(obj1.empid)
print(obj1.empname) 

The __init__() Function

This is kind of Python’s standard initialize method which is invoked during object creation of the class. consider you want to pre-initialize the properties of the class ahead of object creation, then you need to use this method.

class Student:
    def __init__(self, sid, name, age):
        self.sid = sid
        self.name = name
        self.age = age

# -------------------------------------------

student1 = Student(100,"Bob", 22)
print(student1.sid)
print(student1.name)
print(student1.age)

In the above class we have “init” method which gets initialized along with the constructor while creating an object and we have self as our first parameter, which is used for identifying the current/own object.

Note: The \__init\__() function is called automatically every time the class is being used to create a new object.

The self Parameter

The self parameter is a reference to the current instance of the class, and is used to access variables that belongs to the class and It doesn’t need to be named like “self”.

We can call it whatever we want, but it should be the first parameter of any function in the class, see below example..

class Car:
    def __init__(myownobjectref, carid, carmake):
        myownobjectref.carid = carid
        myownobjectref.carmake = carmake

Note: In the above example we have used myownobjectref as first parameter and it refers the current object of Car class.

Modify object properties

class Student:
    def __init__(self, sid, name, age):
        self.sid = sid
        self.name = name

# -------------------------------------------

student1 = Student(100,"Bob")
student1.sid = 101

Delete object properties

class Student:
    def __init__(self, sid, name, age):
        self.sid = sid
        self.name = name

# -------------------------------------------

student1 = Student(100,"Bob")
del student1.sid

Delete object

class Student:
    def __init__(self, sid, name, age):
        self.sid = sid
        self.name = name

# -------------------------------------------

student1 = Student(100,"Bob")
del student1

Modules

Python Modules

Python modules are .py files that consist of Python code. Any Python file can be referenced as a module.

Some modules are available through the Python Standard Library and are therefore installed with your Python installation. Others can be installed with Python’s package manager pip. Additionally, you can create your own Python modules since modules are comprised of Python .py files.

Writing and Importing Modules

Writing Modules

Writing a module is just like writing any other Python file. Modules can contain definitions of functions, classes, and variables that can then be utilized in other Python programs.

From our Python 3 local programming environment or server-based programming environment, let’s start by creating a file hello.py that we’ll later import into another file.

To begin, we’ll create a function that prints Hello, World!:

# math_operations.py (Located under my-own-modules directory)

# Maths Operation

def add(a, b):
    print(a + b)

If we run the program on the command line with python math_operations.py nothing will happen since we have not invoked the functions add.

Importing Modules

Let’s create a second file called main_program.py so that we can import the module we just created, and then call the function.

main_program.py
# Import math_operations module - which is nothing but the math_operations.py file
import math_operations


# Call function
math_operation.add(1, 2)

Because we are importing a module, we need to call the function by referencing the module name in DOT " . " notation.

We could instead import the module as from hello import world and call the function directly as world(). You can learn more about this method by reading how to using from … import when importing modules.

Functions

Python Functions

Python functions are written inside .py files which performs the instruction or action written in Python. each method/function performs set of instruction or operations we wanted to perform. like adding two numbers, checking if the user is admin or not etc.,

Creating Function

In order to create python functions/methods you need to use def key word prefixed. lets see the below example.

# functions.py
# def -> key word tells us this is a method.
# display_app_name(): this is our method name with no parameters, because with in the brackets we have not passes any variable.
def display_app_name():
    print("My App Name")

Calling Function

Calling a medhod in Python is easy, just need to use the method name with the brackets. (If method has any parameters, we need to just pass it inside the brackets.)

# calling the function
display_app_name()

Returning data from Function

# functions.py
def get_current_username(user):
    return user["name"]

userobj = {
    "name": "John",
    "id": 100}

print(get_current_username(userobj))

Calling function inside another function.

# functions.py
def is_admin(user_param):
    return user_param["admin"]

def append_usertype(old_user_id, user_type):
    return f"{old_user_id}_{user_type}"


def regenerate_userid(user_param):
    new_userid = user_param["id"]
    if is_admin(user_param):
        new_userid = append_usertype(new_userid,"ADM")
    else:
        new_userid = append_usertype(new_userid,"USR")

    user_param["id"] = new_userid
    return user_param

#-----------------------------------------

user = {
    "name": "John",
    "id": 100,
    "admin": False
}
print(user)
print(regenerate_userid(user))
Python decision making & loops – Learn Python in Tamil www.aryanz.co.in

Python Decision making and Loops

Python Decision making and Loops

Python Decision making and Loops

Let us see about Python decision making and loops

  1. Decision making
  2. Loops

Watch on YouTube: https://youtu.be/A2qoypUV-ZE

Learn Python in Tamil | பைதான் மொழியைக் கற்றுக்கொள்ளுங்கள் – Python type casting and operators.

Decision making

Decision making evaluates multiple expressions which produce TRUE or FALSE as an outcome.

Which defines action to take and what statements has to execute when the outcome is TRUE or FALSE otherwise.

Note: Python programming language assumes any non-zero and non-null values as TRUE, and if it is either zero or null, then it is assumed as FALSE value

Decision making statements are as follows:

  1. If statement
  2. If-else statement
  3. Nested if statement

If Statement

# if statement

# When you want to check some logical condition and perform actions based on positive result.

x = 8
y = 10

if x > y:
    print("X is greater")
    print(f"{x}")

print("Program ended")

If-else statement

# if-else statement

# An if statement can be followed by an optional else statement, which executes when the boolean expression is FALSE.

x = 80
y = 10

if x > y:
    print("X is greater")
else:
    print("Y is greater")

print("Program Ended")

Nested if-else statement

# nested/multiple if-else statement

# When you want to check multiple conditions and perform actions based on the result (TRUE or FALSE).

x = 80
y = 10
z = 90

# Multiple if

if x > y:
    print("X is greater")
elif x > z:
    print("X is greater")
elif y > z:
    print("Y is greater")
else:
    print("Z is greater")

# Nested If

if x > y:
    if x > z:
        print("x is greater")
    else:
        print("z is greater")
elif y > z:
    print("y is greater")
else:
    print("z is greater")

print("Program Ended")

Loops

A loop statement allows us to execute a statement or group of statements multiple times.

Along with above loops, we also have the following 3 keywords used during Loops.

  1. Break
  2. Continue
  3. Pass

While loop

# While loop repeatedly executes a target statement as long as a given condition becomes true.

# Example 1 (Simple while loop)
count = 1

while count < 4:
    print(count)
    count = count + 1

print("Out of while loop")
print("------------------------------")

# Example 2 : Using else Statement with While Loop

count = 0
while count < 4:
    print(count)
    count = count + 1
else:
    print("count is less than 4")

For loop

# For loop
# it has the ability to iterate over the items of any sequence,
# such as a list or a string.

# We can iterate Collection items
# Such as List, Tuple, Set and so on.

# Example 1 : looping list
blog_websites = ["aryanz.co.in", "balamt.in", "wecancode.live"]

for x in blog_websites:
    print(x)


# Example 2 : looping string value
name = "John"
for letter in name:
    print(letter)


# Example 3: Using else in For loop

for i in range(1,4):
    print(i)
else:
    print(f"Reached the max range")

Nested loop

# Nested loop
# looping inside another loop is called nested loop

# What is the output of the following code? - Comment your answer here > https://youtu.be/A2qoypUV-ZE

for x in range(1, 5):
    for y in range(x-1, x): # 1, 4
        print(f"{y}")
    print(f"\t")
Python decision making & loops - Learn Python in Tamil www.aryanz.co.in
Python decision making & loops – Learn Python in Tamil www.aryanz.co.in

Please disable your adblocker or whitelist this site! We Provide Free content and in return, all we ask is to allow serving Ads.

Pin It on Pinterest