Close

JPA - Mapping of Basic Java Types Examples

JPA JAVA EE 

Java primitive and primitive Wrapper

This example shows what SQL types each of Java primitive and their corresponding wrappers are mapped to. The type mapping dependents on JPA implementation and underlying database, but most of the time Java types are mapped to standard SQL type. In this examples we are using EclipseLink as JPA provider and H2 database.

package com.logicbig.example;

import javax.persistence.Entity;
import javax.persistence.Id;

@Entity
public class ExampleEntity {
@Id
private String id;

private boolean aBoolean;
private Boolean aBooleanW;

private byte aByte;
private Byte aByteWrapper;

private short aShort;
private Short aShortWrapper;

private char aChar;
private Character aCharWrapper;

private int anInt;
private Integer anIntWrapper;

private long aLong;
private Long aLongWrapper;

private float aFloat;
private Float aFloatWrapper;

private double aDouble;
private Double aDoubleWrapper;

private String aString;
}

src/main/resources/META-INF/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="testPersistenceUnit" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.schema-generation.database.action" value="create"/>
<property name="javax.persistence.jdbc.url" value="jdbc:h2:mem:test;DB_CLOSE_DELAY=-1"/>
</properties>
</persistence-unit>
</persistence>

pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.logicbig.example</groupId>
<artifactId>java-sql-conversion</artifactId>
<version>1.0-SNAPSHOT</version>

<dependencies>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.193</version>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>eclipselink</artifactId>
<version>2.6.4</version>
</dependency>

<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>javax.persistence</artifactId>
<version>2.1.1</version>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
</project>
package com.logicbig.example;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import java.util.Arrays;
import java.util.List;

public class Main {
private static final EntityManagerFactory emf =
Persistence.createEntityManagerFactory(
"testPersistenceUnit");
private static final EntityManager entityManager = emf.createEntityManager();

public static void main(String[] args) {
//this will print column name, type, can-be-NULL,
// KEY and default value respectively
runNativeQuery("SHOW COLUMNS from ExampleEntity");
}

private static void runNativeQuery(String s) {
System.out.println("--------\n" + s);
Query query = entityManager.createNativeQuery(s);
List list = query.getResultList();
for (Object o : list) {
System.out.println(Arrays.toString((Object[]) o));
}
}
}

Output

--------
SHOW COLUMNS from ExampleEntity
[ID, VARCHAR(2147483647), NO, PRI, NULL]
[ABOOLEAN, BOOLEAN(1), YES, , NULL]
[ABOOLEANW, BOOLEAN(1), YES, , NULL]
[ABYTE, SMALLINT(5), YES, , NULL]
[ABYTEWRAPPER, SMALLINT(5), YES, , NULL]
[ACHAR, CHAR(2147483647), YES, , NULL]
[ACHARWRAPPER, CHAR(2147483647), YES, , NULL]
[ADOUBLE, DOUBLE(17), YES, , NULL]
[ADOUBLEWRAPPER, DOUBLE(17), YES, , NULL]
[AFLOAT, DOUBLE(17), YES, , NULL]
[AFLOATWRAPPER, DOUBLE(17), YES, , NULL]
[ALONG, BIGINT(19), YES, , NULL]
[ALONGWRAPPER, BIGINT(19), YES, , NULL]
[ASHORT, SMALLINT(5), YES, , NULL]
[ASHORTWRAPPER, SMALLINT(5), YES, , NULL]
[ASTRING, VARCHAR(2147483647), YES, , NULL]
[ANINT, INTEGER(10), YES, , NULL]
[ANINTWRAPPER, INTEGER(10), YES, , NULL]
Original PostDownload Project Browser 




java.util.Date and java.util.Calender mapping

package com.logicbig.example;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import java.util.Calendar;
import java.util.Date;

@Entity
public class ExampleEntity {
@Id
private String id;
@Temporal(TemporalType.TIMESTAMP)
private Date date;
@Temporal(TemporalType.TIMESTAMP)
private Calendar calender;
}

Output

--------
SHOW COLUMNS from ExampleEntity
[ID, VARCHAR(2147483647), NO, PRI, NULL]
[CALENDER, TIMESTAMP(23), YES, , NULL]
[DATE, TIMESTAMP(23), YES, , NULL]
Original PostDownload Project Browser 




java.math.*

This example shows mapping of java. math. Big Integer and java. math. Big Decial.

package com.logicbig.example;

import javax.persistence.Entity;
import javax.persistence.Id;
import java.math.BigDecimal;
import java.math.BigInteger;

@Entity
public class ExampleEntity {
@Id
private String id;

private BigInteger aBigInteger;
private BigDecimal aBigDecimal;
}

