Insert File Into MySQL Database In Java

Sometimes we have a requirement to insert file into database rather then storing it in the file system. For a developer, it is always hard to decide this. You can find good discussion in different forums on web over storing the file either in database or file system. I believe choosing the same depends on the project requirement rather than preferences. You can choose database over file system when file size is small and user’s file needs to be more tightly coupled, secured and confidential. Since this discussion is out of scope of this article, here is a good resource,&nbsp;<a href="https://habiletechnologies.com/blog/better-saving-files-database-file-system/" target="_blank">Which is Better ? Saving Files in Database or File System</a>&nbsp;for your reference.

Introduction

Sometimes we have a requirement to insert file into database rather then storing it in the file system. For a developer, it is always hard to decide this. You can find good discussion in different forums on web over storing the file either in database or file system. I believe choosing the same depends on the project requirement rather than preferences. You can choose database over file system when file size is small and user’s file needs to be more tightly coupled, secured and confidential. Since this discussion is out of scope of this article, here is a good resource, Which is Better ? Saving Files in Database or File System for your reference.

Well, today we will see how to insert image file into MySQL database using JDBC. We will use BLOB datatype of MySQL for storing files....

( Read More )

JPA with Eclipse and MySQL: Using Java Configuration

JPA with Eclipse and MySQL: Using Java Configuration

In this tutorial, we learn more about the Java Persistence API and how to effectively configure it with EclipseLink and MySQL.

The** Java Persistence API** is a standard specification for ORM (Object Relational Mapping) implementations. Also, it shows how to define a PLAIN OLD JAVA OBJECT (POJO) as an entity and how to manage entities with relations.

Key JPA Entities

**1.) **<strong>EntityManagerFactory</strong>: This is a factory class of EntityManager. It creates and manages multiple EntityManager instances.

**2.) **<strong>EntityManger</strong>: This interface manages the persistence operations on entities.

**3.) **<strong>Entity</strong>: Entities are the persistence objects, stores as records in the database.

**4.) **<strong>EntityTransaction</strong>: It has a one-to-one relationship with EntityManager. For each EntityManager, operations are maintained by EntityTransaction class.

**5.) **<strong>Persistence</strong>: This class contains static methods used to obtain a EntityManagerFactory instance.

**6.) **<strong>Query</strong>: This interface is implemented by each JPA vendor to obtain relational objects that meet the criteria.

Now, let us start our JPA implementations with an example:

Required Maven dependencies:

<dependencies>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>eclipselink</artifactId>
<version>2.7.4</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.40</version>
</dependency>
</dependencies>

Here, to achieve persistence in the application, we need to introduce the persistence.xml, which has to be located in the META-INF directory in the project classpath.

persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1"
xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="JPATest"
transaction-type="RESOURCE_LOCAL">
<class><!-- Entity Class Name --></class>
</persistence-unit>
</persistence>

Here, the persistence unit name must be unique. Also, we can add multiple persistence-units for different units. The transaction type for this persistence unit is RESOURCE_LOCAL.

There are two types of transactions:

  • JTA: The transactions will be managed by the Application Server
  • RESOURCE_LOCAL: The transaction will be managed by the JPA Provider Implementation in use.

Also, specify the class name for entities in this configuration file. There is one more configuration used for the database connection. But for dynamic configuration of database connection, we add that configuration in Java code instead of this XML file.

EntityManager:

public class JpaEntityManager {
private EntityManagerFactory emFactoryObj;
private final String PERSISTENCE_UNIT_NAME = "JPATest";
private final Map<String, String> properties=new HashMap<String, String>();


// This Method Is Used To Retrieve The 'EntityManager' Object
public EntityManager getEntityManager() {

String url = String.format("%s/%s", DBConstants.DB_HOST, DBConstants.DB_NAME);

properties.put("javax.persistence.jdbc.driver",DBConstants.DB_DRIVER);
properties.put("javax.persistence.jdbc.url", url);
properties.put("javax.persistence.jdbc.user", DBConstants.DB_USER);
properties.put("javax.persistence.jdbc.password",DBConstants.DB_PASSWORD);
properties.put("useSSL", DBConstants.DB_USE_SSL);
properties.put("requireSSL", DBConstants.DB_REQUIRED_SSL);
properties.put("serverTimezone",DBConstants.DB_SERVER_TIMEZONE);

emFactoryObj = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME,properties);

return emFactoryObj.createEntityManager();
}
}

