How to bootstrap Hibernate without the persistence.xml file?

How to bootstrap Hibernate without the persistence.xml file?
Techiio-author
Written by Sagar RabidasFebruary 22, 2022
9 min read
Hibernate
1 VIEWS 0 LIKES 0 DISLIKES SHARE
0 LIKES 0 DISLIKES 1 VIEWS SHARE
Techiio-author
Sagar Rabidas

Software Developer

In this blog, we will discuss How to bootstrap Hibernate without the persistence.xml file

Introduction of Hibernate ORM & persistence.xml file:-

Hibernate ORM (or simply Hibernate) is an object-relational mapping tool for the Java programming language. It provides a framework for mapping an object-oriented domain model to a relational database. Hibernate handles object-relational impedance mismatch problems by replacing direct, persistent database accesses with high-level object handling functions. Hibernate's primary feature is mapping from Java classes to database tables and mapping from Java data types to SQL data types. Hibernate also provides data query and retrieval facilities. It generates SQL calls and relieves the developer from the manual handling and object conversion of the result set.

Patience. XML defines one or greater endurance gadgets. ... This report defines a persistence unit named order management, which uses the source of a JTA-aware statistic JDBC/MyOrderDB. The jar-file and class factors specify controlled persistence instructions: entity instructions, embeddable instructions, and mapped superclasses.

JPA relies closely on the endurance.Xml configuration record, and the same old API to bootstrap a JPA provider programmatically requires an excessive amount of boilerplate code. Whilst in a standard organization utility, presenting a patience.Xml file is not a trouble, this requirement doesn’t get at the side of unit trying out, especially while checks are completely remoted and that they want to validate exclusive components of JPA or hibernate.

That turned into a problem that I ran into while writing test instances for the excessive-performance java persistence ebook. All my tests want to be isolated, and no longer do they all percentage the same settings or entities.

In my case, the use of an unmarried staying power.Xml report changed into honestly out of the query due to the fact any exchange could have a rippling effect all through the complete check suite.

Hibernate to the rescue:-

Hibernate is awesome. It allows you to build an EntityManagerFactory completely programmatically and with a few lines of code:

protected EntityManagerFactory newEntityManagerFactory() {
    PersistenceUnitInfo persistenceUnitInfo =
        persistenceUnitInfo(getClass().getSimpleName());
    Map<String, Object> configuration = new HashMap<>();
    configuration.put(AvailableSettings.INTERCEPTOR,
        interceptor()
    );
 
    return new EntityManagerFactoryBuilderImpl(
            new PersistenceUnitInfoDescriptor(
                persistenceUnitInfo), configuration
    ).build();
}
 
protected PersistenceUnitInfoImpl persistenceUnitInfo(
    String name) {
    return new PersistenceUnitInfoImpl(
        name, entityClassNames(), properties()
    );
}

Each test starts with some reasonable default properties, and entities must be provided on a per-test basis.

protected Properties properties() {
    Properties properties = new Properties();
    properties.put("hibernate.dialect",
        dataSourceProvider().hibernateDialect()
    );
    properties.put("hibernate.hbm2ddl.auto",
        "create-drop");
    DataSource dataSource = newDataSource();
    if (dataSource != null) {
        properties.put("hibernate.connection.datasource",
        dataSource);
    }
    return properties;
}
 
protected List entityClassNames() {
    return Arrays.asList(entities())
        .stream()
        .map(Class::getName)
        .collect(Collectors.toList());
}
 
protected abstract Class[] entities();

A test can define its settings and entities, and, this way, we can encapsulate the entire environment.

@Override
protected Class<?>[] entities() {
    return new Class<?>[] {
        Patch.class
    };
}
 
@Entity(name = "Patch")
public class Patch {
 
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id;
 
    @ElementCollection
    @CollectionTable(
            name="patch_change",
            joinColumns=@JoinColumn(name="patch_id")
    )
    @OrderColumn(name = "index_id")
    private List<Change> changes = new ArrayList<>();
 
    public List<Change> getChanges() {
        return changes;
    }
}
 
@Embeddable
public class Change {
 
    @Column(name = "path", nullable = false)
    private String path;
 
    @Column(name = "diff", nullable = false)
    private String diff;
 
    public Change() {
    }
 
    public Change(String path, String diff) {
        this.path = path;
        this.diff = diff;
    }
 
    public String getPath() {
        return path;
    }
 
    public String getDiff() {
        return diff;
    }
}

Hibernate
persistence xml file
Java
1 VIEWS 0 LIKES 0 DISLIKES SHARE
0 LIKES 0 DISLIKES 1 VIEWS SHARE
Was this blog helpful?
techiio-price-plantechiio-price-plantechiio-price-plantechiio-price-plantechiio-price-plan
You must be Logged in to comment
Code Block
Techiio-author
Sagar Rabidas
Software Developer
Techiio-followerTechiio-followerTechiio-followerTechiio-followerTechiio-follower
+8 more
300 Blog Posts
14 Discussion Threads
Trending Technologies
15
Software40
DevOps46
Frontend Development24
Backend Development20
Server Administration17
Linux Administration26
Data Center24
Sentry24
Terraform23
Ansible83
Docker70
Penetration Testing16
Kubernetes21
NGINX20
JenkinsX17
Techiio-logo

Techiio is on the journey to build an ocean of technical knowledge, scouring the emerging stars in process and proffering them to the corporate world.

Follow us on:

Subscribe to get latest updates

You can unsubscribe anytime from getting updates from us
Developed and maintained by Wikiance
Developed and maintained by Wikiance