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.!

JDBC Clob datatype, store and read data with java

What is JDBC Clob data type? how to store and read data from it? 

CLOB stands for Character Large Object in general.

SQL Clob is a built-in datatype and is used to store huge amount of characters data. Using this datatype, you can store data up to 2,147,483,647 characters.

The java.sql.Clob interface of the JDBC API represents the CLOB datatype. Since the Clob object in JDBC is implemented using an SQL locator, it holds a logical pointer to the SQL CLOB (not the data).

MYSQL database provides support for this datatype using four variables.

  • TINYTEXT: A CLOB type with a maximum of 28-1 (255) characters.
  • TEXT: A CLOB type with a maximum of 216-1 (65535) characters.
  • MEDIUMTEXT: A CLOB type with a maximum of 224-1 (16777215) characters.
  • LONGTEXT: A CLOB type with a maximum of 232-1 (4294967295 ) characters.

Storing Clob datatype in to table in a database

To store Clob datatype to database, using JDBC program follow the steps given below

Step 1: Connect to the database

You can connect to a database using the getConnection() method of the DriverManager class.

Connect to the MySQL database by passing the MySQL URL which is jdbc:mysql://localhost/sampleDB (where sampleDB is the database name), username and password as parameters to the getConnection() method.

String mysqlUrl = "jdbc:mysql://localhost/sampleDB";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
Step 2: Create a Prepared statement

Create a PreparedStatement object using the prepareStatement() method of the Connection interface. To this method pass the insert query (with place holders) as a parameter.

PreparedStatement pstmt = con.prepareStatement("INSERT INTO Technologies(Name,
Type, Article ) VALUES (?, ?, ?)");
Step 3: Set values to the place holders

Set the values to the place holders using the setter methods of the PreparedStatement interface. Chose the methods according to the datatype of the column. For Example if the column is of VARCHAR type use setString() method and if it is of INT type you can use setInt() method.

And if it is of Clob type you can set value to it using the setCharacterStream() or setClob() methods. To these methods pass an integer variable representing the parameter index and an object of the Reader class as parameters.

pstmt.setString(1, "JavaFX");
pstmt.setString(2, "Java Library");
FileReader reader = new FileReader("E:\\images\\javafx.txt");
pstmt.setClob(3, reader);
pstmt.execute();
Step 4: Execute the statement

Execute the above created PreparedStatement object using the execute() method of the PreparedStatement interface.

Retrieving blob from database

The getClob() method of the ResultSet interface accepts an integer representing the index of the column (or, a String value representing the name of the column) and retrieves the value at the specified column and returns it in the form of a Clob object.

while(rs.next()) {
   System.out.println(rs.getString("Name"));
   System.out.println(rs.getString("Type"));
   Clob clob = rs.getClob("Article");
}

The getCharacterStream() method of the Clob Interface retrieves the contents of the current Clob object and returns as a Reader object.

Using the getClob() method you can get the contents of the Clob as a Reader object and create text file with the retrieved contents, using the write() method of the FileOutputStream object.

Reader r = clob.getCharacterStream();
char cbuf[] = new char[r.read()];
r.read(cbuf);
FileOutputStream outPutStream = new
FileOutputStream("E:\\images\\clob_output"+i+".txt");
outPutStream.write(cbuf.toString().getBytes());
Example : Creates table with Clob field | Inserts large text data from a file to it. Retrieves the text back and stores it in another text file.
import java.io.FileReader;
import java.io.FileWriter;
import java.io.Reader;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
public class ClobExample {
   public static void main(String args[]) throws Exception {
      //Registering the Driver
      DriverManager.registerDriver(new com.mysql.jdbc.Driver());
      //Getting the connection
      String mysqlUrl = "jdbc:mysql://localhost/sampleDB";
      Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
      System.out.println("Connection established......");
      //Creating a table
      Statement stmt = con.createStatement();
      stmt.execute("CREATE TABLE Technologies( Name VARCHAR(255), Type VARCHAR(255), Article LONGTEXT)");
      System.out.println("Table Created......");

      //Inserting values
      String query = "INSERT INTO Technologies(Name, Type, Article ) VALUES (?, ?, ?)";
      PreparedStatement pstmt = con.prepareStatement(query);
      pstmt.setString(1, "JavaFX");
      pstmt.setString(2, "Java Library");
      FileReader reader = new FileReader("E:\\images\\javafx.txt");
      pstmt.setClob(3, reader);
      pstmt.execute();
      pstmt.setString(1, "CoffeeScript");
      pstmt.setString(2, "Scripting Language");
      reader = new FileReader("E:\\images\\coffeescript.txt");
      pstmt.setClob(3, reader);
      pstmt.execute();
      pstmt.setString(1, "Cassandra");
      pstmt.setString(2, "NoSQL Database");
      reader = new FileReader("E:\\images\\cassandra.txt");
      pstmt.setClob(3, reader);
      pstmt.execute();
      //Retrieving the data
      ResultSet rs = stmt.executeQuery("select * from Technologies");
      int j = 0;
      System.out.println("Contents of the table are: ");
      while(rs.next()) {
         System.out.println(rs.getString("Name"));
         Clob clob = rs.getClob("Article");
         Reader r = clob.getCharacterStream();
         String filePath = "E:\\Data\\clob_output"+j+".txt";
         FileWriter writer = new FileWriter(filePath);
         int i;
         while ((i=r.read())!=-1) {
            writer.write(i);
         }
         writer.close();
         System.out.println(filePath);
         j++;
      }
   }
}
wecancode-founder

