0% found this document useful (0 votes)
8 views

Hibernate

Uploaded by

patnaiksai1407
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views

Hibernate

Uploaded by

patnaiksai1407
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

Hibernate

Hibernate is a java framework that is used to interact with java


application and database.
- It is an open source, light-weight, ORM (Object Relation
Management) Tool.
- For data persistence it implements some JPA (Java Persistence
API) Specifications.

ORM – It is a programming technique that is used for data


manipulation, data creation and data access, and map the
object to store data in DB.

Internally it uses the JDBC API to interact with the DB.

JPA (Java Persistence API) – It is a java specification that


provides the functionality to the ORM tool.
Package – javax.persistence -> it contains all the JPA
classes & Interfaces.

Features:
 Open-Source Lightweight
 Fast performance [cause of internal cache memory].
 DB Independent Query [HQL query features]-> it
automatically creates the queries for us, we don’t need to
write it manually.
 Automatic Table Creation.
 Simplifies Complex Join. -> @JoinColumn, @OneToMany,
@ManyToOne, Fetch = FetchType.Lazy etc.
“Hibernate Architecture”
It provides many objects such as persistent object, session
factory, transaction factory, connection factory, session,
transaction etc.
1. Java Application Layer
2. Hibernate Framework Layer
3. Backend Api Layer
4. Database Layer

Elements of Hibernate Architecture:


1. Session Factory:
It is a factory of session and client of ConnectionProvider.
It holds the optional data (Second level cache). The
org.hibernate.SessionFactory interface provides
factory method to get the object of session.

2. Session:
The session object provides an interface between
application and data stored in the database.
It has internal JDBC connection. It provides factory
methods for Transaction, Query and Criteria.
The org.hibernate.Session interface provides methods
to insert, update and delete the object.

3. Transaction:
It is used for transaction management in the program.
It provides the atomic unit of work. [One by one].
The org.hibernate.Transaction provides methods to
manage the transaction.

4. ConnectionProvider:
It is a factory of JDBC Connection and it has an abstract
property for Driver Manager and Data Source.

5. TransactionalFactory:
It is a factory of Transaction and it is a optional part.

Create Program using hibernate configuration:


We have two ways to create the hibernate configuration:
 Using XML File.
 Using Class File.
Using Class file:
1. Add Dependencies:
<!-- Spring Boot Starter Data JPA -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- Hibernate Entity Manager -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
</dependency>
<!-- PostgreSQL Driver -->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>

2. Setup the application.properties file:


# DataSource configuration
spring.datasource.url=jdbc:mysql://localhost:3306/
your_database_name
spring.datasource.username=your_username
spring.datasource.password=your_password
spring.datasource.driver-class-
name=com.mysql.cj.jdbc.Driver

# Hibernate properties
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.diale
ct.MySQLDialect

3. Configure hibernate using class file:


import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import
org.springframework.orm.hibernate5.LocalSessionFactoryBean;

import javax.sql.DataSource;
import java.util.Properties;