Output

--------
SHOW COLUMNS from ExampleEntity
[ID, VARCHAR(2147483647), NO, PRI, NULL]
[ABIGDECIMAL, DECIMAL(38), YES, , NULL]
[ABIGINTEGER, DECIMAL(38), YES, , NULL]
Original PostDownload Project Browser 




java.sql.* date types

This example shows java.sql.Date, java.sql.Time and java. sql. Timestamp mapping.

package com.logicbig.example;

import javax.persistence.Entity;
import javax.persistence.Id;
import java.sql.Date;
import java.sql.Time;
import java.sql.Timestamp;

@Entity
public class ExampleEntity {
@Id
private int id;

private Date date;
private Time time;
private Timestamp timestamp;
}

Output

--------
SHOW COLUMNS from ExampleEntity
[ID, INTEGER(10), NO, PRI, NULL]
[DATE, DATE(8), YES, , NULL]
[TIME, TIME(6), YES, , NULL]
[TIMESTAMP, TIMESTAMP(23), YES, , NULL]
Original PostDownload Project Browser 

Arrays of Simple Types

Arrays of simple types can also be mapped to database columns without any explicit configuration. They will either be mapped to VARBINARY or VARCHAR.

package com.logicbig.example;

import javax.persistence.Entity;
import javax.persistence.Id;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.Date;

@Entity
public class ExampleEntity {
@Id
private int id;

private byte[] bytes;
private Byte[] byteWrappers;

private short[] shorts;
private Short[] shortWrappers;

private int[] ints;
private Integer[] intWrappers;

private char[] chars;
private Character[] charWrappers;

private long[] longs;
private Long[] longWrappers;

private float[] floats;
private Float[] floatWrappers;

private double[] doubles;
private Double[] doubleWrappers;

private BigInteger[] bigIntegers;
private BigDecimal[] bigDecimals;

private String[] strings;

private Date[] dates;
private Calendar[] calendars;
private java.sql.Date[] sqlDates;
private Time[] sqlTimes;
private Timestamp[] sqlTimestamps;

public Date[] getDates() {
return dates;
}

public void setDates(Date[] dates) {
this.dates = dates;
}
}

package com.logicbig.example;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

public class Main {
private static final EntityManagerFactory emf =
Persistence.createEntityManagerFactory("testPersistenceUnit");
private static final EntityManager entityManager = emf.createEntityManager();

public static void main(String[] args) {
runNativeQuery("SHOW TABLES");

//this will print column name, type, can-be-NULL,
// KEY and default value respectively
runNativeQuery("SHOW COLUMNS from ExampleEntity");

//Populate entity with an array and persist
ExampleEntity entity = new ExampleEntity();
entity.setDates(new Date[]{new Date(), new Date(500000)});
entityManager.getTransaction().begin();
entityManager.persist(entity);
entityManager.getTransaction().commit();

ExampleEntity entity1 = entityManager.find(ExampleEntity.class, 0);
Date[] dates = entity1.getDates();
if (dates != null && dates.length > 0) {
System.out.println("date loaded from database: ");
System.out.println(dates[0]);
}
}

private static void runNativeQuery(String s) {
System.out.println("--------\n" + s);
Query query = entityManager.createNativeQuery(s);
List list = query.getResultList();
for (Object o : list) {
System.out.println(Arrays.toString((Object[]) o));
}
}
}

Output

--------
SHOW TABLES
[EXAMPLEENTITY, PUBLIC]
--------
SHOW COLUMNS from ExampleEntity
[ID, INTEGER(10), NO, PRI, NULL]
[BIGDECIMALS, VARBINARY(2147483647), YES, , NULL]
[BIGINTEGERS, VARBINARY(2147483647), YES, , NULL]
[BYTEWRAPPERS, VARBINARY(2147483647), YES, , NULL]
[BYTES, VARBINARY(2147483647), YES, , NULL]
[CALENDARS, VARBINARY(2147483647), YES, , NULL]
[CHARWRAPPERS, VARCHAR(2147483647), YES, , NULL]
[CHARS, VARCHAR(2147483647), YES, , NULL]
[DATES, VARBINARY(2147483647), YES, , NULL]
[DOUBLEWRAPPERS, VARBINARY(2147483647), YES, , NULL]
[DOUBLES, VARBINARY(2147483647), YES, , NULL]
[FLOATWRAPPERS, VARBINARY(2147483647), YES, , NULL]
[FLOATS, VARBINARY(2147483647), YES, , NULL]
[INTWRAPPERS, VARBINARY(2147483647), YES, , NULL]
[INTS, VARBINARY(2147483647), YES, , NULL]
[LONGWRAPPERS, VARBINARY(2147483647), YES, , NULL]
[LONGS, VARBINARY(2147483647), YES, , NULL]
[SHORTWRAPPERS, VARBINARY(2147483647), YES, , NULL]
[SHORTS, VARBINARY(2147483647), YES, , NULL]
[SQLDATES, VARBINARY(2147483647), YES, , NULL]
[SQLTIMES, VARBINARY(2147483647), YES, , NULL]
[SQLTIMESTAMPS, VARBINARY(2147483647), YES, , NULL]
[STRINGS, VARBINARY(2147483647), YES, , NULL]
date loaded from database:
Mon May 01 16:10:21 CDT 2017
Original PostDownload Project Browser 




