0% found this document useful (0 votes)
17 views18 pages

Q.7.Write A Spring Program For Autowiring by Using Bytype ? Pom - XML

Uploaded by

pmovies347
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)
17 views18 pages

Q.7.Write A Spring Program For Autowiring by Using Bytype ? Pom - XML

Uploaded by

pmovies347
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
You are on page 1/ 18

Q.7.Write a spring program for autowiring by using byType ?

pom.xml
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.24</version> <!-- Use the latest version -->
</dependency>
</dependencies>
Step 2: Define Java Beans (Services)
GreetingService.java
public class GreetingService {
public String getGreeting() {
return "Hello, World!";
}
}
UserService.java
import org.springframework.beans.factory.annotation.Autowired;
public class UserService {
private GreetingService greetingService;
// Autowiring by type
@Autowired
public void setGreetingService(GreetingService greetingService) {
this.greetingService = greetingService;
}
public void greetUser() {
System.out.println(greetingService.getGreeting() + " From
UserService!");
}
}
Step 3: Java Configuration Class
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
// Define GreetingService bean
@Bean
public GreetingService greetingService() {
return new GreetingService();
}
// Define UserService bean
@Bean
public UserService userService() {
return new UserService();
}
}
Step 4: Main Application Class
Importorg.springframework.context.annotation.AnnotationConfigAp
plicationContext;
public class App {
public static void main(String[] args) {
// Initialize Spring context using Java configuration class
(AppConfig)
try (AnnotationConfigApplicationContext context = new
AnnotationConfigApplicationContext(AppConfig.class)) {
// Retrieve UserService bean from Spring context
UserService userService = context.getBean(UserService.class);
// Call greetUser method which uses GreetingService
userService.greetUser();
}
}
}

Output :-

Hello, World! From UserService!


Q.8. Write a spring hibernate program for working with hibernate
using hibernate.cfg.xml.
Employee.java >> import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity >> public class Employee { >> @Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id; >> private String name;
private double salary; >> public Employee() {
} >> public Employee(String name, double salary) {
this.name = name; >> this.salary = salary; >> }
public int getId() { >> return id; >> }
public void setId(int id) { >> this.id = id; >> }
public String getName() {
return name; >> } >> public void setName(String name) {
this.name = name; >> } >> public double getSalary()
{return salary; >> } >> public void setSalary(double salary) {
this.salary = salary; >> } >> @Override
public String toString() {
return "Employee{id=" + id + ", name='" + name + "', salary=" + salary
+ '}'; >> } >> }
Step 4: Create the DAO Class (EmployeeDAO.java)
EmployeeDAO.java >>> import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.util.List; >> @Repository
public class EmployeeDAO {
private final SessionFactory sessionFactory; >> @Autowired
public EmployeeDAO(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory; >> } >> // Save employee
public void saveEmployee(Employee employee) {
Session session = sessionFactory.getCurrentSession();
session.saveOrUpdate(employee); >> }
// Get employee by id >> public Employee getEmployeeById(int id) {
Session session = sessionFactory.getCurrentSession();
return session.get(Employee.class, id); >> }
// Get all employees >> @SuppressWarnings("unchecked")
public List<Employee> getAllEmployees() {
Session session = sessionFactory.getCurrentSession();
return session.createQuery("from Employee").getResultList();
} >> // Delete employee by id
public void deleteEmployee(int id) {
Session session = sessionFactory.getCurrentSession();
Employee employee = session.get(Employee.class, id);
if (employee != null) { >> session.delete(employee);
} >> } >> }
Step 6: Create the Main Application Class
Import.org.springframework.context.annotation.AnnotationConfigAp
plicationContext;
public class App { >> public static void main(String[] args) {
// Initialize Spring context
try (AnnotationConfigApplicationContext context = new
AnnotationConfigApplicationContext(AppConfig.class)) {
EmployeeDAO employeeDAO =
context.getBean(EmployeeDAO.class);
Employee employee1 = new Employee("John Doe", 50000);
employeeDAO.saveEmployee(employee1);
// Fetch all employees >> System.out.println("All Employees: ");
employeeDAO.getAllEmployees().forEach(System.out::println);
Employee employee2 = employeeDAO.getEmployeeById(1);
System.out.println("Fetched Employee: " + employee2);
// Delete employee >> employeeDAO.deleteEmployee(1);
System.out.println("After deletion, all employees: ");
employeeDAO.getAllEmployees().forEach(System.out::println);
} >> } >> }
Q.7. Write a spring DAO program for JDBCTemplate class and create table
Employee with values (id, name,salary).

Employee Model Class >> public class Employee { private


int id; >> private String name; private
double salary; >> // Constructor public
Employee(int id, String name, double salary) { this.id = id;
>> this.name = name; >> this.salary = salary; } >>
// Getters and Setters >> public int getId() { return id; >> }
>> public void setId(int id) { this.id = id; >>
} >> public String getName() { return name; >> }>>
public void setName(String name) { this.name = name; >> } >>
public double getSalary() { return salary; >> } >> public void
setSalary(double salary) { this.salary = salary; >> } >>
@Override public String toString() { >> return
"Employee{id=" + id + ", name='" + name + "', salary=" + salary + "}"; >>
} >> }

