0% found this document useful (0 votes)
1 views116 pages

Java Framework

This document provides a step-by-step guide for creating a Hibernate application using Maven in Eclipse, including setting up the project structure and adding necessary dependencies. It also includes source code examples for establishing a database connection, implementing XML mapping, and using annotations for mapping in Hibernate. The document outlines practical applications such as creating an Artist class and saving artist data to a database.

Uploaded by

nishantbhure753
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views116 pages

Java Framework

This document provides a step-by-step guide for creating a Hibernate application using Maven in Eclipse, including setting up the project structure and adding necessary dependencies. It also includes source code examples for establishing a database connection, implementing XML mapping, and using annotations for mapping in Hibernate. The document outlines practical applications such as creating an Artist class and saving artist data to a database.

Uploaded by

nishantbhure753
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Name: Vansh Singh

Class: TYCS C
Roll no: 9179

PRACTICAL 1
AIM : Demonstration to create First Hibernate Application using Maven Project

Define the stepwise demonstration to create a new application in Eclipse which should be
HIbernate application by using Maven Project

Steps:

To create a new application in Eclipse , follow these steps


Step 1. Open Eclipse to start your project .
Step 2. Click on file, choose maven project.

Step 3. This should open a page where you can choose the location of the file to be saved ,
choose your files location and click on Next .

Step 4. On the next page archetype will be pre selected by the software , click on the Next
Button.

Name: Vansh Singh


Class: TYCS C
Roll no: 9179

Step 5. On the next step you have to set up Group ID as “[Link]” and Artifact ID as “your
name” . Here your package name will automatically become a combination of Group ID &
Artifact ID .
Name: Vansh Singh
Class: TYCS C
Roll no: 9179

Step 6. Click on Finish , this should begin the process of creating your maven project. Step 7.
Console will show a message for which conformation has to be given for your project by
entering “Y” character and Enter key . project will be created and will appear in the project
explorer.

Step 8. Project folder will have the following predefined folders in it.
● src/main/java this folder contains packages created for current project
● Inside the package it will have a predefined utility class
● Maven dependency folder contains all the packages and jar files required for the current
project.
● [Link] This contains the dependencies tag which allows the developers to add new
required dependencies.

Name: Vansh Singh


Class: TYCS C
Roll no: 9179

Step 9. To add dependencies of maven.


● Go to web browser search for “ Dependencies for maven project hibernate core” here
hibernate core will have basic functionality of hibernate applications .
● This should show you a list of dependencies , click on stable version this will open a page
which contains dependencies tag copy that and paste setting at [Link] .

Name: Vansh Singh


Class: TYCS C
Roll no: 9179

PRACTICAL 2
AIM : Demonstrates how to establish a connection with a database using Hibernate
SessionFactory.

Source code:

[Link] :

<?xml version="1.0" encoding="UTF-8"?>


<project xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="[Link]
[Link]
<modelVersion>4.0.0</modelVersion>

<groupId>[Link]</groupId>
<artifactId>vansh9179</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>vansh9179</name>

<properties>
<[Link]>UTF-8</[Link]>
<[Link]>17</[Link]>
</properties>

<dependencyManagement>
<dependencies>
<dependency>
<groupId>[Link]</groupId>
<artifactId>junit-bom</artifactId>
<version>5.11.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

<dependencies>
<dependency>
<groupId>[Link]</groupId>

<artifactId>junit-jupiter-api</artifactId>
<scope>test</scope>
</dependency>

<!-- Hibernate Core -->


<dependency>
<groupId>[Link]</groupId>
<artifactId>hibernate-core</artifactId>
<version>[Link]</version>
</dependency>

<!-- MySQL Connector -->


<dependency>
<groupId>[Link]</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.2.0</version>
</dependency>
<!-- Optionally: parameterized tests support -->
<dependency>
<groupId>[Link]</groupId>
<artifactId>junit-jupiter-params</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to
parent pom) -->
<plugins>
<!-- clean lifecycle, see
[Link] -->
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.4.0</version>
</plugin>
<!-- default lifecycle, jar packaging: see
[Link]
ng -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.3.1</version>
Name: Vansh Singh
Class: TYCS C
Roll no: 9179

</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.13.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>3.3.0</version>
</plugin>
<plugin>
<artifactId>maven-jar-plugin</artifactId>
<version>3.4.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>3.1.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>3.1.2</version>
</plugin>
<!-- site lifecycle, see
[Link] -->
<plugin>
<artifactId>maven-site-plugin</artifactId>
<version>3.12.1</version>
</plugin>
<plugin>
<artifactId>maven-project-info-reports-plugin</artifactId>
<version>3.6.1</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>

[Link] :
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
Name: Vansh Singh
Class: TYCS C
Roll no: 9179

"[Link]
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">[Link]</property>
<property name="[Link]">jdbc:mysql://localhost:3306/9179</property>
<property name="[Link]">root</property>
<property name="[Link]">12345</property>
<property name="dialect">[Link].MySQL8Dialect</property>
<property name="[Link]">update</property>
<property name="show_sql">true</property>
</session-factory>
</hibernate-configuration>

[Link] :
package [Link].m65;
import [Link];
import [Link];
import [Link];
public class AppTest {
public static void main(String[] args) {
[Link]("Main method started");
SessionFactory factory = new Configuration().configure("[Link]")
.buildSessionFactory();
// Open session
Session session = [Link]();
[Link]("Session started");
// Close session and factory
[Link]();
[Link]("Session closed");

[Link]();
[Link]("SessionFactory closed");
}
}

OUTPUT :
Name: Vansh Singh
Class: TYCS C
Roll no: 9179
Name: Vansh Singh
Class: TYCS C
Roll no: 9179

PRACTICAL 3
AIM : Design simple application using hibernate to show the implementation of XML
Mapping. (Create Artist Class with Artist_Id as PK ,Artist_Name , Artist_Genre)

Source code:

[Link]

public class Artist {


private int artistId;
private String artistName;
private String artistGenre;

public Artist() {}
public Artist(String artistName, String artistGenre) {
[Link] = artistName;
[Link] = artistGenre;
}
public int getArtistId() {
return artistId;
}
private void setArtistId(int artistId) {
[Link] = artistId;
}
public String getArtistName() {
return artistName;
}
public void setArtistName(String artistName) {
[Link] = artistName;
}
public String getArtistGenre() {
return artistGenre;
}
public void setArtistGenre(String artistGenre) {
[Link] = artistGenre;
}
}
Name: Vansh Singh
Class: TYCS C
Roll no: 9179

[Link]

<?xml version="1.0" encoding="utf-8"?>


<hibernate-mapping>
<class name="Artist" table="Artist">
<id name="artistId" column="artist_id">
<generator class="identity"/>
</id>
<property name="artistName" column="artist_name" not-null="true" length="50"/>
<property name="artistGenre" column="artist_genre" not-null="true" length="50"/>
</class>
</hibernate-mapping>

[Link]
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">[Link]</property>
<property
name="[Link]">jdbc:mysql://localhost:3306/artist9179?useSSL=false&amp;serverTimez
one=UTC</property>
<property name="[Link]">root</property>
<property name="[Link]">12345</property>
<property name="connection.pool_size">10</property>
<property name="dialect">[Link].MySQL8Dialect</property>
<property name="[Link]">update</property>
<property name="show_sql">true</property>

<mapping resource="[Link]"/>
</session-factory>
</hibernate-configuration>

[Link]

import [Link];
import [Link];
import [Link];
Name: Vansh Singh
Class: TYCS C
Roll no: 9179

public class HibernateApp {

public static void main(String[] args) {


SessionFactory factory = new Configuration()
.configure("[Link]")
.buildSessionFactory();

Session session = [Link]();

try {
Artist artist = new Artist("Sabrina Carpenter", "Pop");
Artist artist1 = new Artist("The Weeknd", "Rock");
[Link]();
[Link](artist);
[Link](artist1);
[Link]().commit();
[Link]("Artist saved successfully!");
} finally {
[Link]();
}
}
}

[Link]

<?xml version="1.0" encoding="UTF-8"?>


<project xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="[Link]
[Link]
<modelVersion>4.0.0</modelVersion>

<groupId>[Link]</groupId>
<artifactId>vansh9179</artifactId>
<version>0.0.1-SNAPSHOT</version>
Name: Vansh Singh
Class: TYCS C
Roll no: 9179

<name>vansh9179</name>
<!-- FIXME change it to the project's website -->
<url>[Link]

<properties> <[Link]>UTF-8</[Link]>
<[Link]>17</[Link]>
</properties>

<dependencyManagement>
<dependencies>
<dependency>
<groupId>[Link]</groupId>
<artifactId>junit-bom</artifactId>
<version>5.11.0</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

<dependencies>
<dependency>
<groupId>[Link]</groupId>
<artifactId>junit-jupiter-api</artifactId>
<scope>test</scope>
</dependency>

<!-- Hibernate Core -->


<dependency>
<groupId>[Link]</groupId>
<artifactId>hibernate-core</artifactId>
<version>[Link]</version>
</dependency>

<!-- MySQL Connector -->


<dependency>

<groupId>[Link]</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.2.0</version>
</dependency>
<!-- Optionally: parameterized tests support -->
<dependency>
<groupId>[Link]</groupId>
<artifactId>junit-jupiter-params</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
OUTPUT:
PRACTICAL 4 Name: Vansh Singh
Class: TYCS C
Roll no: 9179

AIM : Design a simple application using hibernate mapping with Annotations.

1. Design a hibernate application to save the data in Artist Table(Id,Name,Album_Name)


using annotation mapping.

Source code:

[Link]
import [Link].*;

@Entity
@Table(name = "Artist")
public class Artist4 {

@Id
@GeneratedValue(strategy = [Link])
private int id;
@Column(name = "name", nullable = false, length = 50)
private String name;

@Column(name = "album_name", nullable = false, length = 50)


private String albumName;

public Artist4() {}

public Artist4(String name, String albumName) {


[Link] = name;
[Link] = albumName;
}

public int getId() { return id; }


public void setId(int id) { [Link] = id; }
Name: Vansh Singh
Class: TYCS C
Roll no: 9179

public String getName() { return name; }


public void setName(String name) { [Link] = name; }

public String getAlbumName() { return albumName; }


public void setAlbumName(String albumName) { [Link] = albumName; } }

[Link]
import [Link];
import [Link];
import [Link];