Here, you have to add your database related configuration like drive class name, hostname, database name, username, password, etc.

Database schema:

CREATE TABLE user (
  id INTEGER NOT NULL,
  name VARCHAR(255) NOT NULL,  
  age VARCHAR(100) NOT NULL,
  PRIMARY KEY(id)
);

Entity:

Here are some annotations used for JPA implementation.

1.) @Entity: to mark the java class as an entity.

2.) @Table: to specify the table to which this entity class maps.

3.) @Id: to identify a row uniquely (JPA Primary Key).

4.) @Column: to specify the mapped column for a persistent property or field.

**5. **<strong>JPARepository</strong>: used to perform database-related operations.

public class JpaRepository<T, ID> implements AutoCloseable {

private final Class<T> typeParameterClass;
protected EntityManager entityManager;

public JpaRepository(Class<T> typeParameterClass) {
JpaEntityManager dbEntityManager = new JpaEntityManager();
entityManager = dbEntityManager.getEntityManager();
this.typeParameterClass = typeParameterClass;
}
/**
 * Save an entity.
 * @param entity
 * @return the saved entity
 */
public <S extends T> S save(S entity) {
entityManager.getTransaction().begin();
entityManager.persist(entity);
entityManager.getTransaction().commit();
return entity;
}
/**
 * merge an entity.
 *
 * @param entity
 * @return the saved entity
 */
public <S extends T> S merge(S entity) {
entityManager.getTransaction().begin();
entityManager.merge(entity);
entityManager.getTransaction().commit();
return entity;
}
/**
 * Delete an entity
 * 
 * @param id
 */
public void delete(ID id) {
entityManager.remove(id);
}
/**
 * Returns a reference to the entity with the given identifier.
 * 
 * @param id
 * @return
 */
public T findById(ID id) {
T t = entityManager.find(typeParameterClass, id);
return t;
}
/**
 * get single result
 * 
 * @param q
 * @return
 */
public Optional<T> getSingleResult(CriteriaQuery<T> q) {

try {
return Optional.ofNullable(entityManager.createQuery(q).getSingleResult());
} catch (RuntimeException e) {
return Optional.empty();
}
}
/**
 * get single result
 * 
 * @param q
 * @return
 */
public Optional<List<T>> getResultList(CriteriaQuery<T> q) {
try {
return Optional.ofNullable(entityManager.createQuery(q).getResultList());
} catch (RuntimeException e) {
return Optional.empty();
}
}
/**
 * used to close entity manager obj
 */
public void close() {
entityManager.clear();
entityManager.close();
}
}

You can also use JPA Criteria API queries, which provide an alternative way for defining JPA queries and is mainly useful for building dynamic queries whose exact structure is only known at runtime.

Now, all configuration is done. So, let us start to test this application.

public class JPADemo {

public static void main(String[] args) {
User user=new User();
user.setId(1);
user.setAge(20);
user.setName("Abc");

try(JpaRepository userJpaRepository=new JpaRepository<BlenderMaster, Long>(BlenderMaster.class)){
userJpaRepository.save(user);
}catch (Exception e) {
e.printStackTrace();
}
}
}

Here, we added the JPA Repository resource in a try catch, so resource will be closed automatically after use. After running this application, one new user entry will be added in the MySQL database.

Thanks For Visiting, Keep Visiting. If you liked this post, share it with all of your programming buddies!

Further reading

Java Programming Masterclass for Software Developers

JSP, Servlets and JDBC for Beginners: Build a Database App

Java 8 New Features In Simple Way

Java In-Depth: Become a Complete Java Engineer!

Java for Absolute Beginners

Java Programming for Complete Beginners - Learn in 250 Steps

