JPA - Basic Persistable Types

[Updated: Mar 8, 2017, Created: Mar 7, 2017]

In this tutorial we will go through basic Java data types that JPA supports as persistable fields/properties of an entity class. These types are supported without any mandatory mapping annotations.

java.lang.String

It is persisted as VARCHAR(n)

Primitives and Primitives wrappers

Java primitive
primitive wrapper
Standard SQL type
boolean/java. lang. Boolean BOOLEAN
byte/java. lang. Byte SMALLINT (5)
short/java. lang. Short SMALLINT (5)
char/java. lang. Character CHARACTER (n)
int/java. lang. Integer INTEGER (10)
long/java. lang. Long BIGINT (19)
float/java. lang. Float DECIMAL (16,7)
double/java. lang. Double DECIMAL (32,15)
Example

java.math.* types

java.math Standard SQL type
java. math. Big Integer DECIMAL (n,0)
java. math. Big Decimal DECIMAL (n,p)
Example

Note that if Java type maps to a column of SQL type 'DECIMAL(n,p)', then we can control precision/scale of the resultant columns by using the annotation @Column on the target field and by setting desired values of its elements 'precision' and/or 'scale'.

java.util.Date and java.util.Calendar

Java date type Standard SQL type
java.util.Date TIMESTAMP
java. util. Calender TIMESTAMP
Example

java.sql.* date types

Java date type Standard SQL type
java.sql.Date Date
java.sql.Time TIME
java. sql. Timestamp TIMESTAMP
Example

Array of Simple types and other serializable types

Arrays of all Java primitives and primitives wrapper can be persisted without any extra configuration. Also arrays of String, java.util.Date, java.util.Calender, java.sql.Date, java.sql.Time and java.sql.Timestamp can also be persisted in the same manner. In short, any type which is serializable can be persisted. All these types are converted to SQL type VARBINARY except for char[] and Character[] which are converted to VARCHAR. VARBINARY is just like BLOB except that VARBINARY supports only limited size.

Example

As stated above that all types which are serializable can be mapped to database. That includes a user defined type that implements serializable. Here's an example.

Example

Note that most of the time it is not be desirable to serialize objects in database, that's because we will not be able to perform granular operations on the data. For example for updating a single field of a serialized object, we have to load the whole object which won't be good for performance. Also as opposed to persisting data in relational structure, serializing all objects in database will not allow the various parts of application and tools to access and use data in different ways without scarifying the productivity and performance.

See Also