Sunday, 6 November 2022

Hibernate: Override the column properties of embedded type

Using @AttributeOverrides and @AttributeOverride anotations, we can override the column properties of embedded type.

Example

@Embedded
@AttributeOverrides({
      @AttributeOverride( name = "firstName", column = @Column(name = "contact_first_name")),
      @AttributeOverride( name = "middleName", column = @Column(name = "contact_middle_name")),
      @AttributeOverride( name = "lastName", column = @Column(name = "contact_last_name"))
    })
private Name name;

 

Find the below working application.

 

Step 1: Create new maven project ‘hibernate-override-embedded-props-demo’.

 

Step 2: Update pom.xml with maven dependencies.

 

pom.xml

<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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.sample.app</groupId>
    <artifactId>hibernate-override-embedded-props-demo</artifactId>
    <version>1</version>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>

        <java.version>15</java.version>
        <maven.compiler.source>${java.version}</maven.compiler.source>
        <maven.compiler.target>${java.version}</maven.compiler.target>

    </properties>

    <dependencies>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>42.4.1</version>
        </dependency>

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-core</artifactId>
            <version>6.1.2.Final</version>
        </dependency>

        <dependency>
            <groupId>javax.persistence</groupId>
            <artifactId>javax.persistence-api</artifactId>
            <version>2.2</version>
        </dependency>


    </dependencies>
</project>

 

Step 3: Define Name and Contact classes.

 

Name.java
package com.sample.app.entity;

import jakarta.persistence.Embeddable;

@Embeddable
public class Name {

    private String firstName;

    private String middleName;

    private String lastName;
    
    public Name() {}