Learn Java Programming Crash Course

Apache Spark for Java Developers

Database Caching With Redis and Java

Database Caching With Redis and Java

Explore database caching with Redis and Java and see some of the different caching strategies.

Explore database caching with Redis and Java and see some of the different caching strategies.

Why Is Database Caching so Important?

The more information you have in a database, the slower it will become over time. Even database management systems that are well-designed to support many concurrent requests will eventually hit their limit.

Database caching is one of the most common strategies for dealing with these performance issues. Caching involves saving the results of database queries in a location that is faster and easier to access. When done correctly, caching will slash query response times, decrease the load on your databases, and cut costs.

However, caches also need to be handled with care because they essentially make another copy of your information in a separate location. Keeping both the database and the cache synchronized and up-to-date can be a trickier challenge than you anticipated. In the next section, we’ll discuss some of the most common database caching strategies.

What Are the Different Caching Strategies?

Manual caching (also known as a cache-aside strategy) involves direct management of both the database and the cache. Your application inspects the cache before launching a database query, and it updates the cache after any changes to the database.

While effective if implemented correctly, manual caching can be extremely tedious, especially if you need to query more than one database. For these reasons, developers have invented a number of alternative caching strategies.

Read-Through Caching Strategy

In read-through caching, the application first queries the cache to see if the information it needs is inside. If not, it retrieves the information from the database and uses it to update the cache. The cache provider or cache library is responsible for the detailed logic of querying and updating the cache.

The read-through strategy works best for read-heavy workloads when the application requests the same data repeatedly: for example, a news website that loads the same articles over and over.

One downside of the read-through strategy is that the first query to the cache will always result in a miss because the requested information is guaranteed not to be inside. To deal with this issue, developers often “warm” the cache ahead of time with information that users are likely to request.

Write-Through Caching Strategy

In write-through caching, updates are made to the cache first and to the database second. There is a direct line from the application to the cache and from the cache to the database. When combined with read-through caching, a write-through strategy guarantees that your data will be consistent, removing the need for manual cache invalidation.

Write-Behind Caching Strategy

In write-behind caching (also known as write-back caching), the application first writes data to the cache. After a set period of delay, the cache writes this information to the database as well. Write-behind caches are best for write-heavy workloads and can perform well even with some failures and downtime.

Java-Based Redis Caching With Redisson

Redis is one of the most popular options for NoSQL databases, using a key-value system to store data. Redisson, a client library for Redis in the Java programming language, makes it easy to access Redis features using all the familiar Java collections.

Redisson allows you to place data in Maps in external storage. You can use this functionality to implement caching for databases, web services, or any other data source.

Read-Through Caching in Redis

Below is a Java example of how to use read-through caching in Redis with Redisson.

If the requested entry doesn’t exist in the cache, it will be loaded by MapLoader object:

MapLoader<String, String> mapLoader = new MapLoader<String, String>() {

    @Override
    public Iterable<String> loadAllKeys() {
        List<String> list = new ArrayList<String>();
        Statement statement = conn.createStatement();
        try {
            ResultSet result = statement.executeQuery("SELECT id FROM student");
            while (result.next()) {
                list.add(result.getString(1));
            }
        } finally {
            statement.close();
        }

        return list;
    }

    @Override
    public String load(String key) {
        PreparedStatement preparedStatement = conn.prepareStatement("SELECT name FROM student where id = ?");
        try {
            preparedStatement.setString(1, key);
            ResultSet result = preparedStatement.executeQuery();
            if (result.next()) {
                return result.getString(1);
            }
            return null;
        } finally {
            preparedStatement.close();
        }
    }
};

Configuration example:

MapLoader<String, String> mapLoader = new MapLoader<String, String>() {

    @Override
    public Iterable<String> loadAllKeys() {
        List<String> list = new ArrayList<String>();
        Statement statement = conn.createStatement();
        try {
            ResultSet result = statement.executeQuery("SELECT id FROM student");
            while (result.next()) {
                list.add(result.getString(1));
            }
        } finally {
            statement.close();
        }

        return list;
    }

    @Override
    public String load(String key) {
        PreparedStatement preparedStatement = conn.prepareStatement("SELECT name FROM student where id = ?");
        try {
            preparedStatement.setString(1, key);
            ResultSet result = preparedStatement.executeQuery();
            if (result.next()) {
                return result.getString(1);
            }
            return null;
        } finally {
            preparedStatement.close();
        }
    }
};

