Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Hibernate6: quick guide to value types

Hibernate6: Quick Guide To Value Types

Value type represents a piece of data in the entity, which do not define its own life cycle.

 

Value types are categorized into three categories.

a.   Basic types

b.   Embeddable types

c.    Collection types

 

Basic types

A basic type is a mapping between a Java type and a single database column.

 

Following list describes the basic types.

a.   Primitive types like byte, short, int, long, float, double, boolean and char.

b.   Primitive wrappers like Byte, Short, Integer, Long, Float, Double, Boolean and Character

c.    String type

d.   Arbitrary-precision numeric types like BigInteger and BigDecimal

e.   Date/time types java.time.LocalDate, java.time.LocalTime, java.time.LocalDateTime, java.time.OffsetTime, java.time.OffsetDateTime, java.time.Instant, java.util.Date, java.util.Calendar,      

f.     java.sql.Date, java.sql.Time, java.sql.Timestamp.

g.   Byte and character arrays:     byte[] or Byte[], char[] or Character[]

h.   Java enumerated types: Any enum

i.     Serializable types: any type that implements Serializable

 

Embeddable types

An Embeddable type life cycle is bound to the parent entity type.

 

Example

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

@Id
private Integer id;

@Embedded
private Name name;

private Integer age;

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

 

In the above example, Name is an embedded type.

 

Collection types

Collection types specifies the collection of elements, For example, a person might have one or more communication addresses.

 

Example

@Entity
@Table(name = "person")
public class Person {

@Id
private Integer id;

@Embedded
private Name name;

private Integer age;

@ElementCollection
List addresses;

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

 

In the above example

a.   id and age are basic types

b.   name is embedded type

c.    addresses is a collection + embedded type

 

Find the below working application.

 

Step 1: Create new maven project ‘hibernate-value-types-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.0modelVersion>
groupId>com.sample.appgroupId>
artifactId>hibernate-value-types-demoartifactId>
version>1version>

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

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

properties>

dependencies>
dependency>
groupId>org.postgresqlgroupId>
artifactId>postgresqlartifactId>
version>42.4.1version>
dependency>

dependency>
groupId>org.hibernategroupId>
artifactId>hibernate-coreartifactId>
version>6.1.2.Finalversion>
dependency>

dependency>
groupId>javax.persistencegroupId>
artifactId>javax.persistence-apiartifactId>
version>2.2version>
dependency>


dependencies>
project>

 

Step 3: Define entity classes.

 

Address.java

 

package com.sample.app.entity;

import jakarta.persistence.Embeddable;

@Embeddable
public class Address {
private String street;
private String city;
private String state;
private String pin;
private String country;

public Address() {}

public Address(String street, String city, String state, String pin, String country) {
this.street = street;
this.city = city;
this.state = state;
this.pin = pin;
this.country = country;
}

public String getStreet() {
return street;
}

public void setStreet(String street) {
this.street = street;
}

public String getCity() {
return city;
}

public void setCity(String city) {
this.city = city;
}

public String getState() {
return state;
}

public void setState(String state) {
this.state = state;
}

public String getPin() {
return pin;
}

public void setPin(String pin) {
this.pin = pin;
}

public String getCountry() {
return country;
}

public void setCountry(String country) {
this.country = country;
}

}

 

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;
}

}

Person.java

package com.sample.app.entity;

import java.util.List;

import jakarta.persistence.ElementCollection;
import jakarta.persistence.Embedded;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Table;

@Entity
@Table(name = "person")
public class Person {

@Id
private Integer id;

@Embedded
private Name name;

private Integer age;

@ElementCollection
List addresses;

public Person(Integer id, Name name, Integer age, List addresses) {
this.id = id;
this.name = name;
this.age = age;
this.addresses = addresses;
}

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;
}

public List getAddresses() {
return addresses;
}

public void setAddresses(List addresses) {
this.addresses = addresses;
}

}

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

 

hibernate.cfg.xml

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

hibernate-configuration>

session-factory>


property name="connection.driver_class">org.postgresql.Driverproperty>
property name="connection.url">jdbc:postgresql://127.0.0.1:5432/testproperty>
property name="connection.username">postgresproperty>
property name="connection.password">postgresproperty>


property name="show_sql">trueproperty>


property name="format_sql">trueproperty>


property name="use_sql_comments">falseproperty>

property name="dialect">org.hibernate.dialect.PostgreSQLDialectproperty>


property name="hbm2ddl.auto">createproperty>


mapping class="com.sample.app.entity.Person" />
mapping class="com.sample.app.entity.Address" />

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 java.util.Arrays;
import java.util.List;

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.Address;
import com.sample.app.entity.Name;
import com.sample.app.entity.Person;

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 List person1Addresses = Arrays.asList(
new Address("Chowdeswari Street", "Bangalore", "Karnataka", "12345", "India"),
new Address("Auto Nagar", "Vijayawada", "Andhra Pradesh", "234567", "India"));

final List person2Addresses = Arrays.asList(


This post first appeared on Java Tutorial : Blog To Learn Java Programming, please read the originial post: here

Share the post

Hibernate6: quick guide to value types

×

Subscribe to Java Tutorial : Blog To Learn Java Programming

Get updates delivered right to your inbox!

Thank you for your subscription

×