    public Name(String firstName, String middleName, String lastName) {
        this.firstName = firstName;
        this.middleName = middleName;
        this.lastName = lastName;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getMiddleName() {
        return middleName;
    }

    public void setMiddleName(String middleName) {
        this.middleName = middleName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

}

 

Contact.java

package com.sample.app.entity;

import jakarta.persistence.AttributeOverride;
import jakarta.persistence.AttributeOverrides;
import jakarta.persistence.Embedded;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;
import jakarta.persistence.Column;

@Entity
@Table(name = "contact")
public class Contact {

    @Id
    private Integer id;

    @Embedded
    @AttributeOverrides({
          @AttributeOverride( name = "firstName", column = @Column(name = "contact_first_name")),
          @AttributeOverride( name = "middleName", column = @Column(name = "contact_middle_name")),
          @AttributeOverride( name = "lastName", column = @Column(name = "contact_last_name"))
        })
    private Name name;

    private Integer age;

    public Contact(Integer id, Name name, Integer age) {
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public Integer getId() {
        return id;
    }

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

    public Name getName() {
        return name;
    }

    public void setName(Name name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

}

 

Step 4: Create hibernate.cfg.xml file under src/main/resources folder.

 

hibernate.cfg.xml

 

<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
        "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>

    <session-factory>

        <!-- Database Connection settings -->
        <property name="connection.driver_class">org.postgresql.Driver</property>
        <property name="connection.url">jdbc:postgresql://127.0.0.1:5432/test</property>
        <property name="connection.username">postgres</property>
        <property name="connection.password">postgres</property>

        <!-- Enable the logging of all the generated SQL statements to the console -->
        <property name="show_sql">true</property>

        <!-- Format the generated SQL statement to make it more readable, -->
        <property name="format_sql">true</property>

        <!-- Hibernate will put comments inside all generated SQL statements to 
            hint what’s the generated SQL trying to do -->
        <property name="use_sql_comments">false</property>

        <property name="dialect">org.hibernate.dialect.PostgreSQLDialect</property>

        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">create</property>

        <!-- mappings for annotated classes -->
        <mapping class="com.sample.app.entity.Contact" />

    </session-factory>

</hibernate-configuration>

Step 5: Define main application class.

 

App.java

package com.sample.app;

import java.io.IOException;
import java.net.URISyntaxException;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

import com.sample.app.entity.Contact;
import com.sample.app.entity.Name;

public class App {
    private static final SessionFactory SESSION_FACTORY = buildSessionFactory();

    private static SessionFactory buildSessionFactory() {
        try {

            final StandardServiceRegistry standardRegistry = new StandardServiceRegistryBuilder()
                    .configure("hibernate.cfg.xml").build();

            final Metadata metaData = new MetadataSources(standardRegistry).getMetadataBuilder().build();

            return metaData.getSessionFactoryBuilder().build();

        } catch (Throwable ex) {
            throw new ExceptionInInitializerError(ex);
        }

    }

    public static void main(final String args[]) throws ClassNotFoundException, IOException, URISyntaxException {
        final Contact contact1 = new Contact(1, new Name("Krishna", null, "G"), 34);
        final Contact contact2 = new Contact(2, new Name("Ram", "krishna", "Geeta"), 39);

        try (final Session session = SESSION_FACTORY.openSession()) {
            session.beginTransaction();
            session.persist(contact1);
            session.persist(contact2);
            session.getTransaction().commit();
        }

    }
}

 

Total project structure looks like below.

 



Run App.java, you will see below messages in the console.

Aug 08, 2022 9:32:52 PM org.hibernate.Version logVersion
INFO: HHH000412: Hibernate ORM core version 6.1.2.Final
Aug 08, 2022 9:32:52 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure
WARN: HHH10001002: Using built-in connection pool (not intended for production use)
Aug 08, 2022 9:32:52 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001005: Loaded JDBC driver class: org.postgresql.Driver
Aug 08, 2022 9:32:52 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001012: Connecting with JDBC URL [jdbc:postgresql://127.0.0.1:5432/test]
Aug 08, 2022 9:32:52 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001001: Connection properties: {password=****, user=postgres}
Aug 08, 2022 9:32:52 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator
INFO: HHH10001003: Autocommit mode: false
Aug 08, 2022 9:32:52 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl$PooledConnections <init>
INFO: HHH10001115: Connection pool size: 20 (min=1)
Aug 08, 2022 9:32:52 PM org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl logSelectedDialect
INFO: HHH000400: Using dialect: org.hibernate.dialect.PostgreSQLDialect
Aug 08, 2022 9:32:53 PM org.hibernate.metamodel.internal.EntityInstantiatorPojoStandard resolveConstructor
INFO: HHH000182: No default (no-argument) constructor for class: com.sample.app.entity.Contact (class must be instantiated by Interceptor)
Hibernate: 
    
    drop table if exists contact cascade
Aug 08, 2022 9:32:53 PM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@3f183caa] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
Aug 08, 2022 9:32:53 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper$StandardWarningHandler logWarning
WARN: SQL Warning Code: 0, SQLState: 00000
Aug 08, 2022 9:32:53 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper$StandardWarningHandler logWarning
WARN: table "contact" does not exist, skipping
Hibernate: 
    
    create table contact (
       id integer not null,
        age integer,
        contact_first_name varchar(255),
        contact_last_name varchar(255),
        contact_middle_name varchar(255),
        primary key (id)
    )
Aug 08, 2022 9:32:53 PM org.hibernate.resource.transaction.backend.jdbc.internal.DdlTransactionIsolatorNonJtaImpl getIsolatedConnection
INFO: HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@65383667] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
Aug 08, 2022 9:32:53 PM org.hibernate.engine.transaction.jta.platform.internal.JtaPlatformInitiator initiateService
INFO: HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
Hibernate: 
    insert 
    into
        contact
        (age, contact_first_name, contact_last_name, contact_middle_name, id) 
    values
        (?, ?, ?, ?, ?)
Hibernate: 
    insert 
    into
        contact
        (age, contact_first_name, contact_last_name, contact_middle_name, id) 
    values
        (?, ?, ?, ?, ?)

 

You can confirm the DDL by querying the PostgreSQL.

test=# \d+ contact
                                                       Table "public.contact"
       Column        |          Type          | Collation | Nullable | Default | Storage  | Compression | Stats target | Description 
---------------------+------------------------+-----------+----------+---------+----------+-------------+--------------+-------------
 id                  | integer                |           | not null |         | plain    |             |              | 
 age                 | integer                |           |          |         | plain    |             |              | 
 contact_first_name  | character varying(255) |           |          |         | extended |             |              | 
 contact_last_name   | character varying(255) |           |          |         | extended |             |              | 
 contact_middle_name | character varying(255) |           |          |         | extended |             |              | 
Indexes:
    "contact_pkey" PRIMARY KEY, btree (id)
Access method: heap

You can download this application from this link.



 

Previous                                                    Next                                                    Home

Saturday, 5 November 2022

Convert a wrapper array to primitive array in Java

Write a program to convert the wrapper array to primitive array in Java. For example, for the Integer[] array, you should return int[].

 

Step 1: Write a function that return a primitive type equivalent to the given wrapper type.

private static final Map<Class<?>, Class<?>> WRAPPER_TO_PRIMITIVE;

static {
	WRAPPER_TO_PRIMITIVE = new LinkedHashMap<>();

	WRAPPER_TO_PRIMITIVE.put(Byte.class, byte.class);
	WRAPPER_TO_PRIMITIVE.put(Short.class, short.class);
	WRAPPER_TO_PRIMITIVE.put(Integer.class, int.class);
	WRAPPER_TO_PRIMITIVE.put(Long.class, long.class);
	WRAPPER_TO_PRIMITIVE.put(Float.class, float.class);
	WRAPPER_TO_PRIMITIVE.put(Double.class, double.class);
	WRAPPER_TO_PRIMITIVE.put(Boolean.class, boolean.class);
	WRAPPER_TO_PRIMITIVE.put(Character.class, char.class);
}

public static Class<?> getPrimitiveType(final Class<?> wrapperType) {
	final Class<?> primitiveType = WRAPPER_TO_PRIMITIVE.get(wrapperType);

	if (primitiveType == null) {
		throw new IllegalArgumentException("Given type is not a wrapper type");
	}

	return primitiveType;
}

Step 2: Get the component type of wrapper array.

Class<?> wrapperArrayClazz = wrapperArray.getClass();
Class<?> wrapperArrayComponentType = wrapperArrayClazz.getComponentType();

Step 3: Find the equivalent primitive type from the wrapper array component type.

Class<?> primitiveType = getPrimitiveType(wrapperArrayComponentType);

Step 4: Define primitive array and copy the elements one by one.

int length = Array.getLength(wrapperArray);
Object primitiveArray = Array.newInstance(primitiveType, length);
for (int i = 0; i < length; i++) {
	Object ele = Array.get(wrapperArray, i);
	Array.set(primitiveArray, i, ele);
}

Find the below working application.

 


ArrayWrapperToPrimitiveDemo.java

package com.sample.app.arrays;

import java.lang.reflect.Array;
import java.util.LinkedHashMap;
import java.util.Map;

public class ArrayWrapperToPrimitiveDemo {

	private static final Map<Class<?>, Class<?>> WRAPPER_TO_PRIMITIVE;

	static {
		WRAPPER_TO_PRIMITIVE = new LinkedHashMap<>();

		WRAPPER_TO_PRIMITIVE.put(Byte.class, byte.class);
		WRAPPER_TO_PRIMITIVE.put(Short.class, short.class);
		WRAPPER_TO_PRIMITIVE.put(Integer.class, int.class);
		WRAPPER_TO_PRIMITIVE.put(Long.class, long.class);
		WRAPPER_TO_PRIMITIVE.put(Float.class, float.class);
		WRAPPER_TO_PRIMITIVE.put(Double.class, double.class);
		WRAPPER_TO_PRIMITIVE.put(Boolean.class, boolean.class);
		WRAPPER_TO_PRIMITIVE.put(Character.class, char.class);
	}

	public static Class<?> getPrimitiveType(final Class<?> wrapperType) {
		final Class<?> primitiveType = WRAPPER_TO_PRIMITIVE.get(wrapperType);

		if (primitiveType == null) {
			throw new IllegalArgumentException("Given type is not a wrapper type");
		}

		return primitiveType;
	}

	public static Object toPrimitiveArray(final Object wrapperArray) {

		if (wrapperArray == null) {
			throw new IllegalArgumentException("Wrapper array cannot be null");
		}

		final Class<?> wrapperArrayClazz = wrapperArray.getClass();
		if (!wrapperArrayClazz.isArray()) {
			throw new IllegalArgumentException("Given input is not an array");
		}

		final Class<?> wrapperArrayComponentType = wrapperArrayClazz.getComponentType();
		final Class<?> primitiveType = getPrimitiveType(wrapperArrayComponentType);
		final int length = Array.getLength(wrapperArray);

		final Object primitiveArray = Array.newInstance(primitiveType, length);
		for (int i = 0; i < length; i++) {
			final Object ele = Array.get(wrapperArray, i);
			Array.set(primitiveArray, i, ele);
		}
		return primitiveArray;
	}

	public static void main(String[] args) {
		Integer[] primes = new Integer[] { 2, 3, 5, 7, 11 };

		int[] primesPrimitiveArray = (int[]) toPrimitiveArray(primes);

		for (int i : primesPrimitiveArray) {
			System.out.println(i);
		}
	}
}

Output

2
3
5
7
11


You may like

Interview Questions

Array programs in Java

Generic method to concatenate two arrays in Java

Get the string representation of array by given delimiter in Java

Get an iterator from array in Java

Get reverse iterator for the given array in Java

Convert primitive array to wrapper array in Java

Convert a primitive array to wrapper array in Java

Write a program to convert the primitive array to wrapper array in Java. For example, for the int[] array, you should return Integer[].

 

Step 1: Let’s define a map, to get the wrapper type equivalent to the given primitive type.

private static final Map<Class<?>, Class<?>> PRIMITIVES_TO_WRAPPERS;

static {
	PRIMITIVES_TO_WRAPPERS = new LinkedHashMap<>();
	PRIMITIVES_TO_WRAPPERS.put(boolean.class, Boolean.class);
	PRIMITIVES_TO_WRAPPERS.put(byte.class, Byte.class);
	PRIMITIVES_TO_WRAPPERS.put(char.class, Character.class);
	PRIMITIVES_TO_WRAPPERS.put(double.class, Double.class);
	PRIMITIVES_TO_WRAPPERS.put(float.class, Float.class);
	PRIMITIVES_TO_WRAPPERS.put(int.class, Integer.class);
	PRIMITIVES_TO_WRAPPERS.put(long.class, Long.class);
	PRIMITIVES_TO_WRAPPERS.put(short.class, Short.class);
	PRIMITIVES_TO_WRAPPERS.put(void.class, Void.class);
}

Step 2: Define a method that return a wrapper type equivalent to the given primitive type.

public static Class<?> getWrapperType(Class<?> primitiveType) {
	if (primitiveType.isPrimitive()) {
		return PRIMITIVES_TO_WRAPPERS.get(primitiveType);
	}
	throw new IllegalArgumentException("Given type is not primitive");
}

Step 3: Get the component type of given input array.

Class<?> clazz = primitiveArray.getClass();
Class<?> componentType = clazz.getComponentType();

Step 4: Define new array using the input array component type and copy the elements from input array to this wrapper array.

int inputArrayLength = Array.getLength(primitiveArray);
Object[] arr = (Object[]) Array.newInstance(getWrapperType(componentType), inputArrayLength);

for (int i = 0; i < inputArrayLength; i++) {
	arr[i] = Array.get(primitiveArray, i);
}

Find the below working application.


ArrayPrimitiveToWrapperDemo.java

package com.sample.app.arrays;

import java.lang.reflect.Array;
import java.util.LinkedHashMap;
import java.util.Map;

public class ArrayPrimitiveToWrapperDemo {

	private static final Map<Class<?>, Class<?>> PRIMITIVES_TO_WRAPPERS;

	static {
		PRIMITIVES_TO_WRAPPERS = new LinkedHashMap<>();
		PRIMITIVES_TO_WRAPPERS.put(boolean.class, Boolean.class);
		PRIMITIVES_TO_WRAPPERS.put(byte.class, Byte.class);
		PRIMITIVES_TO_WRAPPERS.put(char.class, Character.class);
		PRIMITIVES_TO_WRAPPERS.put(double.class, Double.class);
		PRIMITIVES_TO_WRAPPERS.put(float.class, Float.class);
		PRIMITIVES_TO_WRAPPERS.put(int.class, Integer.class);
		PRIMITIVES_TO_WRAPPERS.put(long.class, Long.class);
		PRIMITIVES_TO_WRAPPERS.put(short.class, Short.class);
		PRIMITIVES_TO_WRAPPERS.put(void.class, Void.class);
	}

	public static Class<?> getWrapperType(Class<?> primitiveType) {
		if (primitiveType.isPrimitive()) {
			return PRIMITIVES_TO_WRAPPERS.get(primitiveType);
		}
		throw new IllegalArgumentException("Given type is not primitive");
	}

	public static Object[] toWrapperArray(final Object primitiveArray) {

		if (primitiveArray == null) {
			throw new IllegalArgumentException("primitiveArray can't null");
		}

		final Class<?> clazz = primitiveArray.getClass();
		if (!clazz.isArray()) {
			throw new IllegalArgumentException("input is not an array");
		}

		final Class<?> componentType = clazz.getComponentType();
		if (!componentType.isPrimitive()) {
			throw new IllegalArgumentException("Input is not a primitive array");
		}

		final int inputArrayLength = Array.getLength(primitiveArray);

		final Object[] arr = (Object[]) Array.newInstance(getWrapperType(componentType), inputArrayLength);

		for (int i = 0; i < inputArrayLength; i++) {
			arr[i] = Array.get(primitiveArray, i);
		}
		return arr;
	}

	public static void main(String[] args) {
		final int[] primes = new int[] { 2, 3, 5, 7, 11 };

		final Integer[] primesWrapperArray = (Integer[]) toWrapperArray(primes);

		for (Integer i : primesWrapperArray) {
			System.out.println(i);
		}
	}

}

Output

2
3
5
7
11


 

You may like

Interview Questions

Array programs in Java

Generic method to concatenate two arrays in Java

Get the string representation of array by given delimiter in Java

Get an iterator from array in Java

Get reverse iterator for the given array in Java

How to break out of nested loops in Java?

Get reverse iterator for the given array in Java

Write a method that takes an array as input and return the reverse iterator.

 

Signature

public static <T> Iterator<T> reverseIterator(T[] array)

Define ArrayReverseIterator

 

ArrayReverseIterator.java

package com.sample.app.iterators;

import java.util.Iterator;
import java.util.NoSuchElementException;

public class ArrayReverseIterator<T> implements Iterator<T>, Iterable<T> {

	private final T[] array;
	private int currentIndex;

	public ArrayReverseIterator(T[] array) {
		if (array == null) {
			throw new IllegalArgumentException("Array can't be null to get an interator");
		}

		this.array = array;
		final int length = array.length;
		currentIndex = length > 0 ? (length - 1) : -1;
	}

	@Override
	public boolean hasNext() {
		return currentIndex > -1;
	}

	@Override
	public T next() {
		if (currentIndex <= -1) {
			throw new NoSuchElementException();
		}
		return array[currentIndex--];
	}

	@Override
	public void remove() {
		throw new UnsupportedOperationException();
	}

	@Override
	public Iterator<T> iterator() {
		return this;
	}
}

 

Use ArrayReverseIterator to read the array elements from last.


ArrayReverseIteratorDemo.java

package com.sample.app.arrays;

import java.util.Iterator;

import com.sample.app.iterators.ArrayReverseIterator;

public class ArrayReverseIteratorDemo {

	public static <T> Iterator<T> reverseIterator(T[] array) {
		return new ArrayReverseIterator<T>(array);
	}

	public static void main(String[] args) {
		ArrayReverseIterator<Integer> iterator = (ArrayReverseIterator) reverseIterator(new Integer[] { 2, 3, 5, 7, 11 });

		for (Integer ele : iterator) {
			System.out.println(ele);
		}
	}

}

 

Output

11
7
5
3
2

 

  

You may like

Interview Questions

Array programs in Java

Generic method to concatenate two arrays in Java

Get the string representation of array by given delimiter in Java

Get an iterator from array in Java

java.util.Date vs java.sql.Date

How to break out of nested loops in Java?

org.hibernate.InstantiationException: Unable to locate constructor for embeddable

I got this error, when the embeddable class do not have a default constructor. Resolved this problem by having a default constructor in Embeddable class.

@Embeddable
public class Name {

    private String firstName;

    private String middleName;

    private String lastName;
    
    public Name() {}

    public Name(String firstName, String middleName, String lastName) {
        this.firstName = firstName;
        this.middleName = middleName;
        this.lastName = lastName;
    }

    ..........
    ..........
}

 You can download the complete working application from this link.


 

Previous                                                    Next                                                    Home