@Configuration
public class HibernateConfig {

@Bean
public LocalSessionFactoryBean sessionFactory(DataSource
dataSource) {
LocalSessionFactoryBean sessionFactoryBean = new
LocalSessionFactoryBean();
sessionFactoryBean.setDataSource(dataSource);

sessionFactoryBean.setPackagesToScan("com.acejobber.chatserver.E
ntity"); // Specify packages to scan for entity classes

Properties hibernateProperties = new Properties();


hibernateProperties.setProperty("hibernate.dialect",
"org.hibernate.dialect.PostgreSQLDialect");
hibernateProperties.setProperty("hibernate.hbm2ddl.auto",
"update");
hibernateProperties.setProperty("hibernate.show_sql", "true");
hibernateProperties.setProperty("hibernate.format_sql", "true");

hibernateProperties.setProperty("hibernate.globally_quoted_identifie
rs", "true");

// C3P0 Connection Pooling

hibernateProperties.setProperty("hibernate.connection.provider_clas
s", "org.hibernate.connection.C3P0ConnectionProvider");
hibernateProperties.setProperty("hibernate.c3p0.min_size",
"5");
hibernateProperties.setProperty("hibernate.c3p0.max_size",
"20");
hibernateProperties.setProperty("hibernate.c3p0.timeout",
"1800");

hibernateProperties.setProperty("hibernate.c3p0.max_statements",
"50");

hibernateProperties.setProperty("hibernate.c3p0.idle_test_period",
"3000");
hibernateProperties.setProperty("hibernate.c3p0.test_connection_on
_checkout", "true");

hibernateProperties.setProperty("hibernate.c3p0.preferredTestQuery
", "SELECT 1;");

hibernateProperties.setProperty("hibernate.c3p0.debugUnreturnedC
onnectionStackTraces", "true");

sessionFactoryBean.setHibernateProperties(hibernateProperties);

return sessionFactoryBean;
}
}

Using XML file:


1. Add Dependencies:
<!-- Hibernate Entity Manager -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
</dependency>
<!-- PostgreSQL Driver -->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>

2. Set Application Property:


spring.application.name=chatserver
server.port=8088
# spring.datasource.url=jdbc:postgresql://dlsvr.eai.ealphai.com:5432/
doctormanagement
spring.datasource.url=jdbc:postgresql://localhost:5432/company
spring.datasource.username=postgresfrrggg
spring.datasource.password=rootcause

spring.datasource.driver-class-name=org.postgresql.Driver
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto= update

spring.jpa.properties.hibernate.globally_quoted_identifiers=true
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect

spring.jpa.show-sql: true
# debug=true

spring.main.allow-circular-references=true
logging.level.org.springframework=DEBUG
logging.level.org.hibernate=DEBUG

3. Configure hibernate.cfg.xml file:


<?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 Dialect -->
<property
name="hibernate.dialect">org.hibernate.dialect.PostgreS
QLDialect</property>

<!-- Database Connection Settings -->


<property
name="hibernate.connection.url">jdbc:postgresql://localh
ost:5432/company</property>
<property
name="hibernate.connection.username">postgresfrrggg<
/property>
<property
name="hibernate.connection.password">rootcause</prop
erty>

<!-- Automatic Schema Generation -->


<property
name="hbm2ddl.auto">update</property>

<!-- SQL Output Settings -->


<property
name="hibernate.show_sql">true</property>
<property
name="hibernate.format_sql">true</property>
<property
name="hibernate.use_sql_comments">true</property>
<property
name="hibernate.globally_quoted_identifiers">true</prop
erty>
<property
name="hibernate.type_registry_sql_supports_comments"
>true</property>

<!-- Debugging and Performance Monitoring -->


<property
name="hibernate.generate_statistics">true</property>
<property
name="hibernate.debug_pretty_print_stacktrace">true</
property>
<property
name="hibernate.template_check_timeout">3000</prope
rty>

<!-- JDBC Metadata Defaults -->


<property
name="hibernate.temp.use_jdbc_metadata_defaults">fals
e</property>

<!-- Connection Pooling Configuration -->


<property
name="hibernate.connection.provider_class">org.hiberna
te.connection.C3P0ConnectionProvider</property>
<property
name="hibernate.c3p0.min_size">5</property>
<property
name="hibernate.c3p0.max_size">20</property>
<property
name="hibernate.c3p0.timeout">1800</property>
<property
name="hibernate.c3p0.max_statements">50</property>
<property
name="hibernate.c3p0.idle_test_period">3000</property
>
<property
name="hibernate.c3p0.test_connection_on_checkout">tru
e</property>
<property
name="hibernate.c3p0.preferredTestQuery">SELECT
1;</property>
<property
name="hibernate.c3p0.debugUnreturnedConnectionStack
Traces">true</property>

<!-- Mapping Configuration -->


<mapping
class="com.acejobber.chatserver.Entity.Message" />
<mapping
class="com.acejobber.chatserver.Entity.MessageInbox" />
<mapping
class="com.acejobber.chatserver.Entity.Conversation" />
<mapping
class="com.acejobber.chatserver.MainService.ChatEntity"
/>

</session-factory>
</hibernate-configuration>

4. Set the sessionFactory in main Method


package com.acejobber.chatserver;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;

import com.acejobber.chatserver.Entity.Conversation;
import com.acejobber.chatserver.Entity.Message;
import com.acejobber.chatserver.Entity.MessageInbox;
import com.acejobber.chatserver.MainService.ChatEntity;

@SpringBootApplication
public class ChatserverApplication {

public static void main(String[] args) {

SpringApplication.run(ChatserverApplication.class, args);

@Bean
public SessionFactory getSession() {
Configuration configuration = new Configuration();

configuration.configure("hibernate.cfg.xml").addAnnotatedClass(Messa
ge.class);

configuration.configure("hibernate.cfg.xml").addAnnotatedClass(Messa
geInbox.class);

configuration.configure("hibernate.cfg.xml").addAnnotatedClass(Conve
rsation.class);

configuration.configure("hibernate.cfg.xml").addAnnotatedClass(ChatE
ntity.class);
SessionFactory sessionFactory =
configuration.buildSessionFactory();
Session session = sessionFactory.openSession();
System.out.println(session.isConnected());
// return session;
return sessionFactory;
}
}

Persistence Class creation using annotation:


package com.acejobber.chatserver.Entity;

import java.util.ArrayList;
import java.util.List;

import javax.persistence.*;

import com.fasterxml.jackson.annotation.JsonBackReference;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonManagedReference;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

@Entity
@Data
@Table(name = "inbox", schema = "sdtest")
@JsonInclude(JsonInclude.Include.NON_NULL)
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
public class MessageInbox {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "inbox_id")
private Long id;

@Column
private Long receiverId; // chatter ID

@Column
private Long senderId; // User ID
@JsonManagedReference
@OneToMany(mappedBy = "inbox", fetch = FetchType.EAGER, cascade
= CascadeType.ALL)
private List<Message> messages;

@JsonBackReference
@ManyToOne(fetch = FetchType.LAZY,cascade = CascadeType.ALL)
@JoinColumn(name = "conversation_id")
private Conversation conversation;

public void addMessage(Message message) {


if (messages == null) {
messages = new ArrayList<>();
}
message.setInbox(this);
messages.add(message);
}
}

You might also like