Write-Through Caching in Redis

Below is a Java example of how to use write-through caching in Redis in Redis with Redisson.

Cache update method will not return until both the cache and the database have been updated by MapWriter object:

MapLoader<String, String> mapLoader = new MapLoader<String, String>() {

    @Override
    public Iterable<String> loadAllKeys() {
        List<String> list = new ArrayList<String>();
        Statement statement = conn.createStatement();
        try {
            ResultSet result = statement.executeQuery("SELECT id FROM student");
            while (result.next()) {
                list.add(result.getString(1));
            }
        } finally {
            statement.close();
        }

        return list;
    }

    @Override
    public String load(String key) {
        PreparedStatement preparedStatement = conn.prepareStatement("SELECT name FROM student where id = ?");
        try {
            preparedStatement.setString(1, key);
            ResultSet result = preparedStatement.executeQuery();
            if (result.next()) {
                return result.getString(1);
            }
            return null;
        } finally {
            preparedStatement.close();
        }
    }
};

Configuration example:

MapLoader<String, String> mapLoader = new MapLoader<String, String>() {

    @Override
    public Iterable<String> loadAllKeys() {
        List<String> list = new ArrayList<String>();
        Statement statement = conn.createStatement();
        try {
            ResultSet result = statement.executeQuery("SELECT id FROM student");
            while (result.next()) {
                list.add(result.getString(1));
            }
        } finally {
            statement.close();
        }

        return list;
    }

    @Override
    public String load(String key) {
        PreparedStatement preparedStatement = conn.prepareStatement("SELECT name FROM student where id = ?");
        try {
            preparedStatement.setString(1, key);
            ResultSet result = preparedStatement.executeQuery();
            if (result.next()) {
                return result.getString(1);
            }
            return null;
        } finally {
            preparedStatement.close();
        }
    }
};

Write-Behind Caching in Redis

The MapWriter interface is also used to asynchronously commit updates to the Map object (cache) and the external storage (database). Threads amounts used in the background write operation execution sets through the writeBehindThreads setting.

Below, we see a Java example of the configuration for a Redis-based write-behind caching implementation in Redisson:

MapLoader<String, String> mapLoader = new MapLoader<String, String>() {

    @Override
    public Iterable<String> loadAllKeys() {
        List<String> list = new ArrayList<String>();
        Statement statement = conn.createStatement();
        try {
            ResultSet result = statement.executeQuery("SELECT id FROM student");
            while (result.next()) {
                list.add(result.getString(1));
            }
        } finally {
            statement.close();
        }

        return list;
    }

    @Override
    public String load(String key) {
        PreparedStatement preparedStatement = conn.prepareStatement("SELECT name FROM student where id = ?");
        try {
            preparedStatement.setString(1, key);
            ResultSet result = preparedStatement.executeQuery();
            if (result.next()) {
                return result.getString(1);
            }
            return null;
        } finally {
            preparedStatement.close();
        }
    }
};

All discussed strategies are available for the RMap, RMapCache, RLocalCachedMap, and RLocalCachedMapCache objects in Redisson. Using these latter two objects can make read operations in Redis up to 45 times faster.

MySQL Database Tutorial for Beginners to Advanced Part 1

MySQL Database Tutorial for Beginners to Advanced Part 1

Learn about MySQL Database from scratch. Go from zero to hero in MySQL Database with this complete course.

Learn about MySQL Database from scratch. Go from zero to hero in MySQL Database with this complete course.

In this course you will learn about MySQL Database from scratch. We will assume that you are a complete beginner and by the end of the course you will be at advanced level. In this complete course you shall get demonstration of every single topic that we have explained. This course is fully practical without neglecting the theories and basics.