User defined serializable object and its array

package com.logicbig.example;

import javax.persistence.Entity;
import javax.persistence.Id;
import java.util.Arrays;

@Entity
public class ExampleEntity {
@Id
private int id;
private MySerializableObject mySerializableObject;
private MySerializableObject[] mySerializableObjects;

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public MySerializableObject getMySerializableObject() {
return mySerializableObject;
}

public void setMySerializableObject(MySerializableObject mySerializableObject) {
this.mySerializableObject = mySerializableObject;
}

public MySerializableObject[] getMySerializableObjects() {
return mySerializableObjects;
}

public void setMySerializableObjects(MySerializableObject[] mySerializableObjects) {
this.mySerializableObjects = mySerializableObjects;
}

@Override
public String toString() {
return "ExampleEntity{" +
"id=" + id +
", mySerializableObject=" + mySerializableObject +
", mySerializableObjects=" + Arrays.toString(mySerializableObjects) +
'}';
}
}
package com.logicbig.example;

import java.io.Serializable;

public class MySerializableObject implements Serializable {
private String myString;

public String getMyString() {
return myString;
}

public void setMyString(String myString) {
this.myString = myString;
}

@Override
public String toString() {
return "MyObject{" +
"myString='" + myString + '\'' +
'}';
}
}

src/main/resources/META-INF/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="testPersistenceUnit" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.schema-generation.database.action" value="create"/>
<property name="javax.persistence.jdbc.url" value="jdbc:h2:mem:test;DB_CLOSE_DELAY=-1"/>
</properties>
</persistence-unit>
</persistence>

pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>com.logicbig.example</groupId>
<artifactId>jpa-user-defined-serializable-type</artifactId>
<version>1.0-SNAPSHOT</version>

<dependencies>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.193</version>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>eclipselink</artifactId>
<version>2.6.4</version>
</dependency>

<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>javax.persistence</artifactId>
<version>2.1.1</version>
</dependency>
</dependencies>

<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
</project>
package com.logicbig.example;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import java.util.Arrays;
import java.util.List;

public class Main {
private static final EntityManagerFactory emf =
Persistence.createEntityManagerFactory(
"testPersistenceUnit");
private static final EntityManager entityManager = emf.createEntityManager();

public static void main(String[] args) {
runNativeQuery("SHOW TABLES");
runNativeQuery("SHOW COLUMNS from ExampleEntity");

//creating and persisting
MySerializableObject myObject = new MySerializableObject();
myObject.setMyString("a test string");

ExampleEntity entity = new ExampleEntity();
entity.setId(1);
entity.setMySerializableObject(myObject);

entityManager.getTransaction().begin();
entityManager.persist(entity);
entityManager.getTransaction().commit();

//it will show binary format of the persisted entity
runNativeQuery("select * from ExampleEntity");

System.out.println("finding entity:");
ExampleEntity entity1 = entityManager.find(ExampleEntity.class, 1);
System.out.println(entity1);
}

private static void runNativeQuery(String s) {
System.out.println("--------\n" + s);
Query query = entityManager.createNativeQuery(s);
List list = query.getResultList();
for (Object o : list) {
System.out.println(Arrays.toString((Object[]) o));
}
}
}

Output

--------
SHOW TABLES
[EXAMPLEENTITY, PUBLIC]
--------
SHOW COLUMNS from ExampleEntity
[ID, INTEGER(10), NO, PRI, NULL]
[MYSERIALIZABLEOBJECT, VARBINARY(2147483647), YES, , NULL]
[MYSERIALIZABLEOBJECTS, VARBINARY(2147483647), YES, , NULL]
--------
select * from ExampleEntity
[1, [B@6f7bf62f, null]
finding entity:
ExampleEntity{id=1, mySerializableObject=MyObject{myString='a test string'}, mySerializableObjects=null}
Original PostDownload Project Browser 




See Also