JDBC (Java Database Connectivity) is an API that allows Java applications to interact with relational databases through two main packages: java.sql and javax.sql. Key features include database connectivity, SQL execution, and transaction management, with methods like getConnection() from the DriverManager class facilitating connections. Hibernate is an ORM framework that simplifies database interactions by mapping Java objects to database tables, reducing complexity and preventing SQL injection.
JDBC (Java Database Connectivity) is an API that allows Java applications to interact with relational databases through two main packages: java.sql and javax.sql. Key features include database connectivity, SQL execution, and transaction management, with methods like getConnection() from the DriverManager class facilitating connections. Hibernate is an ORM framework that simplifies database interactions by mapping Java objects to database tables, reducing complexity and preventing SQL injection.
What is JDBC Write down 2 List & explain all the The getConnection() DriverManager class Differentiate between
riverManager class Differentiate between What is Hibernate,
packages of JDBC interfaces used in JDBC method is a static The DriverManager class statement and prepared and why is it used? JDBC (Java Database API. JDBC provides several method of the in JDBC is responsible for statement Connectivity) is an API Hibernate is an open- JDBC API provides key interfaces that enable DriverManager class in managing database Statement-Used to execute (Application source Object- two main packages Java applications to JDBC. It is used to drivers and establishing static SQL queries.-Prone Programming Relational Mapping for database interact with databases. establish a connection connections between Java to SQL injection attacks as (ORM) framework for Interface) in Java that between a Java queries are dynamic. connectivity in Java: Below are the main applications and Java applications. It enables applications 1.java.sql interfaces used in JDBC: application and a databases. It is part of the -Slower for repeated simplifies database to connect to and database. execution as it compiles PackageContains 1.DriverResponsible for java.sql package. interactions by allowing interact with relational Syntax: the query every time. core JDBC classes loading the JDBC driver Key Features of developers to work with databases. It allows Connection con = -Executes SQL queries and interfaces for and establishing a DriverManager: Java objects instead of Java programs to DriverManager.getConne directly as a string. database operations. connection to the 1.Manages Database SQL queries. Hibernate execute SQL queries, -Statement stmt = Provides database. Example: ction(url, user, Drivers – Loads and automatically maps retrieve data, and password); con.createStatement(); functionalities for Class.forName("com.mys registers JDBC drivers Java classes to manage database Parameters: ResultSet rs = connecting to ql.cj.jdbc.Driver"); automatically. database tables and transactions. 1.url – The database URL stmt.executeQuery("SELE databases, executing 2.ConnectionRepresents 2.Establishes Database handles operations like Key Features of JDBC: CT * FROM users WHERE queries, and a connection session (e.g., Connections – Provides querying, updating, and 1.Database "jdbc:mysql://localhost:3 id=" + userId); managing result sets. with the database. Used the getConnection() deleting records. Connectivity – 306/dbname"). PreparedStatement Key to create statements and method to connect Java Why is Hibernate Used? Provides a standard 2.user – The database Interfaces/Classes: manage transactions. applications to databases. -Used to execute 1.Eliminates JDBC way to connect Java username. precompiled parameterized Connection, 3.StatementUsed to 3.Logs and Traces Errors Complexity – Reduces applications with 3.password – The SQL queries. Statement, ResultSet, execute static SQL – Helps in debugging the need for writing databases like MySQL, database password. -Used to execute DriverManager. queries. database connection complex SQL queries Oracle, and Example Usage: precompiled parameterized 2.javax.sql 4.PreparedStatementUse issues. and managing database PostgreSQL. java SQL queries. PackageProvides d to execute 4.Supports Multiple connections manually. 2.SQL Execution – -Prevents SQL injection by advanced JDBC parameterized queries to import java.sql.*; public Drivers – Can handle 2.Provides Database Allows execution of class JDBCExample { using parameterized features, mainly for prevent SQL injection. multiple database Independence – SQL queries such as public static void queries. enterprise 5.CallableStatementUsed connections Supports multiple SELECT, INSERT, main(String[] args) { try -Faster for repeated applications. to execute stored simultaneously. databases without UPDATE, and DELETE. {Class.forName("com.my execution as the query is Supports connection procedures in the Important Methods of modifying the 3.Platform sql.cj.jdbc.Driver"); precompiled. pooling and database. DriverManager: application code. Independence – Works Connection con = -Uses placeholders (?) for distributed ResultSetStores the 1.getConnection(String 3.Enables Caching – with different DriverManager.getConne dynamic values in queries. transactions. Key result of an executed url, String user, String Improves performance databases through Interfaces/Classes: SQL query. Allows ction("jdbc:mysql://localh password) – Establishes a PreparedStatement pstmt = by caching frequently JDBC drivers. ost:3306/mydb", "root", con.prepareStatement("SE DataSource, iteration over retrieved database connection. accessed data. 4.Transaction "password"); LECT * FROM users ConnectionPoolData rows. 2.registerDriver(Driver 4.Supports Automatic Management – WHERE id=?"); Source, RowSet, ResultSetMetaDataProvid System.out.println("Conn driver) – Manually Table Creation – Supports commit and ection Successful!"); pstmt.setInt(1, userId); XADataSource. es metadata (column registers a JDBC driver. Generates tables based rollback operations to con.close();} catch ResultSet rs = names, types, etc.) about 3.setLoginTimeout(int on Java entity classes, ensure data integrity. pstmt.executeQuery(); a ResultSet. Example: (Exception e) { seconds) – Sets the simplifying database ResultSetMetaData rsmd e.printStackTrace(); } } } timeout for a connection management. = rs.getMetaData(); attempt. What are the steps to connect to Write a JDBC Program to Write a JDBC program to Write a java program to What is thread? Explain thread life cycle the database in Java. with diagram Insert the record into delete the records of delete salary column from A thread is the smallest 1. Load and Register the JDBC patient table (Use students whose names are Emp table. Assume Emp table unit of execution in a A thread in Java goes Driver •Required for older JDBC prepared statement) starting with ‘m’ character with attributes ENo, EName program. It is a through different states versions, but optional in modern and salary is already created. lightweight subprocess during its execution. The import java.sql.*; import java.sql.*; that allows multitasking Thread Life Cycle consists Java. import java.sql.*; public class public class and parallel execution of of five main states: Class.forName("com.mysql.cj.jdb public class InsertPatientRecord { DeleteStudentRecords { code within a Java 1. New (Created) c.Driver"); DeleteColumnFromEmp public static void public static void application. •When a thread object is 2. Establish a Connection { main(String[] args) { main(String[] args) { Key Features of created but not yet started. •Use the public static void String url = String url = Threads: •Example: DriverManager.getConnection() main(String[] args) { "jdbc:mysql://localhost:3306/ "jdbc:mysql://localhost:3 1.Enables Multitasking – Thread t = new Thread(); method to connect to the String url = hospital"; // Change 306/school"; String user Allows multiple 2. Runnable database. "jdbc:mysql://localhost:3 database name if needed = "root"; operations to run •The thread is ready to run Connection con = 306/company"; // Change String user = "root"; String String password = concurrently. but waiting for CPU DriverManager.getConnection("jd database name if needed password = "password"; "password"; 2.Runs Independently – scheduling. bc:mysql://localhost:3306/mydb", String user = "root"; String sql = "INSERT INTO String sql = "DELETE Each thread runs •It enters this state after "root", "password"); String password = patient (id, name, age, FROM students WHERE separately without calling start(). 3. Create a Statement "password"; disease) VALUES (?, ?, ?, name LIKE ?"; affecting others. •Example: •Use a Statement or String sql = "ALTER ?)"; try 3.Uses Less Memory – t.start(); PreparedStatement object to TABLE Emp DROP try { {Class.forName("com.m Compared to processes, 3. Running execute SQL queries. COLUMN salary"; Class.forName("com.mysql. ysql.cj.jdbc.Driver"); threads share the same •The thread is executing Statement stmt = try cj.jdbc.Driver"); Connection con = memory space. its task after getting CPU con.createStatement(); {Class.forName("com.m Connection con = DriverManager.getConne 4.Can Be Created in Two time. 4. Execute SQL Query ysql.cj.jdbc.Driver"); DriverManager.getConnectio ction(url, user, Ways – By extending •Example: •Use executeQuery() for SELECT Connection con = n(url, user, password); password); the Thread class or public void run() { statements or executeUpdate() DriverManager.getConne PreparedStatement pstmt = PreparedStatement implementing the System.out.println("Threa for INSERT, UPDATE, or DELETE. ction(url, user, con.prepareStatement(sql); pstmt = Runnable interface. d is running..."); } ResultSet rs = password); pstmt.setInt(1, 101); con.prepareStatement(s Example: Creating a 4. Blocked/Waiting stmt.executeQuery("SELECT * Statement stmt = pstmt.setString(2, "John ql); Thread in Java •The thread is temporarily FROM users"); con.createStatement(); Doe"); pstmt.setString(1, java inactive, waiting for a 5. Process the Results stmt.executeUpdate(sql); pstmt.setInt(3, 30); "M%"); class MyThread extends resource or signal. •Iterate through the ResultSet to System.out.println("Colu pstmt.setString(4, "Flu"); int rowsDeleted = Thread { public void •Example: retrieve data. mn 'salary' deleted int rowsInserted = pstmt.executeUpdate(); run() { t.wait(); while (rs.next()) { successfully from Emp pstmt.executeUpdate(); System.out.println(rows System.out.println("Thr 5. Terminated (Dead) System.out.println("User ID: " + table!"); if (rowsInserted > 0) { Deleted + " records ead is running..."); } •The thread has completed rs.getInt("id")); } stmt.close(); System.out.println("Record deleted successfully!"); public static void execution or stopped due 6. Close the Connection con.close(); inserted successfully!");} pstmt.close(); main(String[] args) { to an error. •Always close the ResultSet, } catch (Exception e) { pstmt.close(); con.close(); MyThread t1 = new •Example: Statement, and Connection to e.printStackTrace();}} con.close(); } catch (Exception e) { MyThread(); // Create System.out.println("Threa free resources. } catch (Exception e) { e.printStackTrace();}}} d finished execution."); thread t1.start(); // Start rs.close(); stmt.close(); e.printStackTrace();}}} thread execution } } con.close(); What is wait ( ) and notify ( ) in Explain Thread What are the main applications of multithreading? What is synchronization? What is the Spring priority in detail the Spring Framework and benefits 1. wait() Method: Synchronization in Java is a Framework? Why is Spring of using Spring? •Causes the current thread to pause Thread priority in Java mechanism that allows only used in Java applications? 1. Main Applications of Spring execution and release the lock. determines the order of one thread at a time to The Spring Framework is a Framework: •The thread remains in the waiting state execution when multiple access a shared resource, powerful, open-source 1.Enterprise Applications – until another thread calls notify(). threads are waiting for CPU preventing data framework for building Used in large-scale business •Example: time. Higher-priority threads inconsistency and race enterprise-level Java applications due to its synchronized(obj) { obj.wait();} are more likely to execute conditions in multithreading applications. It provides a modular design and 2. notify() Method: before lower-priority environments. comprehensive infrastructure transaction management. •Wakes up one waiting thread that is threads. Types of Synchronization in for developing, managing, and 2.Web Applications – Spring waiting on the same object. Thread Priority Levels: Java deploying Java applications MVC helps build dynamic and •The awakened thread must reacquire the Thread.MIN_PRIORITY=1Lo 1. Synchronized Method efficiently. secure web applications. west priority lock before continuing execution. •Declaring a method as •Lightweight and Modular 3.Microservices – Spring Boot •Example: Thread.NORM_PRIORITY=5D synchronized ensures only •Spring is a lightweight simplifies microservices synchronized(obj) { obj.notify();} class efault priority one thread can execute it at framework with a modular development with auto- SharedResource { Thread.MAX_PRIORITY=10Hi a time. design, allowing developers to configuration and embedded ghest priority synchronized void produce() throws •Example: use only the necessary servers. InterruptedException { class MyThread extends Class Counter{ components. 4.RESTful APIs – Spring REST System.out.println("Producer is Thread { Private int count=0: •Dependency Injection (DI) makes it easy to develop producing..."); public void run() { Public synchronized void •Uses Inversion of Control (IoC) RESTful web services. wait(); System.out.println(Thread.c Increment () { to manage dependencies, . 2. Benefits of Using Spring System.out.println("Producer resumed.");} urrentThread().getName() + " Count ++; reducing tight coupling Framework: synchronized void consume() { Priority: " + }Public synchronized int get between components. 1.Lightweight and System.out.println("Consumer is Thread.currentThread().getP count() { return count; •Aspect-Oriented Programming ModularDevelopers can use consuming..."); riority());} }} (AOP) only the required notify();}} public static void 2. Synchronized Block •Separates cross-cutting components, making main(String[] args) { public class WaitNotifyExample { •Synchronizes only a concerns like logging, security, applications efficient. public static void main(String[] args) { MyThread t1 = new specific part of a method and transactions, improving 2.Dependency Injection SharedResource resource = new MyThread(); instead of the entire method, maintainability. (DI)Reduces tight coupling SharedResource(); MyThread t2 = new improving performance. •Integrated Transaction between components, MyThread(); new Thread(() -> { •Example: Management improving flexibility and try { resource.produce(); } catch MyThread t3 = new class Printer { void •Provides built-in declarative maintainability. (InterruptedException e) { MyThread(); printDocuments(int pages) { transaction management, 3.Aspect-Oriented e.printStackTrace(); } t1.setPriority(Thread.MIN_P synchronized (this) { for (int i reducing the need for complex Programming (AOP)Helps }).start(); RIORITY); // Priority 1 = 1; i <= pages; i++) { JDBC code. manage cross-cutting new Thread(() -> { t2.setPriority(Thread.NORM_ System.out.println("Printing •Spring MVC for Web concerns like logging, try { Thread.sleep(1000); PRIORITY); // Priority 5 page: " + i); } } } } Development security, and transactions. resource.consume(); } catch t3.setPriority(Thread.MAX_P 3. Static Synchronization •Supports web applications 4.Transaction RIORITY); // Priority 10 (InterruptedException e) { •Used when multiple threads with Spring MVC, a flexible and ManagementProvides built-in e.printStackTrace(); } t1.start(); access static methods of a powerful model-view-controller transaction support, reducing }).start();}} t2.start(); class. framework. boilerplate JDBC code. t3.start();}} What are the key How do you create a 1. IoC Containers 3. Bean Scopes in Spring Lifecycle of a Spring Bean Explain Architecture of components of Spring simple "Hello World" Inversion of Control (IoC) Spring provides different Hibernate. 1.Instantiation:The architecture? application in Spring? Container is the core of the scopes to define the lifespan The Hibernate Architecture and visibility of beans. Spring IoC container The Spring Framework is Spring Framework, consists of various import Example: creates an instance of designed in a layered responsible for managing the components that work org.springframework.boo java the bean using its architecture, where each lifecycle and dependencies of together to provide efficient t.SpringApplication; @Component constructor or a factory component provides Spring Beans. Object-Relational Mapping import method. specific functionality. The •It automatically injects @Scope("prototype") (ORM) and database org.springframework.boo public class MyBean { } 2.Population of key components of Spring dependencies using interaction. t.autoconfigure.SpringBo Properties:Dependency Architecture are: Dependency Injection (DI). Key Components of otApplication; Scope Description injection occurs, where 1. Core Container (Core & •Provides two types of IoC Hibernate Architecture: import the container injects Bean) containers: BeanFactory – A single bean 1.Configuration – Loads org.springframework.we values or references •Provides the foundation Lightweight, used for simple instance shared Hibernate settings from b.bind.annotation.GetMa singleton into the bean's for the framework, applications. across the hibernate.cfg.xml or pping; (Default) properties (e.g., via including Dependency ApplicationContext – More entire hibernate.properties, import setter methods or Injection (DI) and advanced, supports event application. including database org.springframework.we constructor arguments). BeanFactory. handling, internationalization, connection details. b.bind.annotation.Reque A new instance 3.Bean Post-Processing 2. AOP (Aspect-Oriented etc. 2.SessionFactory – A stMapping; prototyp is created every (Initialization):The Bean Programming) Example: heavyweight object that import e time the bean is PostProcessor interface •Separates cross-cutting ApplicationContext context = provides database org.springframework.we requested. allows custom concerns (e.g., logging, new connections and is created b.bind.annotation.RestC modification of the bean security, transactions). AnnotationConfigApplication A new instance once per application. ontroller; before and after •Helps in implementing Context(AppConfig.class); is created per 3.Session – A lightweight @SpringBootApplication initialization.The @Post aspects dynamically. 2. Spring Bean request HTTP request Construct annotation object that represents a public class 3. Data Access Layer A Spring Bean is an object (Web or InitializingBean interf connection between the HelloWorldApplication { •Handles database managed by the Spring IoC applications). ace's afterPropertiesSet application and the public static void interactions, supporting container. It is instantiated, () method can be used database. It is used to main(String[] args) { A new instance multiple data access configured, and assembled for custom initialization perform CRUD operations. SpringApplication.run(He session is created per technologies automatically by Spring. logic. 4.Transaction – Manages lloWorldApplication.clas HTTP session. 4. Spring MVC (Web Layer) Ways to define a Bean: 4.Bean is Ready for database transactions to s, args);}} •Provides a Model-View- 1.Using @Component global- Used for portlet Use:The bean is fully ensure data consistency @RestController Controller (MVC) Annotation session applications. initialized and available (e.g., commit or rollback). @RequestMapping("/api" framework for building web java for use in the 5.Query & Criteria API – ) applications. @Component public class application context. Used to execute SQL-like class HelloController { 5. Spring Security MyBean { } queries in an object- @GetMapping("/hello") •Provides authentication 2.Using @Bean in a oriented manner. public String sayHello() { and authorization features. Configuration Class 6.JDBC & Dialect – return "Hello, Spring •Protects applications java Hibernate internally uses World!";}} against security threats @Configuration public class JDBC to interact with (e.g., CSRF, SQL Injection). AppConfig { @Bean public databases, and Dialect MyBean myBean() { return new ensures compatibility with MyBean(); } } different databases. What is the Hibernate What is a Hibernate Session? What is a persistent class in What are Hibernate mapping What are the states of What is the use of HQL? configuration file? How is it created? Hibernate? How is it different files? Explain the different types the object in hibernate? Hibernate Query A Hibernate Session is a from a transient class? of mapping in Hibernate? 1. Transient State The Hibernate Language (HQL) is an lightweight, single-threaded object A persistent class is a Java class Hibernate mapping files define •The object is not configuration file object-oriented query that represents a connection whose objects are managed by the relationship between Java associated with (hibernate.cfg.xml) is language similar to SQL between a Java application and Hibernate and mapped to a objects (entities) and database Hibernate and is not an XML file that but works with Hibernate the database. It is used to perform database table. These objects are tables. These files specify how stored in the database. contains essential entities instead of CRUD operations (Create, Read, stored in the database and can be class properties correspond to •It is created using the settings required for database tables. Update, Delete) and interact with retrieved, updated, or deleted table columns, enabling new keyword but has Hibernate to connect Uses of HQL: database records. using Hibernate. Hibernate to perform Object- not been saved. with a database and •Enables database- Key Features of Hibernate Characteristics of a Persistent Relational Mapping (ORM) •Hibernate does not manage ORM (Object- independent queries. Session: Class: efficiently. track changes to Relational Mapping). •Allows querying Java •Provides methods like save(), •It must have a no-argument •Mapping files are typically transient objects. Purpose of the objects instead of tables. update(), delete(), and get() for constructor. written in XML format with the 2. Persistent State Hibernate •Supports CRUD database operations. •It should be annotated with extension .hbm.xml. •The object is Configuration File operations (Retrieve, •Works within a transaction to @Entity and mapped to a table •Alternatively, Hibernate also associated with a 1.Database Insert, Update, Delete). ensure data consistency. using @Table. supports annotations for Hibernate Session and Connection •Can use joins, A Hibernate Session is created A transient class refers to any mapping. stored in the database. Configuration – aggregations, and from the SessionFactory, which is Java class that is not managed by One-to-One Mapping •Hibernate tracks Defines the database conditions like SQL. initialized using the Hibernate and does not interact •Each row in Table A is related changes and URL, username, hibernate.cfg.xml configuration with the database. Its objects exist to one row in Table B. automatically updates password, and driver. file. in memory but are not stored in •Example: A User has one the database when the 2.Hibernate Properties Example of Creating a Hibernate the database unless explicitly Profile. transaction is – Specifies settings Session: saved. •Annotation private Profile committed. like SQL dialect, import org.hibernate.Session; Key Differences Between profile; •The object is logging, and import Persistent and Transient Classes: One-to-Many Mapping managed by Hibernate automatic table generation. org.hibernate.SessionFactory; Transie •One row in Table A is related to within an active Persiste 3.SessionFactory import Feature nt multiple rows in Table B. session. nt Class Setup – Helps org.hibernate.cfg.Configuration; Class •Example: A Department has 3. Detached State Hibernate create and public class many Employees. •The object was Managed manage sessions for HibernateSessionExample { public •Annotation private previously persistent, by Yes No database operations. static void main(String[] args) List<Employee> employees; but the Hibernate Hibernate 4.Entity Mapping – {Factory (only once in the Many-to-One Mapping Session is now closed. Associates Java application) SessionFactory Mapped to •Many rows in Table A relate to •Changes to the object classes with database factory = new a one row in Table B (reverse of will not be Yes No One-to-Many). tables. Configuration().configure("hiberna Database automatically te.cfg.xml").buildSessionFactory() Table •Example: Many Employees synchronized with the ; Session session = belong to one Department. database. Stored in Many-to-Many Mapping factory.openSession(); •The object can be the Yes No •Multiple rows in Table A relate session.beginTransaction(); reattached using Database to multiple rows in Table B. session.getTransaction().commit() update() or merge(). ; session.close();} } Exists
Instant Download (Ebook) Real-Time & Stream Data Management: Push-Based Data in Research & Practice by Wolfram Wingerath, Norbert Ritter, Felix Gessert ISBN 9783030105549, 9783030105556, 3030105547, 3030105555 PDF All Chapters