wecancode-founder

August 04, 2021

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

Planning to learn ReactJS or Angular or Flutter.!

Java 8: Streams – Part 1

What is Streams?

Stream is a new abstract layer introduced in Java 8, It represents a sequence of objects from a source, which supports aggregate operations.

To understand better, lets take basic sql function distinct.

SELECT DISTINCT(USER_TYPE_ FROM [MYSCHEMA].[USER];

In the above SQL script, we perform Distinct operation using the DISTINCT method. which actually performs operation on the retrived data/rows.

Similarly Java8:Streams also performs operation or action on collective data.

Follow are the characteristic of Java8:Streams

  • Sequence of elements − Stream provides a set of elements of specific type in a sequential manner. A stream gets/computes/manipulated the elements/data. It never stores the manipulated elements/data.
  • Source − Stream accepts Collections, Arrays, or I/O resources as input source.
  • Aggregate operations − Stream supports aggregate operations such as filter, map, limit, reduce, find, match, & so on.
  • Pipelining − Most of the stream operations return stream itself so that their result can be pipelined. These operations are called intermediate operations and their function is to take input, process them, and return output to the target. collect() method is a terminal operation which is normally present at the end of the pipelining operation to mark the end of the stream.
  • Automatic iterations − Stream operations do the iterations internally over the source elements provided, in contrast to Collections where explicit iteration is required.

Lets continure in the next part..

Java Programming: Why do we have main method ? can this method name be changed ?

Java Programming: Why do we have main method ? can this method name be changed ?

I was wondering always, why it is always main method is the starting point for the Java program.

Well When i was matured enough to read the Java Specification i learnt why and whether can it be changed ? Okay Lets See !!

Why main method ?

Main method is the starting point for the java program, JVM initialize the class and invokes main method, having below listed specifications (reference 12.1.4). 

  • Should be named as main 
  • Should be public 
  • Should be static 
  • Should accept String array as argument. 
  • Return type is void 

As based on the above specification, we can conclude that we cannot rename the main method. 

Some Additional Info.!

public static void main(String[] args)  // this is valid

public static void main(String… args)  //String…  this is also valid where it is available from the java 5

public static void main(String args[]) //This is valid but not recommended because the array brackets in the variable)

String Java Program: Palindrome

String Java Program: Palindrome

Interview Questions

Refer this for preparing yourself on how to write java program to check given string is a Palindrome or not.

Palindrome

public class PalindromeApp {
	public static void main(String[] args) {
		String input = "dad";
		if (PalindromeApp.isPalindrome(input)) {
			System.out.println(String.format("%s is palindrome", input));
		} else {
			System.out.println(String.format("%s is NOT palindrome", input));
		}
	}

	private static Boolean isPalindrome(String input) {
		char[] inputArr = input.toLowerCase().toCharArray();
		char[] reverse = new char[inputArr.length];

		for (int i = 0; i < inputArr.length; i++) {
			reverse[i] = inputArr[(inputArr.length - 1) - i];
		}
		String r = new String(reverse); // String.copyValueOf(reverse);
		return (input.equals(r));
	}
}

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