Step 3: Create the EmployeeDAO Class

import org.springframework.jdbc.core.JdbcTemplate;

import org.springframework.jdbc.core.RowMapper;

import org.springframework.stereotype.Repository;

import java.util.List;

@Repository >> public class EmployeeDAO {

private final JdbcTemplate jdbcTemplate;

// Constructor injection of JdbcTemplate

public EmployeeDAO(JdbcTemplate jdbcTemplate) {

this.jdbcTemplate = jdbcTemplate; >> }

// Method to create the Employee table

public void createTable() {


String sql = "CREATE TABLE IF NOT EXISTS Employee (" +

"id INT PRIMARY KEY, " + >> "name VARCHAR(100), " +

"salary DOUBLE)"; >> jdbcTemplate.execute(sql);

} >> // Method to insert an employee into the Employee table

public int addEmployee(Employee employee) {

String sql = "INSERT INTO Employee (id, name, salary) VALUES (?,?, ?)";

return jdbcTemplate.update(sql, employee.getId(), employee.getName(),


employee.getSalary());

} >> // Method to fetch an employee by ID

public Employee getEmployeeById(int id) {

String sql = "SELECT * FROM Employee WHERE id = ?";

return jdbcTemplate.queryForObject(sql, new Object[]{id}, new


EmployeeRowMapper()); >> }

Step 4: Create Java Configuration Class

import org.springframework.context.annotation.Bean;

import org.springframework.context.annotation.Configuration;

import org.springframework.jdbc.core.JdbcTemplate;

import.org.springframework.jdbc.datasource.DriverManagerDataSource;
>> import javax.sql.DataSource; >> @Configuration

public class AppConfig {

// Define DataSource bean (H2 database for in-memory database)

@Bean >> public DataSource dataSource() {

DriverManagerDataSource dataSource = new


DriverManagerDataSource();

dataSource.setDriverClassName("org.h2.Driver");
dataSource.setUrl("jdbc:h2:mem:testdb;DB_CLOSE_DELAY=-1");
dataSource.setUsername("sa"); >> dataSource.setPassword("");
return dataSource; >> }
// Define JdbcTemplate bean >> @Bean public
JdbcTemplate jdbcTemplate(DataSource dataSource) { return new
JdbcTemplate(dataSource); >> } // Define
EmployeeDAO bean >> @Bean

public EmployeeDAO employeeDAO(JdbcTemplate jdbcTemplate) {


return new EmployeeDAO(jdbcTemplate); >> }>> }

Step 5: Create the Main Application Class

importorg.springframework.context.annotation.AnnotationConfigApplication
Context; public class App { >> public static void main(String[] args) {

try (AnnotationConfigApplicationContext context = new


AnnotationConfigApplicationContext(AppConfig.class)) {

EmployeeDAO employeeDAO = context.getBean(EmployeeDAO.class);

// Create the Employee table >> employeeDAO.createTable();

Employee employee1 = new Employee(1, "John Doe", 50000);

Employee employee2 = new Employee(2, "Jane Smith", 60000);

employeeDAO.addEmployee(employee1);

employeeDAO.addEmployee(employee2);

// Fetch and print all employees >> System.out.println("All Employees:");

employeeDAO.getAllEmployees().forEach(System.out::println);

System.out.println("Employee with ID 1: " +


employeeDAO.getEmployeeById(1));

// Update employee salary >>


employeeDAO.updateEmployeeSalary(1, 55000);
System.out.println("Updated Employee with ID 1: " +
employeeDAO.getEmployeeById(1)); >> } >> } >> }
Q.8. Write a spring configuration program for autowiring byname
pom.xml (for Maven):
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.3.24</version> <!-- Use the latest version -->
</dependency>
</dependencies>
Step 2: Define the Beans
GreetingService.java
public class GreetingService {
public String getGreeting() {
return "Hello, Spring!";
}
}
UserService.java
import org.springframework.beans.factory.annotation.Autowired;
public class UserService {
private GreetingService greetingService;
// Autowiring by name (spring will look for a bean named
'greetingService')
@Autowired
public void setGreetingService(GreetingService greetingService) {
this.greetingService = greetingService;
}
public void greetUser() {
System.out.println(greetingService.getGreeting() + " From
UserService!");
}
}
Step 3: Spring Configuration Class
AppConfig.java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class AppConfig {
// Define GreetingService bean (name will be 'greetingService')
@Bean
public GreetingService greetingService() {
return new GreetingService();
}
// Define UserService bean (name will be 'userService')
@Bean
public UserService userService() {
return new UserService();
}
}
Step 4: Main Application Class
App.java
Import.org.springframework.context.annotation.AnnotationConfigAp
plicationContext;
public class App {
public static void main(String[] args) {
// Initialize Spring context using AppConfig class
try (AnnotationConfigApplicationContext context = new
AnnotationConfigApplicationContext(AppConfig.class)) {
// Retrieve UserService bean from the Spring context
UserService userService = context.getBean(UserService.class);
// Call greetUser method which uses the GreetingService
userService.greetUser();
}
}
}

You might also like