public class HibernateApp {

public static void main(String[] args) {


SessionFactory factory = new Configuration()
.configure("[Link]")
.addAnnotatedClass([Link])
.buildSessionFactory();
// Create session
Session session = [Link]();

try {
Artist4 artist = new Artist4("Sabrina Carpenter", "Manchild");
Artist4 artist1 = new Artist4("The Weeknd", "Starboy");

[Link]();
[Link](artist);
[Link](artist1);
[Link]().commit();
[Link]("Artist saved successfully!");
} finally {
[Link]();
}
}
Name: Vansh Singh
Class: TYCS C
Roll no: 9179

[Link]
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">[Link]</property>
<property
name="[Link]">jdbc:mysql://localhost:3306/artist9179?useSSL=false&amp;serverTimez
one=UTC</property>
<property name="[Link]">root</property>
<property name="[Link]">12345</property>
<property name="connection.pool_size">10</property>
<property name="dialect">[Link].MySQL8Dialect</property>
<property name="[Link]">update</property>
<property name="show_sql">true</property>

<mapping class="Artist4"/>
</session-factory>
</hibernate-configuration>
[Link]
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="[Link]
[Link]
<modelVersion>4.0.0</modelVersion>

<groupId>[Link]</groupId>
<artifactId>vansh9179</artifactId>
<version>0.0.1-SNAPSHOT</version>

<name>vansh9179</name>
<properties>
<[Link]>UTF-8</[Link]>
<[Link]>17</[Link]>
</properties>
Name: Vansh Singh
Class: TYCS C
Roll no: 9179

<!-- Hibernate Core -->


<dependency>
<groupId>[Link]</groupId>
<artifactId>hibernate-core</artifactId>
<version>[Link]</version>
</dependency>

<!-- MySQL Connector -->


<dependency>
<groupId>[Link]</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.2.0</version>
</dependency>
<!-- Optionally: parameterized tests support -->
<dependency>
<groupId>[Link]</groupId>
<artifactId>junit-jupiter-params</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

OUTPUT :

Name: Vansh Singh


Class: TYCS C
Roll no: 9179

2. Design a hibernate application to save the data in Admission


Table(Admission_Id,Student_Name,Address) using annotation mapping

[Link]

import [Link].*;

@Entity
@Table(name = "Admission9179")
public class Admission {
@Id
@GeneratedValue(strategy = [Link])
private int admissionId;

@Column(name = "student_name", nullable = false, length = 50)


private String studentName;

@Column(name = "address", nullable = false, length = 100)


private String address;

public Admission() {}

public Admission(String studentName, String address) {


[Link] = studentName;
[Link] = address;
}
Name: Vansh Singh
Class: TYCS C
Roll no: 9179

public int getAdmissionId() { return admissionId; }


public void setAdmissionId(int admissionId) { [Link] = admissionId; }

public String getStudentName() { return studentName; }


public void setStudentName(String studentName) { [Link] = studentName; }

public String getAddress() { return address; }


public void setAddress(String address) { [Link] = address; }
}

[Link]

import [Link];
import [Link];
import [Link];

public class HibernateApp {


public static void main(String[] args) {
// Create SessionFactory
SessionFactory factory = new Configuration()
.configure("[Link]")
.addAnnotatedClass([Link])
.buildSessionFactory();

// Create session
Session session = [Link]();

try {
Admission admission = new Admission("Meenakshi", "Kharghar");
Admission admission1 = new Admission("Vaishnav", "Dombivali");

[Link]();
[Link](admission);
[Link](admission1);
[Link]().commit();
Name: Vansh Singh
Class: TYCS C
Roll no: 9179

[Link]("Admission saved successfully!");


} finally {
[Link]();
}
}
}

[Link]

<hibernate-configuration>
<session-factory> <property
name="connection.driver_class">[Link]</property> <property
name="[Link]">jdbc:mysql://localhost:3306/admission1?useSSL=false&amp;serverTim
ezone=UTC</property>
<property name="[Link]">root</property>
<property name="[Link]">12345</property>
<property name="connection.pool_size">10</property>
<property name="dialect">[Link].MySQL8Dialect</property>
<property name="[Link]">update</property>
<property name="show_sql">true</property>

<mapping class="Admission"/>
</session-factory>
</hibernate-configuration>

[Link]
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="[Link]
[Link]
<modelVersion>4.0.0</modelVersion>

<groupId>[Link]</groupId>
Name: Vansh Singh
Class: TYCS C
Roll no: 9179

<artifactId>vansh9179</artifactId>
<version>0.0.1-SNAPSHOT</version>

<name>vansh9179</name>
<properties>
<[Link]>UTF-8</[Link]>
<[Link]>17</[Link]>
</properties>

<!-- Hibernate Core -->


<dependency>
<groupId>[Link]</groupId>
<artifactId>hibernate-core</artifactId>
<version>[Link]</version>
</dependency> <!-- MySQL Connector -->
<dependency>
<groupId>[Link]</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.2.0</version>
</dependency>
<!-- Optionally: parameterized tests support -->
<dependency>
<groupId>[Link]</groupId>
<artifactId>junit-jupiter-params</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

OUTPUT :
Name: Vansh Singh
Class: TYCS C
Roll no: 9179
Name: Vansh Singh
Class: TYCS C
Roll no: 9179

PRACTICAL - 5

AIM : Demonstration of Hibernate Lifecycle


1. Create hibernate application to demonstrate the hibernate lifecycle using
Annotation Mapping

Source Code :

[Link]

import [Link].*;

@Entity
@Table(name = "Artist9143")
public class Artist {

@Id
@GeneratedValue(strategy = [Link])
private int id;

@Column(name = "name", nullable = false, length = 50)


private String name;

@Column(name = "album_name", nullable = false, length = 100)


private String albumName;

public Artist() {}

public Artist(String name, String albumName) {


[Link] = name;
[Link] = albumName;
}

public int getId() { return id; }


public void setId(int id) { [Link] = id; }
Name: Vansh Singh
Class: TYCS C
Roll no: 9179

public String getName() { return name; }


public void setName(String name) { [Link] = name; }

public String getAlbumName() { return albumName; }


public void setAlbumName(String albumName) { [Link] = albumName; }

@Override
public String toString() {
return "Artist [id=" + id + ", name=" + name + ", albumName=" +
albumName + "]"; } }

[Link]

<hibernate-configuration>
<session-factory>
<property
name="connection.driver_class">[Link]</property>
<property
name="[Link]">jdbc:mysql://localhost:3306/artist?useSSL=false&amp;server
Timezone= UTC</property>
<property name="[Link]">root</property>
<property name="[Link]">12345</property>
<property name="connection.pool_size">10</property>
<property
name="dialect">[Link].MySQL8Dialect</property>
<property name="[Link]">update</property>
<property name="show_sql">true</property>

<mapping class="Artist"/>
</session-factory>
</hibernate-configuration>

[Link]

import [Link];
Name: Vansh Singh
Class: TYCS C
Roll no: 9179

import [Link];
import [Link];

public class HibernateLifecycleDemo {

public static void main(String[] args) {


Configuration config = new Configuration();\
[Link]("[Link]");
[Link]([Link]);
SessionFactory factory = [Link]();

// 1. Transient state
Artist artist = new Artist("The Weeknd", "Timeless");
[Link]("1. Transient state: Created artist object: " + artist);
Session session = [Link]();
[Link]();

// 2. Persistent state
[Link](artist);
[Link]("2. Persistent state: Artist saved, assigned ID = " + [Link]());

[Link]("The Weeknd Updated");


[Link]("2. Persistent state: Updated artist name to: " + [Link]());

[Link]().commit();
[Link]();
[Link]("Transaction committed and session closed. Artist is now detached.");

// 3. Detached state
[Link]("The Weeknd Detached");
[Link]("3. Detached state: Modified detached artist
name to: " + [Link]());

session = [Link]();
[Link]();
Name: Vansh Singh
Class: TYCS C
Roll no: 9179

// 4. Persistent state (reattached)


[Link](artist);
[Link]("4. Persistent state (reattached): Artist reattached to session with
name: " + [Link]());

// 5. Removed state
[Link](artist);

[Link]("5. Removed state: Artist marked for deletion.");


[Link]().commit();
[Link]();
[Link]("Transaction committed and session closed after
deletion."); [Link]();
[Link]("SessionFactory closed.");
}
}

[Link]

<?xml version="1.0" encoding="UTF-8"?>


<project xmlns="[Link]
xmlns:xsi="[Link]
xsi:schemaLocation="[Link]
[Link]
<modelVersion>4.0.0</modelVersion>

<groupId>[Link]</groupId>
<artifactId>anoushka9143</artifactId>
<version>0.0.1-SNAPSHOT</version>

<name>anoushka9143</name>
<!-- FIXME change it to the project's website -->
<url>[Link]

<properties>
Name: Vansh Singh
Class: TYCS C
Roll no: 9179

<[Link]>UTF-8</[Link]
Encoding>
<[Link]>17</[Link]>
</properties>

<dependencyManagement>
<dependencies>
<dependency>
<groupId>[Link]</groupId>
<artifactId>junit-bom</artifactId>
<version>5.11.0</version>
<type>pom</type>
<scope>import</scope>

</dependency>
</dependencies>
</dependencyManagement>

<dependencies>
<dependency>
<groupId>[Link]</groupId>
<artifactId>junit-jupiter-api</artifactId>
<scope>test</scope>
</dependency>

<!-- Hibernate Core -->


<dependency>
<groupId>[Link]</groupId>
<artifactId>hibernate-core</artifactId>
<version>[Link]</version>
</dependency>

<!-- MySQL Connector -->


<dependency>
<groupId>[Link]</groupId>
Name: Vansh Singh
Class: TYCS C
Roll no: 9179

<artifactId>mysql-connector-j</artifactId>
<version>8.2.0</version>
</dependency>

OUTPUT :
2. Create a hibernate application to demonstrate the hibernate lifecycle using xml
[Link]

public class Admission {


private int admissionid;
private String studentName;

public Admission() {}

public Admission(String studentName) {


[Link] = studentName;
}

public int getAdmissionId() { return admissionid; }


public void setAdmissionId(int admissionId) { [Link] =

admissionId; } public String getStudentName() { return studentName;

Name: Vansh Singh


Class: TYCS C
Roll no: 9179
public void setStudentName(String studentName) { [Link] = studentName; }

@Override
public String toString() {
return "admission{id=" + admissionid + ", studentName='" +
studentName + "'}"; } }

[Link]

<?xml version="1.0" encoding="UTF-8"?>

<hibernate-mapping>
<class name="Admission" table="admission9143">
<id name="admissionId" column="id">
<generator class="identity"/>
</id>
<property name="studentName" column="student_name"/>

</class>
</hibernate-mapping>

[Link]

import [Link];
import [Link];
import [Link];
import [Link];

public class HibernateLifecycleDemo {

public static void main(String[] args) {


// Create SessionFactory
SessionFactory factory = new Configuration().configure().buildSessionFactory();
Name: Vansh Singh
Class: TYCS C
Roll no: 9179
// 1. Transient state
Admission admission = new Admission ("Anoushka");
[Link]("1. Transient state: Created admission object: " +
admission); // 2. Persistent state
Session session = [Link]();
Transaction tx = [Link]();
[Link](admission);
[Link]("2. Persistent state: "
+[Link]()); [Link]();
[Link]();

// 3. Detached state
[Link]("3. Detached state: " + [Link]());

// 5. Removed state : schedule object for deletion


Session session2 = [Link]();
Transaction tx2 = [Link]();
[Link](admission);
[Link]("4. Removed State (scheduled for deletion): " + admission);

[Link]();
[Link]();
[Link]("Transaction committed and session closed after
deletion."); [Link]();
[Link]("SessionFactory closed.");
}
}

[Link]

<?xml version="1.0" encoding="UTF-8"?>


<project xmlns="[Link]
Name: Vansh Singh
Class: TYCS C
Roll no: 9179

xmlns:xsi="[Link]
xsi:schemaLocation="[Link]
[Link]
<modelVersion>4.0.0</modelVersion>

<groupId>[Link]</groupId>
<artifactId>anoushka9143</artifactId>
<version>0.0.1-SNAPSHOT</version>

<name>anoushka9143</name>
<!-- FIXME change it to the project's website -->
<url>[Link]

<properties>
<[Link]>UTF-8</[Link]
Encoding>
<[Link]>17</[Link]>
</properties>

<dependencyManagement>
<dependencies>
<dependency>
<groupId>[Link]</groupId>
<artifactId>junit-bom</artifactId>
<version>5.11.0</version>
<type>pom</type>
<scope>import</scope>
</dependency> </dependencies>
</dependencyManagement>

<dependencies>
<dependency>
<groupId>[Link]</groupId>
<artifactId>junit-jupiter-api</artifactId>
<scope>test</scope>
</dependency>
Name: Vansh Singh
Class: TYCS C
Roll no: 9179

<!-- Hibernate Core -->


<dependency>
<groupId>[Link]</groupId>
<artifactId>hibernate-core</artifactId>
<version>[Link]</version>
</dependency>

<!-- MySQL Connector -->


<dependency>
<groupId>[Link]</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.2.0</version>
</dependency>

OUTPUT :

Name: Vansh Singh


Class: TYCS C
Roll no: 9179
PRACTICAL - 6

AIM : Hibernate Mapping with Dynamic Inputs.


1. Create a hibernate application to save the Artist class details entered by the
user(Id, name , Album_Name) using Annotation Mapping.

Source Code :

[Link] :
package [Link].anoushka9143;

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

@Entity
@Table(name = "Artist9143")
public class Artist9143 {

@Id
@GeneratedValue(strategy = [Link])
private int id;

@Column(name = "name", nullable = false, length = 50)


private String artistName;

@Column(name = "album_name", nullable = false, length = 100)


private String albumName;

public Artist9143) {}

public Artist9143(String name, String albumName) {


[Link] = name;
[Link] = albumName;
}
Name: Vansh Singh
Class: TYCS C
Roll no: 9179

public int getId() { return id; }


public void setId(int id) { [Link] = id; }

public String getName() { return artistName; }


public void setName(String name) { [Link] = name; }

public String getAlbumName() { return albumName; }


public void setAlbumName(String albumName) { [Link] = albumName; }

@Override
public String toString() {
return "Artist [id=" + id + ", name=" + artistName + ", albumName=" +
albumName + "]"; }
}

[Link] :
package [Link].anoushka9143;

import [Link];
import [Link];
import [Link];
import [Link];

public class App9143 {


public static void main(String[] args) {
Scanner scanner = new Scanner([Link]);

[Link]("Enter artist name: ");


String artistName = [Link]();

[Link]("Enter album name: ");


String albumName = [Link]();

Configuration config = new Configuration();


[Link]("[Link]");
[Link]([Link]);

SessionFactory factory = [Link]();


Name: Vansh Singh
Class: TYCS C
Roll no: 9179

// 1. Transient state
Artist9143 artist = new Artist9143();
[Link](artistName);
[Link](albumName);

[Link]("1. Transient state: Created artist object: Name = "


+ [Link]() + ", Album = " + [Link]());

Session session = [Link]();


[Link]();

// 2. Persistent state
[Link](artist);
[Link]("2. Persistent state: Artist saved, assigned ID = " + [Link]());

[Link](artistName + " Updated");


[Link](albumName + " Vol 2");
[Link]("2. Persistent state: Updated artist details to: "
+ [Link]() + ", " + [Link]());

[Link]().commit();
[Link]();
[Link]("Transaction committed and session closed. Artist is now detached.");

// 3. Detached state
[Link](artistName + " Detached");
[Link](albumName + " Final");
[Link]("3. Detached state: Modified detached
artist: Name = " + [Link]() + ", Album = " +
[Link]());

session = [Link]();
[Link]();

// 4. Persistent state (reattached)


[Link](artist);
[Link]("4. Persistent state (reattached): Artist reattached
to session: " + [Link]());
Name: Vansh Singh
Class: TYCS C
Roll no: 9179

// 5. Removed state
[Link](artist);
[Link]("5. Removed state: Artist marked for deletion.");

[Link]().commit();
[Link]();
[Link]("Transaction committed and session closed after deletion.");

[Link]();
[Link]("SessionFactory closed.");

[Link]();

}
}

[Link] :
<!-- Hibernate Core -->
<dependency>
<groupId>[Link]</groupId>
<artifactId>hibernate-core</artifactId>
<version>[Link]</version>
</dependency>

<!-- MySQL Connector -->


<dependency>
<groupId>[Link]</groupId>
<artifactId>mysql-connector-j</artifactId>
<version>8.2.0</version>
</dependency>
<!-- Optionally: parameterized tests support -->
<dependency>
<groupId>[Link]</groupId>
<artifactId>junit-jupiter-params</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>[Link]</groupId>
Name: Vansh Singh
Class: TYCS C
Roll no: 9179

<artifactId>[Link]-api</artifactId>
<version>2.2</version>
</dependency>

[Link] :
<hibernate-configuration>
<session-factory>
<property
name="connection.driver_class">[Link]</property
> <property
name="[Link]">jdbc:mysql://localhost:3306/9143?useSSL=false&amp;serverTimezon
e=UTC</p roperty>
<property name="[Link]">root</property>
<property name="[Link]">12345</property>
<property name="connection.pool_size">10</property>
<property name="dialect">[Link].MySQL8Dialect</property>
<property name="[Link]">update</property>
<property name="show_sql">true</property>

<mapping class="[Link].anoushka9143.Artist9143"/>
</session-factory>
</hibernate-configuration>

OUTPUT :
2. Create a hibernate application to save the Admission class details entered by
user (Id,
Name: Vansh Singh
Class: TYCS C
Roll no: 9179

StudentName) using XML Mapping.

Source Code :

[Link] :

package [Link].anoushka9143;

public class Admission9143 {


private int id;
private String studentName;
public Admission9143() {}

public Admission9143(String studentName) {


[Link] = studentName;
}

public int getId() {


return id;
}

public void setId(int id) {


[Link] = id;
}

public String getStudentName() {


return studentName;
}

public void setStudentName(String studentName) {


[Link] = studentName;
}

@Override
public String toString() {
return "Admission9143{id=" + id + ", studentName='" +
studentName + "'}"; }
}
Name: Vansh Singh
Class: TYCS C
Roll no: 9179

[Link] :

package [Link].anoushka9143;

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class App9143 {


public static void main(String[] args) {
SessionFactory factory = new
Configuration().configure().buildSessionFactory(); Scanner sc = new
Scanner([Link]);

[Link]("Enter Student Name: ");


String studentName = [Link]();

Admission9143 adm = new Admission9143(studentName);


[Link]("1. Transient State: " + adm);

Session session = [Link]();


Transaction tx = [Link]();
[Link](adm);

[Link]("2. Persistent State: " + adm);


[Link]();
[Link]();

[Link]("3. Detached State: " + adm);

Session session2 = [Link]();


Transaction tx2 = [Link]();
[Link](adm);
[Link]("4. Removed State (scheduled for deletion): " + adm);
[Link]();
[Link]();
Name: Vansh Singh
Class: TYCS C
Roll no: 9179

[Link]();
[Link]();
}
}

[Link] :

<?xml version="1.0" encoding="UTF-8"?>


<hibernate-configuration>
<session-factory>
<!-- JDBC connection properties -->
<property
name="connection.driver_class">[Link]</property
> <property
name="[Link]">jdbc:mysql://localhost:3306/9143?useSSL=false&amp;serverTimezon
e=UTC</p roperty>
<property name="[Link]">root</property>
<property name="[Link]">12345</property>
<property name="connection.pool_size">10</property>
<property name="dialect">[Link].MySQL8Dialect</property>
<property name="[Link]">update</property>
<property name="show_sql">true</property>

<!-- Use your Admission mapping -->


<mapping resource="[Link]"/>
</session-factory>
</hibernate-configuration>

[Link] :<?xml version="1.0" encoding="utf-8"?>


<hibernate-mapping>
<class name="[Link].anoushka9143.Admission9143"
table="Admission9143"> <id name="id" column="id">
<generator class="identity"/>
</id>
<property name="studentName" column="student_name" not-null="true"
length="50"/> </class>
</hibernate-mapping>
Name: Vansh Singh
Class: TYCS C
Roll no: 9179

Name: Vansh Singh


Class: TYCS C
Roll no: 9179

PRACTICAL - 7

Aim : Inheritance mapping by using annotation

1. Create a hibernate application to demonstrate Table per class mapping using annotation

Source Code :

[Link]
package [Link].anoushka9143;

import [Link].*;

@Entity

@Table(name = "student9143")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)

@DiscriminatorColumn(name = "student_type", discriminatorType =


[Link]) public abstract class Student9143{

@Id

@GeneratedValue(strategy = [Link])

private int id;

@Column(name = "name")

private String name;

public Student9143() {}

public Student9143(String name) {

[Link] = name;

//getters and setters


Name: Vansh Singh
Class: TYCS C
Roll no: 9179

public int getId() { return id; }

public String getName() { return name; }

public void setName(String name) { [Link] = name; }}

[Link]

package [Link].anoushka9143;

import [Link].*;

@Entity

@DiscriminatorValue("Undergraduate")

public class UndergraduateStudent9143 extends Student9143 {

@Column(name = "year")
private int year;

public UndergraduateStudent9143() {}

public UndergraduateStudent9143(String name, int year) {

super(name);

[Link] = year;

//getters and setters

public int getYear() { return year; }

public void setYear(int year) { [Link] = year; }

[Link]

package [Link].anoushka9143;

import [Link].*;

@Entity
Name: Vansh Singh
Class: TYCS C
Roll no: 9179

@DiscriminatorValue("Graduate")

public class GraduateStudent9143 extends Student9143 {

@Column(name = "research_topic")

private String researchTopic;public GraduateStudent9143() {}

public GraduateStudent9143(String name, String researchTopic) {

super(name);

[Link] = researchTopic;

public String getResearchTopic() { return researchTopic; }

public void setResearchTopic(String researchTopic) { [Link] =


researchTopic; } }

[Link]

package [Link].anoushka9143;

import [Link];

import [Link];

import [Link];

import [Link];

public class App9143 {

public static void main(String[] args) {

SessionFactory factory = new Configuration()

.configure("[Link]")

.addAnnotatedClass([Link])

.addAnnotatedClass([Link])

.addAnnotatedClass([Link])

.buildSessionFactory();
Name: Vansh Singh
Class: TYCS C
Roll no: 9179

Scanner sc = new Scanner([Link]);

try {

[Link]("Enter Undergraduate Student Name: ");

String ugName = [Link]();

[Link]("Enter Undergraduate Year: ");int ugYear = [Link]();

[Link](); // clear newline

[Link]("Enter Graduate Student Name: ");

String gradName = [Link]();

[Link]("Enter Research Topic: ");

String topic = [Link]();

UndergraduateStudent9143 ugStudent = new


UndergraduateStudent9143(ugName, ugYear); GraduateStudent9143
gradStudent = new GraduateStudent9143(gradName, topic);

Session session = [Link]();

[Link]();

[Link](ugStudent);

[Link]("Inserted Undergraduate Student: " +

[Link]()); [Link](gradStudent);

[Link]("Inserted Graduate Student: " +

[Link]()); [Link]().commit();

[Link]();

[Link]("Students saved successfully!");

} finally {

[Link]();

[Link]();

}
Name: Vansh Singh
Class: TYCS C
Roll no: 9179

[Link]

<hibernate-configuration>

<session-factory>

<mapping class="[Link].anoushka9143.Student9143"/><mapping
class="[Link].anoushka9143UndergraduateStudent9143"/>

<mapping class="[Link].anoushka9143.GraduateStudent9143"/>

</session-factory>

</hibernate-configuration>

OUTPUT :
2. Create a hibernate application to demonstrateTable Per Concrete class
mapping using annotation.

Source Code :
[Link]

package [Link].anoushka9143;
Name: Vansh Singh
Class: TYCS C
Roll no: 9179

import [Link].*;

@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class Student9143 {

@Id
@GeneratedValue(strategy = [Link])
private int id;

@Column(name = "name")private String name;

public Student9143() {}

public Student9143(String name) {


[Link] = name;
}

public int getId() { return id; }

public String getName() { return name; }

public void setName(String name) { [Link] = name; }


}

[Link]
package [Link].anoushka9143;

import [Link].*;
@Entity
@Table
public class UndergraduateStudent9143 extends Student9143 {

@Column(name = "year")
private int year;

public UndergraduateStudent9143() {}

public UndergraduateStudent9143(String name, int year) {


super(name);
[Link] = year;
}

public int getYear() { return year; }


Name: Vansh Singh
Class: TYCS C
Roll no: 9179

public void setYear(int year) { [Link] = year; }


}

[Link]
package [Link].anoushka9143;
import [Link].*;

@Entity
@Table
public class GraduateStudent9143 extends Student9143 {

@Column(name = "research_topic")
private String researchTopic;
public GraduateStudent9143() {}

public GraduateStudent9143(String name, String researchTopic) {


super(name);
[Link] = researchTopic;
}

public String getResearchTopic() { return researchTopic; }

public void setResearchTopic(String researchTopic) { [Link] =


researchTopic; } }

[Link]

<hibernate-configuration>

<session-factory>

<mapping

class="[Link].anoushka9143.UndergraduateStudent9143"/>

<mapping

class="[Link].anoushka9143.GraduateStudent9143"/>

</session-factory>

</hibernate-configuration>

[Link]
package [Link].anoushka9143;
Name: Vansh Singh
Class: TYCS C
Roll no: 9179

import [Link];
import [Link];
import [Link];
import [Link];

public class App9143 {


public static void main(String[] args) {

SessionFactory factory = new Configuration()


.configure("[Link]")
.addAnnotatedClass([Link])
.addAnnotatedClass([Link])
.buildSessionFactory();

Session session = [Link]();


Scanner sc = new Scanner([Link]);

try {
// Undergraduate Student
[Link]("Enter Undergraduate Student Name: ");String ugName =
[Link](); [Link]("Enter Year: ");
int year = [Link]();
[Link](); // consume newline

// Graduate Student 1
[Link]("Enter Graduate Student 1 Name: ");
String gradName1 = [Link]();
[Link]("Enter Research Topic for Graduate Student 1: ");
String topic1 = [Link]();

// Graduate Student 2
[Link]("Enter Graduate Student 2 Name: ");
String gradName2 = [Link]();
[Link]("Enter Research Topic for Graduate Student 2: ");
String topic2 = [Link]();

UndergraduateStudent9143 ugStudent = new


UndergraduateStudent9143(ugName, year); GraduateStudent9143
gradStudent1 = new GraduateStudent9143(gradName1, topic1);
GraduateStudent9143 gradStudent2 = new GraduateStudent9143(gradName2,
topic2); [Link]();

[Link](ugStudent);
[Link]("Inserted Undergraduate Student: " +
[Link]()); [Link](gradStudent1);
Name: Vansh Singh
Class: TYCS C
Roll no: 9179

[Link]("Inserted Graduate Student 1: " + [Link]());


[Link](gradStudent2);
[Link]("Inserted Graduate Student 2: " + [Link]());
[Link]().commit();
[Link]("All records inserted successfully!");
} finally {
[Link]();
[Link]();
}
}
}

OUTPUT :

3. Create a hibernate application to demonstrateTable per subclass mapping using


annotation

SOURCE CODE :
1. [Link]
package [Link].anoushka9143;
Name: Vansh Singh
Class: TYCS C
Roll no: 9179

import [Link].*;

@Entity
@Inheritance(strategy = [Link])
@Table(name = "employee9143")
public class Employee9143 {
@Id
@GeneratedValue(strategy = [Link])
private int id;

@Column
private String name;

public Employee9143() {}

public Employee9143(String name) {


[Link] = name;
}

public int getId() { return id; }


public void setId(int id) { [Link] = id; }

public String getName() { return name; }


public void setName(String name) { [Link] = name; }
}

2. [Link]
package [Link].anoushka9143;

import [Link].*;

@Entity
@Table(name = "regular_employee9143")
@PrimaryKeyJoinColumn(name = "emp_id")
public class RegularEmployee9143 extends Employee9143 {

private float salary;


Name: Vansh Singh
Class: TYCS C
Roll no: 9179

private int bonus;

public RegularEmployee9143() {}

public RegularEmployee9143(String name, float salary, int bonus) {


super(name);
[Link] = salary;
[Link] = bonus;
}

public float getSalary() { return salary; }


public void setSalary(float salary) { [Link] = salary; }

public int getBonus() { return bonus; }


public void setBonus(int bonus) { [Link] = bonus; }
}

3. [Link]
package [Link].anoushka9143;

import [Link].*;

@Entity
@Table(name = "contract_employee9143")
@PrimaryKeyJoinColumn(name = "emp_id")
public class ContractEmployee9143 extends Employee9143 {

private float payPerHour;


private String contractDuration;

public ContractEmployee9143() {}

public ContractEmployee9143(String name, float payPerHour, String


contractDuration) { super(name);
[Link] = payPerHour;
[Link] = contractDuration;
}

public float getPayPerHour() { return payPerHour; }


public void setPayPerHour(float payPerHour) { [Link] = payPerHour; }
Name: Vansh Singh
Class: TYCS C
Roll no: 9179

public String getContractDuration() { return contractDuration; }


public void setContractDuration(String contractDuration) { [Link] =
contractDuration; } }
4. [Link]

<hibernate-configuration>

<session-factory>

<mapping class="[Link].anoushka9143.Employee9143"/>

<mapping class="[Link].anoushka9143.RegularEmployee9143"/>

<mapping class="[Link].anoushka9143.ContractEmployee9143"/>

</session-factory>

</hibernate-configuration>

5. [Link]
package [Link].anoushka9143;

import [Link];
import [Link];
import [Link];
import [Link];

public class App9143 {

public static void main(String[] args) {


SessionFactory factory = new Configuration()
.configure("[Link]")
.addAnnotatedClass([Link])
.addAnnotatedClass([Link])
.addAnnotatedClass([Link])
.buildSessionFactory();

Scanner sc = new Scanner([Link]);


Session session = [Link]();
Name: Vansh Singh
Class: TYCS C
Roll no: 9179

try {
[Link]("Enter Regular Employee Name: ");
String regName = [Link]();
[Link]("Enter Salary: ");
float salary = [Link]();
[Link]("Enter Bonus: ");
int bonus = [Link]();
[Link](); // clear buffer

[Link]("Enter Contract Employee Name: ");


String conName = [Link]();
[Link]("Enter Pay Per Hour: ");
float payPerHour = [Link]();
[Link](); // clear buffer
[Link]("Enter Contract Duration: ");
String duration = [Link]();

RegularEmployee9143 regEmp = new RegularEmployee9143(regName, salary,


bonus); ContractEmployee9143 conEmp = new ContractEmployee9143(conName,
payPerHour, duration);

[Link]();
[Link](regEmp);
[Link]("Inserted Regular Employee: " + [Link]());

[Link](conEmp);
[Link]("Inserted Contract Employee: " + [Link]());

[Link]().commit();
[Link]("All employees inserted successfully!");

} finally {

[Link]();
[Link]();
}
}
}
OUTPUT:
Name: Vansh Singh
Class: TYCS C
Roll no: 9179
Name: Vansh Singh
Class: TYCS C
Roll no: 9179

PRACTICAL - 8
Aim : List and Map Collection Mapping by Annotation

1. Demonstrate the List collection One-To-Many Mapping


[Link]
package [Link].anoushka9143;
import [Link].*;
import [Link];
import [Link];

@Entity
@Table(name = "department9143")
public class Department9143 {

@Id
@GeneratedValue(strategy = [Link])
private int id;

private String name;

@OneToMany(mappedBy = "department", cascade = [Link])


private List<Student9143> students = new ArrayList<>();

public Department9143() {}

public Department9143(String name) {


[Link] = name;
}

public int getId() { return id; }

public String getName() { return name; }


public void setName(String name) { [Link] = name; }

public List<Student9143> getStudents() { return students; }

public void addStudent(Student9143 student) {


[Link](student);
[Link](this);
}
}
Name: Vansh Singh
Class: TYCS C
Roll no: 9179

[Link]
package [Link].anoushka9143;

import [Link].*;

@Entity
@Table(name = "student9143")
public class Student9143 {

@Id
@GeneratedValue(strategy = [Link])
private int id;
private String name;

@ManyToOne
@JoinColumn(name = "department_id")
private Department9143 department;

public Student9143() {}

public Student9143(String name) {


[Link] = name;
}

public int getId() { return id; }

public String getName() { return name; }


public void setName(String name) { [Link] = name; }

public Department9143 getDepartment() { return department; }


public void setDepartment(Department9143 department) {
[Link] = department;
}
}

[Link]
package [Link].anoushka9143;

import [Link];
import [Link];
import [Link];
import [Link];
Name: Vansh Singh
Class: TYCS C
Roll no: 9179

import [Link];

public class App9143 {


public static void main(String[] args) {
SessionFactory factory = new
Configuration().configure().buildSessionFactory(); Session session =
[Link]();
Transaction tx = [Link]();
Scanner sc = new Scanner([Link]);

[Link]("Enter Department Name: ");

String deptName = [Link]();

[Link]("Enter First Student Name: ");


String s1Name = [Link]();
[Link]("Enter Second Student Name: ");
String s2Name = [Link]();

Department9143 department = new Department9143(deptName);


Student9143 s1 = new Student9143(s1Name);
Student9143 s2 = new Student9143(s2Name);

[Link](s1);
[Link](s2);

[Link](department);

[Link]();

[Link]("Inserted Department: ");


[Link]("Department ID: " + [Link]());
[Link]("Department Name: " + [Link]());
[Link]("Students: ");
for (Student9143 s : [Link]()) {
[Link](" - Student ID: " + [Link]() + ", Name: " +
[Link]()); }

[Link]();
[Link]();
[Link]();
}
}
Name: Vansh Singh
Class: TYCS C
Roll no: 9179

[Link]

<hibernate-configuration>

<session-factory>
<mapping class="[Link].anoushka9143.Department9143"/>

<mapping class="[Link].anoushka9143.Student9143"/>

</session-factory>

</hibernate-configuration>

OUTPUT :

2. Demonstrate the List collection Many-To-One Mapping


SOURCE CODE :

[Link]
package [Link].anoushka9143;

import [Link].*;
@Entity
@Table(name = "department9143")
public class Department9143 {

@Id
@GeneratedValue(strategy = [Link])
Name: Vansh Singh
Class: TYCS C
Roll no: 9179

private int id;

private String name;

public Department9143() {}
public Department9143(String name) {
[Link] = name;
}
public int getId() { return id; }

public String getName() { return name; }

public void setName(String name) { [Link] = name; }


}

[Link]
package [Link].anoushka9143;

import [Link].*;

@Entity
@Table(name = "student9143")
public class Student9143 {

@Id
@GeneratedValue(strategy = [Link])
private int id;

private String name;

@ManyToOne(cascade = [Link])
@JoinColumn(name = "department_id")
private Department9143 department;

public Student9143() {}

public Student9143(String name, Department9143 department) {


[Link] = name;
[Link] = department;
}

public int getId() { return id; }

public String getName() { return name; }


Name: Vansh Singh
Class: TYCS C
Roll no: 9179

public Department9143 getDepartment() { return department; }

public void setDepartment(Department9143 department) { [Link] =


department; } }

[Link]
package [Link].anoushka9143;

import [Link];
import [Link];
import [Link];
import [Link];

import [Link];

public class App9143{


public static void main(String[] args) {
SessionFactory factory = new
Configuration().configure().buildSessionFactory(); Session session =
[Link]();

Transaction tx = [Link]();

Scanner sc = new Scanner([Link]);

[Link]("Enter Department Name: ");


String deptName = [Link]();

Department9143 department = new Department9143(deptName);

[Link]("Enter First Student Name: ");


String studentName1 = [Link]();
Student9143 s1 = new Student9143(studentName1, department);

[Link]("Enter Second Student Name: ");


String studentName2 = [Link]();
Student9143 s2 = new Student9143(studentName2, department);

[Link](s1);
[Link](s2);
[Link]();

[Link]("\nInserted Department:");
[Link]("Department ID: " + [Link]());
[Link]("Department Name: " + [Link]());
Name: Vansh Singh
Class: TYCS C
Roll no: 9179
[Link]("Students:");
[Link](" - Student ID: " + [Link]() + ", Name: " + [Link]() +
", Department ID: " + ([Link]() != null ? [Link]().getId() :
null)); [Link](" - Student ID: " + [Link]() + ", Name: " +
[Link]() + ", Department ID: " + ([Link]() != null ?
[Link]().getId() : null));

[Link]();
[Link]();
[Link]();
}
}

[Link]
<?xml version="1.0" encoding="UTF-8"?>
<hibernate-configuration>
<session-factory>
<!-- JDBC connection properties -->
<property
name="connection.driver_class">[Link]</property
> <property
name="[Link]">jdbc:mysql://localhost:3306/m9143?useSSL=false&amp;serverTimez
one=UTC< /property>
<property name="[Link]">root</property>

<property name="[Link]">12345</property>
<property name="connection.pool_size">10</property>
<property name="dialect">[Link].MySQL8Dialect</property>
<property name="[Link]">update</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<mapping class="[Link].anoushka9143.Department9143"/>
<mapping class="[Link].anoushka9143.Student9143"/>
</session-factory>
</hibernate-configuration>

OUTPUT :
Name: Vansh Singh
Class: TYCS C
Roll no: 9179
3. Demonstrate the Map collection One-To-One Mapping
[Link]
package [Link].anoushka9143;

import [Link].*;

@Entity
@Table(name = "user9143")
public class User9143 {

@Id
@GeneratedValue(strategy = [Link])

private int id;


private String name;

@OneToOne(cascade = [Link], orphanRemoval = true)


@JoinColumn(name = "preferences_id") // FK in 'user9143' table referencing UserPreferences9143
Name: Vansh Singh
Class: TYCS C
Roll no: 9179
private UserPreferences9143 preferences;

public User9143() {}

public User9143(String name) {


[Link] = name;
}

public int getId() {


return id;
}

public String getName() {


return name;
}

public void setName(String name) {


[Link] = name;
}

public UserPreferences9143 getPreferences() {


return preferences;
}

public void setPreferences(UserPreferences9143 preferences) {


[Link] = preferences;
}
}

[Link]
package [Link].anoushka9143;

import [Link].*;
import [Link];
import [Link];

@Entity
@Table(name = "user_preferences9143")

public class UserPreferences9143 {


Name: Vansh Singh
Class: TYCS C
Roll no: 9179

@Id
@GeneratedValue(strategy = [Link])
private int id;

@ElementCollection
@CollectionTable(
name = "user_preferences_map9143",
joinColumns = @JoinColumn(name = "user_preferences_id")
)
@MapKeyColumn(name = "preference_type")
@Column(name = "preference_value")
private Map<String, String> preferences = new HashMap<>();

public UserPreferences9143() {}

public int getId() {


return id;
}

public Map<String, String> getPreferences() {


return preferences;
}

public void setPreferences(Map<String, String> preferences) {


[Link] = preferences;
}
}

[Link]
package [Link].anoushka9143;

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class App9143 {


public static void main(String[] args) {
Name: Vansh Singh
Class: TYCS C
Roll no: 9179

Configuration configuration = new Configuration().configure();


[Link]([Link]);

[Link]([Link]);

SessionFactory sessionFactory = [Link]();


Session session = [Link]();
Transaction tx = [Link]();

Scanner sc = new Scanner([Link]);


[Link]("Enter User Name: ");
String userName = [Link]();

[Link]("Enter first preference type: ");


String prefType1 = [Link]();
[Link]("Enter first preference value: ");
String prefValue1 = [Link]();

[Link]("Enter second preference type: ");


String prefType2 = [Link]();
[Link]("Enter second preference value: ");
String prefValue2 = [Link]();

User9143 user = new User9143(userName);


UserPreferences9143 preferences = new UserPreferences9143();
[Link]().put(prefType1, prefValue1);
[Link]().put(prefType2, prefValue2);

[Link](preferences);

[Link](user);

[Link]();
[Link]();
[Link]();
[Link]();

[Link]("User with preferences saved successfully!");


}
Name: Vansh Singh
Class: TYCS C
Roll no: 9179

[Link]
<?xml version="1.0" encoding="UTF-8"?>
<hibernate-configuration>
<session-factory>
<mapping class="[Link].anoushka9143.User9143"/>

<mapping class="[Link].anoushka9143.UserPreferences9143"/>
</session-factory>
</hibernate-configuration>

OUTPUT :

4. Demonstrate the Map collection Many-To-Many Mapping


Source Code:
[Link]
package [Link].anoushka9143;

import [Link];
import [Link];
import [Link];
import [Link];
Name: Vansh Singh
Class: TYCS C
Roll no: 9179

import [Link];

public class App9143 {


public static void main(String[] args) {
Configuration configuration = new Configuration().configure();
[Link]([Link]);
[Link]([Link]);
[Link]([Link]);

SessionFactory sessionFactory = [Link]();


Session session = [Link]();
Transaction tx = [Link]();
Scanner scanner = new Scanner([Link]);

[Link]("Enter first employee name: ");String empName1 =


[Link](); [Link]("Enter second employee name: ");
String empName2 = [Link]();
[Link]("Enter project name: ");
String projectName = [Link]();
[Link]("Enter role for " + empName1 + ": ");
String role1 = [Link]();
[Link]("Enter role for " + empName2 + ": ");
String role2 = [Link]();

Employee9143 emp1 = new Employee9143(empName1);


Employee9143 emp2 = new Employee9143(empName2);
[Link](emp1);
[Link](emp2);

Project9143 project = new Project9143(projectName);


[Link](emp1, role1);
[Link](emp2, role2);

[Link](project);

[Link]();
[Link]();
[Link]();
[Link]();
Name: Vansh Singh
Class: TYCS C
Roll no: 9179

[Link]("Saved project with employee roles!");


}
}

[Link]
package [Link].anoushka9143;

import [Link].*;

@Entity
@Table(name = "employee9143")
public class Employee9143 {

@Id
@GeneratedValue(strategy = [Link])
private Integer id;

private String name;

public Employee9143() {}

public Employee9143(String name) {


[Link] = name;
}

public Integer getId() { return id; }

public String getName() { return name; }

public void setName(String name) { [Link] = name; }


}

[Link]
package [Link].anoushka9143;

import [Link].*;
import [Link];
import [Link];
@Entity
@Table(name = "project")
public class Project9143 {
Name: Vansh Singh
Class: TYCS C
Roll no: 9179

@Id
@GeneratedValue(strategy = [Link])
private Integer id;

private String name;

@ElementCollection
@CollectionTable(
name = "project_employee_role",
joinColumns = @JoinColumn(name = "project_id")
)
@MapKeyJoinColumn(name = "employee_id")
@Column(name = "role")
private Map<Employee9143, String> employeeRoles = new

HashMap<>(); public Project9143() {}

public Project9143(String name) {


[Link] = name;
}

public Integer getId() { return id; }


public String getName() { return name; }
public void setName(String name) { [Link] = name; }
public Map<Employee9143, String> getEmployeeRoles() { return
employeeRoles; } public void setEmployeeRoles(Map<Employee9143,
String> employeeRoles) {
[Link] = employeeRoles;
}
}

[Link]
<?xml version="1.0" encoding="UTF-8"?>
<hibernate-configuration>
<session-factory>
<!-- JDBC connection properties -->
<mapping class="[Link].anoushka9143.Employee9143"/>
<mapping class="[Link].anoushka9143.Project9143"/>
</session-factory>
</hibernate-configuration>
OUTPUT :
Name: Vansh Singh
Class: TYCS C
Roll no: 9179

Vansh Singh
TYCS ‘C’
9179

Practical 9
Aim: Retrieve data by using HQL.a Student and Department table
with a Many-to-One mapping.
[Link] all students.
Code:
[Link]
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class App {
public static void main(String[] args) {
SessionFactory factory = new
Configuration().configure().buildSessionFactory(); Session session =
[Link]();
[Link]();
String hql = "FROM Student";
List<Student> students = [Link](hql, [Link]).list(); for
(Student s : students) {
[Link]("ID : " + [Link]());
[Link]("Name : " + [Link]());
[Link]("Age : " + [Link]());
[Link]("Email : " + [Link]());
[Link]("Course : " + [Link]());
[Link]("----------------------------------");
}
[Link]().commit();
[Link]();
[Link]();
}
}

[Link]
package [Link].practical9;
import [Link].*;
@Entity
public class Department {
@Id
@GeneratedValue(strategy = [Link])
private int id;
private String name;
public Department() {}
public Department(String name) {
[Link] = name;
}
public int getId() {
VanshSingh
TYCS ‘C’
9179
return id;
}
public void setId(int id){

[Link]= id;
}
public String getName(){
return name;
}
public void setName(String name){
[Link]= name;
}
}
[Link]
package [Link].practical9;
import [Link].*;
@Entity
public class Student{
@Id
@GeneratedValue(strategy= [Link])
private int id;
private String name;
private int age;
@ManyToOne
@JoinColumn(name= "department_id")
private Department department;
public Student() {}
public Student(String name, int age, Department department){
[Link]= name;
[Link]= age;
[Link]= department;
}
public int getId(){
return id;
}
public void setId(int id){
[Link]= id;
}
public String getName(){
return name;
}
public void setName(String name){
[Link]= name;
}
public int getAge(){
return age;
}
public void setAge(int age){
[Link]= age;
Vansh Singh
TYCS ‘C’
9179
}
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
[Link] = department;
}
}
[Link])
<mapping class="Department"/>
<mapping class="Student"/>
Output:

2.
Get students from a specific department name (e.g., "Computer
Science") Code;
[Link]
package [Link].practical9;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class App {
public static void main(String[] args) {
SessionFactory factory = new Configuration()
.configure("[Link]")
.addAnnotatedClass([Link])
.addAnnotatedClass([Link])
.buildSessionFactory();
Session session = [Link]();
[Link]();
Query<Student> query = [Link](
"FROM Student s WHERE [Link] = :deptName",
[Link]); [Link]("deptName", "CS");
List<Student> students = [Link]();
for (Student s : students) {
[Link]("Name : " + [Link]());
Vansh Singh
TYCS ‘C’
9179
[Link]("Age : " + [Link]());
[Link]("Department: " + [Link]().getName());
[Link]("----------------------------------");
}
[Link]().commit();
[Link]();
[Link]();
}
}
Output:

3. Get average age of students


Code:
[Link]
package [Link].practical9;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class App {
public static void main(String[] args) {
SessionFactory factory = new Configuration()
.configure("[Link]")
.addAnnotatedClass([Link])
.addAnnotatedClass([Link])
.buildSessionFactory();
Session session = [Link]();
[Link]();
Query query = [Link]("SELECT AVG([Link]) FROM
Student s"); Double avgAge = (Double) [Link]();
[Link]("Avarage Age:" +avgAge);
[Link]().commit();
[Link]();
[Link]();
}
Vansh Singh
TYCS ‘C’
9179
}
Output:

4. Get students ordered by age descending


[Link]
package [Link].practical9;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class App {
public static void main(String[] args) {
SessionFactory factory = new Configuration()
.configure("[Link]")
.addAnnotatedClass([Link])
.addAnnotatedClass([Link])
.buildSessionFactory();
Session session = [Link]();
[Link]();
Query query = [Link]("FROM Student s ORDER BY [Link]
DESC"); List<Student> students = [Link]();// Print students
for (Student s : students) {
[Link]("Name : " + [Link]());
[Link]("Age : " + [Link]());
[Link]("----------------------------------");
}
[Link]().commit();
[Link]();
[Link]();
}
}
Output:

Vansh Singh
TYCS ‘C’
9179

5. Get departments with more than 1 student (using group by)


[Link]
package [Link].practical9;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class App {
public static void main(String[] args) {

SessionFactory factory = new Configuration()


.configure("[Link]")
.addAnnotatedClass([Link])
.addAnnotatedClass([Link])
.buildSessionFactory();
Session session = [Link]();
[Link]();
Query query = [Link]("SELECT [Link], COUNT(s)
FROM Student s GROUP BY [Link] HAVING COUNT(s) > 1");
List<Object[]> results = [Link]();
for (Object[] row: results) {
[Link]("Department : " +row[0]+",Students:"+row[1]);
[Link]("----------------------------------");
}
[Link]().commit();
[Link]();
[Link]();
}
}
Output:
Vansh Singh
TYCS ‘C’
9179

6. Get students between age 18 and 25


[Link]
package [Link].practical9;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class App {
public static void main(String[] args) {
SessionFactory factory = new Configuration()
.configure("[Link]")
.addAnnotatedClass([Link])
.addAnnotatedClass([Link])
.buildSessionFactory();
Session session = [Link]();
[Link]();
Query query = [Link]("FROM Student s WHERE [Link]
BETWEEN 18 AND 25");
List<Student> students = [Link]();
for (Student s: students) {
[Link]("Name : " +[Link]());
[Link]("Age : " +[Link]());
[Link]("----------------------------------");
}
[Link]().commit();
[Link]();
[Link]();
}
}
Output:

Vansh Singh
TYCS ‘C’
9179

7. Update student name by ID


[Link]
package [Link].practical9;
import [Link];
import [Link]; // Make sure this is
imported import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class App {
public static void main(String[] args) {
SessionFactory factory = new Configuration()
.configure("[Link]")
.addAnnotatedClass([Link])
.addAnnotatedClass([Link])
.buildSessionFactory();
Session session = [Link]();
Transaction tx = [Link]();
Query<?> query = [Link]("UPDATE Student s SET [Link] =
:newName WHERE [Link] = :id");
[Link]("newName", "MP");
[Link]("id", 3);
int rows = [Link]();
[Link]();
[Link]();
[Link]();
[Link]("Updated Rows: " + rows);
}
}
Output:
Vansh Singh
TYCS ‘C’
9179

8. Delete a student by ID
[Link]
package [Link].practical9;
import [Link];
import [Link]; // Make sure this is
imported import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class App {
public static void main(String[] args) {
SessionFactory factory = new Configuration()
.configure("[Link]")
.addAnnotatedClass([Link])
.addAnnotatedClass([Link])
.buildSessionFactory();
Session session = [Link]();
Transaction tx = [Link]();
Query query = [Link]("DELETE FROM Student s WHERE [Link] =
:id"); [Link]("id", 3);
int rows = [Link]();
[Link]();
[Link]();
[Link]();
[Link]("Deleted Rows: " + rows);
}
}
Output:

Vansh Singh
TYCS ‘C’
9179

9. Get all students along with their department names


[Link]
package [Link].practical9;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class App {
public static void main(String[] args) {
SessionFactory factory = new Configuration()
.configure("[Link]")
.addAnnotatedClass([Link])
.addAnnotatedClass([Link])
.buildSessionFactory();
Session session = [Link]();
Transaction tx = [Link]();
Query<Object[]> query = [Link](
"SELECT [Link], [Link] FROM Student s JOIN [Link] d",
Object[].class
);
List<Object[]> results = [Link]();
for (Object[] row : results) {
[Link]("Student: " + row[0] + ", Department: " + row[1]); }
[Link]();
[Link]();
[Link]();
}
}
Output:

10. Get students in "CS" department


[Link]
package [Link].practical9;
import [Link];
import [Link];
Vansh Singh
TYCS ‘C’
9179
import [Link];
import [Link];

import [Link];
import [Link];
public class App {
public static void main(String[] args) {
SessionFactory factory = new Configuration()
.configure("[Link]")
.addAnnotatedClass([Link])
.addAnnotatedClass([Link])
.buildSessionFactory();
Session session = [Link]();
Transaction tx = [Link]();
Query<String> query = [Link](
"SELECT [Link] FROM Student s JOIN [Link] d WHERE [Link] =
:deptName",
[Link]
);
[Link]("deptName", "Science");
List<String> studentNames = [Link]();
for (String s : studentNames) {
[Link]("Student: " + s);
}
[Link]();
[Link]();
[Link]();
}
}
Output:

Vansh Singh
TYCS “C’
9179
PRACTICAL-10
AIM : Implementation of HCQL with Restrictions class ,Order class
name email salary address
1 n alice@[Link] 55000.00 New York

2 Bob Smith [Link]@[Link] 62000.00 Chicago

3 Carol White NULL 48000.00 Los Angeles

4 David Green [Link]@[Link] 70000.00 New York

5 Eve Black [Link]@[Link] 53000.00 Boston

6 Frank Brown NULL 30000.00 Seattle

7 Grace Adams [Link]@[Link] Austin

8 Henry King [Link]@[Link] 40000.00 Chicago

Common Code:

[Link] package
[Link].muskan9046;
import [Link].*;
@Entity
@Table(name = "Employee") public
class Employee {
@Id private int id;
private String name;
private String email;
private Double salary;
private String address;
public Employee() {
}
public Employee(int id, String name, String email, Double salary, String
address) { [Link] = id; [Link] = name; [Link] = email; [Link] =
salary; [Link] = address;
} public int
getId() { return
id;

} public void setId(int


id) { [Link] = id;
Vansh Singh
TYCS “C’
9179
}
public String getName() {
return name;
}
public void setName(String name) {
[Link] = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
[Link] = email;
}
public Double getSalary() {
return salary;
}
public void setSalary(Double salary) {
[Link] = salary;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
[Link] = address;
}
}
[Link]
<?xml version="1.0" encoding="utf-8"?>
<hibernate-configuration>
<session-factory>
<property
name="[Link].driver_class">[Link]</property>
<property
name="[Link]">jdbc:mysql://localhost:3306/muskan9046?useSSL=f
alse&a m p; serverTimezone=UTC</property>
<property name="[Link]">root</property>
<property name="[Link]"></property>
<property name="connection.pool_size">10</property>
<property
name="[Link]">[Link].MySQL8Dialect</property>
<property name="show_sql">false</property>
<property name="format_sql">false</property>
<property name="[Link]">update</property>
<mapping class="[Link].muskan9046 Employee"/>
</session-factory>
Vansh Singh
TYCS “C’
9179

</hibernate-configuration>

1. Find all employees whose salary is greater than x(x= user input)

Code: [Link]
package [Link].muskan9046; import
[Link]; import
[Link]; import
[Link]; import
[Link]; import
[Link]; import
[Link]; import
[Link]; import [Link]; public
class App {
public static void main(String[] args) {
SessionFactory sessionFactory = new Configuration()
.configure("[Link]")
.addAnnotatedClass([Link])
.buildSessionFactory();
Session session = [Link]();
try (Scanner scanner = new Scanner([Link])) {
[Link]("Enter salary x: "); double x =
[Link]();
[Link]();
CriteriaBuilder builder = [Link]();
CriteriaQuery<Employee> query = [Link]([Link]);
Root<Employee> root = [Link]([Link]);
[Link](root).where([Link]([Link]("salary"), x));
List<Employee> employees = [Link](query).getResultList();
[Link]().commit(); if ([Link]()) {
[Link]("No employees found with salary greater than " + x); }
else { [Link]("Employees with salary greater than " + x +
":"); for
(Employee emp : employees) {
[Link]("ID: " + [Link]());
[Link]("Name: " + [Link]());
[Link]("Email: " + ([Link]() != null ? [Link]() :
"NULL")); [Link]("Salary: " + [Link]());
[Link]("Address: " + [Link]());
[Link]("------------------------------");
Vansh Singh

TYCS “C’
9179

}
}
} catch (Exception e) {
[Link](); }
finally {
[Link]();
[Link]();
}
}
}

OUTPUT:

2) Fetch employees who live in either 'New York' or 'Chicago'.


CODE:
[Link]
package [Link]. muskan9046; import
[Link]; import
[Link]; import
[Link]; import
[Link]; import
[Link]; import
[Link]; import
[Link]; import
[Link]; import
[Link]; import [Link]; import
[Link]; public class App {
public static void main(String[] args) {
SessionFactory sessionFactory = new Configuration()
.configure("[Link]")
.addAnnotatedClass([Link])
Vansh Singh
TYCS “C’
9179

.buildSessionFactory();
Session session = [Link]();
try {
[Link]();
Criteria criteria = [Link]([Link]);
[Link]([Link]("address", [Link]("New York",
"Chicago"))); List<Employee> employees = [Link]();
[Link]().commit(); if ([Link]()) {
[Link]("No employees found living in New York or Chicago.");
} else {
[Link]("Employees living in New York or Chicago:"); for
(Employee emp : employees) {
[Link]("ID: " + [Link]());
[Link]("Name: " + [Link]());
[Link]("Email: " + ([Link]() != null ? [Link]() :
"NULL"));
[Link]("Salary: " + [Link]());
[Link]("Address: " + [Link]());

[Link]("------------------------------");

[Link]();
[Link]();
}
} }
} catch (Exception e) {
[Link](); }
}
Vansh Singh
TYCS “C’
9179

OUTPUT:

3) Get employees whose salary is between x and y.(x and y take it from user)

[Link]
package [Link]. muskan9046;
import [Link]; import
[Link]; import
[Link]; import
[Link]; import
[Link]; import
[Link]; import [Link];
public class App {
public static void main(String[] args) {
SessionFactory sessionFactory = new Configuration()
Vansh Singh
TYCS “C’
9179

.configure("[Link]")
.addAnnotatedClass([Link])
.buildSessionFactory();
Session session = [Link]();
try (Scanner scanner = new Scanner([Link])) {
[Link]("Enter lower salary limit (x): ");
double x = [Link]();
[Link]("Enter upper salary limit (y): ");
double y = [Link]();
[Link]();
Criteria criteria = [Link]([Link]);
[Link]([Link]("salary", x, y));
List<Employee> employees = [Link]();
[Link]().commit(); if
([Link]()) {
[Link]("No employees found with salary between " + x + " and " + y); } else
{
[Link]("Employees with salary between " + x + " and " + y + ":"); for
(Employee emp : employees) {
[Link]("ID: " + [Link]());
[Link]("Name: " + [Link]());
[Link]("Email: " + ([Link]() != null ? [Link]() :
"NULL"));
[Link]("Salary: " + [Link]());
[Link]("Address: " + [Link]());
[Link]("------------------------------");

[Link]();
[Link]();
}
}
}
OUTPUT:
Vansh Singh
TYCS “C’
9179

4) Get employees who either live in 'Austin' or have a salary greater than 70,000.

[Link]
package [Link]. muskan9046;
import [Link]; import
[Link]; import
[Link]; import
[Link]; import
[Link]; import
[Link]; import [Link];
public class App {
public static void main(String[] args) {
SessionFactory sessionFactory = new Configuration()
.configure("[Link]")
.addAnnotatedClass([Link])
.buildSessionFactory();
Session session = [Link]();
try {
[Link]();
Criteria criteria = [Link]([Link]);
[Link]([Link](
[Link]("address", "Austin"),
[Link]("salary", 70000.0)
));
List<Employee> employees = [Link]();
[Link]().commit(); if
([Link]()) {
[Link]("No employees found who live in Austin or have salary greater than
70000.");
} else {
[Link]("Employees who live in Austin or have salary greater than 70000:"); for
(Employee emp : employees) {
[Link]("ID: " + [Link]());
[Link]("Name: " + [Link]());
[Link]("Email: " + ([Link]() != null ? [Link]() :
"NULL"));
[Link]("Salary: " + [Link]());
[Link]("Address: " + [Link]());
[Link]("------------------------------");
Vansh
Singh
TYCS
“C’
9179

}
}

[Link](); [Link](); }

OUTPUT:

5. Fetch employees with salary > 40,000 and sort them by address ascending.

[Link]
package [Link]. muskan9046;
import [Link]; import
[Link]; import
[Link]; import
[Link]; import
[Link]; import
[Link]; public class App {
public static void main(String[] args) {
SessionFactory sessionFactory = new Configuration()
.configure("[Link]")
.addAnnotatedClass([Link])
Vansh Singh
TYCS “C’
9179

.buildSessionFactory();
Session session = [Link]();
try {
[Link]();
Criteria criteria = [Link]([Link]);
[Link]([Link]("salary", 40000.0));
[Link]([Link]("address"));
List<Employee> employees = [Link]();
[Link]().commit(); if ([Link]()) {
[Link]("No employees found with salary greater than 40,000."); } else
{
[Link]("Employees with salary greater than 40,000 sorted by address:"); for
(Employee emp : employees) {
[Link]("ID: " + [Link]());
[Link]("Name: " + [Link]());
[Link]("Email: " + ([Link]() != null ? [Link]() :
"NULL"));
[Link]("Salary: " + [Link]());
[Link]("Address: " + [Link]());
[Link]("------------------------------");
}
}
} catch (Exception e) {
[Link]();
} finally {

[Link]();
[Link]();
}
}
}

OUTPUT:
Vansh singh
TYCS ‘C’
9179

PRACTICAL NO 11
Aim:Implementation of NamedQuery with hibernate

Artist table :
id name genre country debutYear

1 Arijit Singh Playback India 2005

2 Shreya Ghoshal Classical India 2000

3 Ed Sheeran Pop UK 2011

4 Adele Pop/Soul UK 2008

5 Shakira Latin Pop Colombia 1990

6 Taylor Swift Pop USA 2006

7 Sonu Nigam Playback India 1992

8 Billie Eilish Pop USA 2015

9 AR Rahman Film Score India 1992

10 BTS K-Pop South Korea 2013

Q1. Write a Hibernate program using @NamedQuery to fetch all artists from a
country given by the user
❖ Source code:
● [Link]
package [Link]._pract11;
import [Link].*;
import [Link];
import [Link];
import [Link];
@NamedQueries(
{
@NamedQuery(
name = "findArtistByCountry",
query = "from Artist a where [Link] = :country"
)
Vansh singh
TYCS ‘C’
9179
}
)
@Entity
@Table(name="artists")
public class Artist {
@Id
@GeneratedValue(strategy = [Link])
private int id;
@Column(name = "name")
private String name;
@Column(name= "genre")
private String genre;
@Column(name= "country")
private String country;
@Column(name= "debutYear")
private int debutYear;
public Artist() {}
public Artist(String name, String genre, String country,int debutYear) {}
public int getId() {
return id;
}
public void setId(int id) {
[Link] = id;
}
public String getName() {
return name;
}
public void setName(String name) {
[Link] = name;
}
public String getGenre() {
return genre;
}
public void setGenre(String genre) {
[Link] = genre;
}
public String getCountry() {
return country;
}
Vansh singh
TYCS ‘C’
9179

public void setCountry(String country) {


[Link] = country;
}
public int getDebutYear() {
return debutYear;
}
public void setDebutYear(int debutYear) {
[Link] = debutYear;
}
}

● [Link]

<?xml version="1.0" encoding="UTF-8"?>


<hibernate-configuration>
<session-factory>
<property name="[Link].driver_class">[Link]</property>
<property
name="[Link]">jdbc:mysql://localhost:3306/9020_megha?useSSL=false&am
p;requireSSL=false&amp;verifyServerCertificate=false</property>
<property name="[Link]">root</property>
<property name="[Link]"></property>
<property name="connection.pool_size">8</property>
<property name="[Link]">[Link].MySQL8Dialect</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="[Link]">update</property>
<mapping class="[Link]._pract11.Artist"/>
</session-factory>
</hibernate-configuration>

● [Link]’
package [Link]._pract11;
import [Link].*;
import [Link].*;
import [Link];
import [Link].*;
import [Link];
public class App
Vansh singh
TYCS ‘C’
9179

{
public static void main( String[] args )
{

SessionFactory sf = new Configuration().configure().buildSessionFactory();


Session sn = [Link]();
Scanner sk = new Scanner([Link]);
[Link]("Enter the Country: ");
String x = [Link]();
TypedQuery query = [Link]("findArtistByCountry");
[Link]("country",x);
List<Artist> art=[Link]();
for (Artist a : art) {
[Link]("ID:" + [Link]());
[Link]("Name:" + [Link]());
[Link]("Country:" + [Link]());
[Link]("Genre:" + [Link]());
[Link]("Debut Year:" + [Link]());
[Link]("--- Finish ---");
}
[Link]();
}
}

Output:

Vansh singh
TYCS ‘C’
9179

Q2. Write a Hibernate program using @NamedQuery to fetch artists based on both genre
and debutYear given by the user
e.g. Fetch artists with genre = 'Pop' and debutYear > 2010.

❖ Source code:
● [Link]
package [Link].pract11_9020;
import [Link].*;
import [Link];
import [Link];
import [Link];
@NamedQueries(
{
@NamedQuery(
name = "findArtistByGenreAndYear",
query = "FROM Artist a WHERE [Link] = :genre AND [Link] = :year" )})
@Entity
@Table(name="artists")
public class Artist {
@Id
@GeneratedValue(strategy = [Link])
private int id;
@Column(name = "name")
private String name;
@Column(name= "genre")
private String genre;
@Column(name= "country")
private String country;
Vansh singh
TYCS ‘C’
9179

@Column(name= "debutYear")
private int debutYear;
public Artist() {}
public Artist(String name, String genre, String country,int debutYear) {}
public int getId() {
return id;
}
public void setId(int id) {
[Link] = id;

}
public String getName() {
return name;
}
public void setName(String name) {
[Link] = name;
}
public String getGenre() {
return genre;
}
public void setGenre(String genre) {
[Link] = genre;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
[Link] = country;
}
public int getDebutYear() {
return debutYear;
}
public void setDebutYear(int debutYear) {
[Link] = debutYear;
}}

● [Link]
package [Link].pract11_9020;
import [Link].*;
Vansh singh
TYCS ‘C’
9179

import [Link].*;
import [Link];
import [Link].*;
import [Link];
public class App {
public static void main(String[] args) {
SessionFactory sf = new Configuration().configure().buildSessionFactory();
Session sn = [Link]();
Scanner sk = new Scanner([Link]);
[Link]("Enter the Genre: ");
String x = [Link]();
[Link]("Enter the Debut Year: ");
int y = [Link]();
Query<Artist> query = [Link]("findArtistByGenreAndYear",
[Link]);
[Link]("genre", x);
[Link]("year", y);
List<Artist> art=[Link]();
if ([Link]()) {
[Link]("\nNo artists found for the specified genre and year."); } else {
[Link]("\n--- Found Artists ---");
for (Artist a : art) {
[Link]("ID:" + [Link]());
[Link]("Name:" + [Link]());
[Link]("Country:" + [Link]());
[Link]("Genre:" + [Link]());
[Link]("Debut Year:" + [Link]());
[Link]("--- Finish ---");
}
[Link]();
}
}
}
Output:
Vansh singh
TYCS ‘C’
9179

Q3. Write a NamedQuery in XML to fetch all artists sorted by debutYear in


ascending order.
❖ Source code:
● [Link]
package [Link].pract11_9020;
public class Artist {
private int id;
private String name;
private String genre;
private String country;
private int debutYear;
public Artist() {}
public Artist(String name, String genre, String country,int debutYear) {}
public int getId() {
return id;
}
public void setId(int id) {
[Link] = id;
}
public String getName() {
return name;
}
Vansh singh
TYCS ‘C’
9179

public void setName(String name) {


[Link] = name;
}
public String getGenre() {
return genre;
}
public void setGenre(String genre) {
[Link] = genre;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
[Link] = country;
}
public int getDebutYear() {
return debutYear;
}
public void setDebutYear(int debutYear) {
[Link] = debutYear;
}
}

● [Link]

<?xml version="1.0" encoding="UTF-8"?>


<hibernate-mapping package="[Link].pract11_9020">
<class name="Artist" table="artists">
<id name="id" column="id">
<generator class="identity"/>
</id>
<property name="name" column="name"/>
<property name="genre" column="genre"/>
<property name="country" column="country"/>
<property name="debutYear" column="debutYear"/>
</class>
<query name="findAllArtistsSortedByYear">
<![CDATA[
from Artist a ORDER BY [Link] ASC
Vansh singh
TYCS ‘C’
9179

]]>
</query>
</hibernate-mapping>

● [Link]
<?xml version="1.0" encoding="UTF-8"?>
<hibernate-configuration>
<session-factory>
<property name="[Link].driver_class">[Link]</property>
<property
name="[Link]">jdbc:mysql://localhost:3306/megha_9020?useSSL=true&amp
;requireSSL=false&amp;verifyServerCertificate=false</property>
<property name="[Link]">root</property>
<property name="[Link]">root</property>
<property name="connection.pool_size">8</property>
<property name="[Link]">[Link].MySQL8Dialect</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="[Link]">update</property>
<mapping resource="[Link]"/>
</session-factory>
</hibernate-configuration>

● [Link]
package [Link].pract11_9020;
import [Link].*;
import [Link];
import [Link].*;
import [Link];
public class App {
public static void main(String[] args) {
SessionFactory sf = new Configuration().configure().buildSessionFactory();
Session sn = [Link]();
Query<Artist> query = [Link]("findAllArtistsSortedByYear", [Link]);
List<Artist> art=[Link]();
if ([Link]()) {
[Link]("\nNo artists found for the specified genre and year."); } else {
Vansh singh
TYCS ‘C’
9179

[Link]("\n--- Found Artists ---");

for (Artist a : art) {


[Link]("ID:" + [Link]());
[Link]("Name:" + [Link]());
[Link]("Country:" + [Link]());
[Link]("Genre:" + [Link]());
[Link]("Debut Year:" + [Link]());
[Link]("--- Finish ---");
}
[Link]();
}
}
}

Output:
Vansh singh
TYCS ‘C’
9179
Vansh singh
TYCS ‘C’
9179
Q4. Write a NamedQuery in XML to fetch only the name column of all artists

❖ Source code
● [Link]

<?xml version="1.0" encoding="UTF-8"?>


<hibernate-mapping package="[Link].pract11_9020">
<class name="Artist" table="artists">
<id name="id" column="id">
<generator class="identity"/>
</id>
<property name="name" column="name"/>
<property name="genre" column="genre"/>
<property name="country" column="country"/>
<property name="debutYear" column="debutYear"/>
</class>
<query name="findAllArtistNames">
<![CDATA[
select [Link] from Artist a
]]>
</query>
Vansh singh
TYCS ‘C’
9179

</hibernate-mapping>

● [Link]
package [Link].pract11_9020;
import [Link].*;
import [Link].*;
import [Link];
import [Link].*;
import [Link];
public class App {
public static void main(String[] args) {
SessionFactory sf = new Configuration().configure().buildSessionFactory();
Session sn = [Link]();

TypedQuery<String> query = [Link]("findAllArtistNames", [Link]);


List<String> art = [Link]();
if ([Link]()) {
[Link]("\nNo artists found for the specified genre and year."); } else {
[Link]("\n--- Found Artists ---");

for (String name : art) {


[Link]("Name: " + name);
}
[Link]("--- Finish ---");

[Link]();
}
}
}
Vansh singh
TYCS ‘C’
9179
Output:

Q5. Write a NamedQuery in XML to count the total number of artists from a given
country.
❖ Source code:
● [Link]

<?xml version="1.0" encoding="UTF-8"?>


<hibernate-mapping package="[Link].pract11_9020">
<class name="Artist" table="artists">
<id name="id" column="id">
Vansh singh
TYCS ‘C’
9179
<generator class="identity"/>
</id>
<property name="name" column="name"/>
<property name="genre" column="genre"/>
<property name="country" column="country"/>
<property name="debutYear" column="debutYear"/>
</class>
<query name="countArtistsByCountry">
<![CDATA[
select count(a) from Artist a where [Link] = :country
]]>
</query>
</hibernate-mapping>

● [Link]
package [Link].pract11_9020;
import [Link].*;
import [Link].*;
import [Link];
import [Link].*;
import [Link];
public class App {
public static void main(String[] args) {
SessionFactory sf = new Configuration().configure().buildSessionFactory();
Session sn = [Link]();
Scanner sk = new Scanner([Link]);
[Link]("Enter the country to count artists from: ");
String countryInput = [Link]();
TypedQuery<Long> query = [Link]("countArtistsByCountry",
[Link]);

[Link]("country", countryInput);
Long artistCount = [Link]();
[Link]("\nTotal number of artists from " + countryInput + ": " + artistCount);
[Link]();
}
}
Output:
Vansh singh
TYCS ‘C’
9179

You might also like