Building a Java-Based Online Ticket Booking System involves creating a platform where users can search for events, book tickets, and manage their bookings. Below is a step-by-step guide to building such a system, including the key components, design considerations, and example code snippets.
1. Requirements Analysis
Before starting, define the requirements for the system:
- User Roles: Admin (manage events) and Customer (book tickets).
- Event Management: Add, update, delete, and view events.
- Ticket Booking: Search for events, book tickets, and view booking history.
- Payment Integration: Integrate a payment gateway for ticket payments.
- Reporting: Generate reports for event bookings and revenue.
2. System Design
Modules
- Event Management
- Add, update, delete, and view events.
- Ticket Booking
- Search for events, book tickets, and view booking history.
- Payment Integration
- Process payments for ticket bookings.
- Reporting
- Generate reports for event bookings and revenue.
- User Authentication
- Admin and customer login.
Database Design
- Event Table:
event_id
,name
,description
,date
,location
,total_tickets
,available_tickets
- Booking Table:
booking_id
,user_id
,event_id
,booking_date
,status
- User Table:
user_id
,username
,password
,role
3. Technology Stack
- Backend: Java (Spring Boot)
- Frontend: Thymeleaf (for simplicity) or Angular/React (for advanced UI)
- Database: MySQL or H2 (for testing)
- Build Tool: Maven or Gradle
- Security: Spring Security for authentication and authorization
- Payment Gateway: Integrate with a payment gateway like Stripe or PayPal
4. Implementation
Step 1: Set Up the Project
Create a Spring Boot project using Spring Initializr with the following dependencies:
- Spring Web
- Spring Data JPA
- Spring Security
- Thymeleaf (for UI)
- MySQL Driver (or H2 for testing)
Step 2: Define Entities
Create Java classes for the database tables.
Event.java
@Entity
public class Event {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long eventId;
private String name;
private String description;
private LocalDateTime date;
private String location;
private int totalTickets;
private int availableTickets;
// Getters and Setters
}
Booking.java
@Entity
public class Booking {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long bookingId;
private Long userId;
private Long eventId;
private LocalDateTime bookingDate;
private String status;
// Getters and Setters
}
User.java
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long userId;
private String username;
private String password;
private String role; // "ADMIN" or "CUSTOMER"
// Getters and Setters
}
Step 3: Create Repositories
Use Spring Data JPA to create repositories for database operations.
EventRepository.java
public interface EventRepository extends JpaRepository<Event, Long> {
List<Event> findByDateAfter(LocalDateTime date); // For upcoming events
}
BookingRepository.java
public interface BookingRepository extends JpaRepository<Booking, Long> {
List<Booking> findByUserId(Long userId); // For booking history
}
UserRepository.java
public interface UserRepository extends JpaRepository<User, Long> {
Optional<User> findByUsername(String username); // For authentication
}
Step 4: Implement Services
Create service classes to handle business logic.
EventService.java
@Service
public class EventService {
@Autowired
private EventRepository eventRepository;
public List<Event> getAllEvents() {
return eventRepository.findAll();
}
public void addEvent(Event event) {
eventRepository.save(event);
}
public void updateEvent(Long eventId, Event event) {
event.setEventId(eventId);
eventRepository.save(event);
}
public void deleteEvent(Long eventId) {
eventRepository.deleteById(eventId);
}
public List<Event> getUpcomingEvents() {
return eventRepository.findByDateAfter(LocalDateTime.now());
}
}
BookingService.java
@Service
public class BookingService {
@Autowired
private BookingRepository bookingRepository;
@Autowired
private EventRepository eventRepository;
public void bookTicket(Booking booking) {
Event event = eventRepository.findById(booking.getEventId()).orElseThrow();
if (event.getAvailableTickets() > 0) {
event.setAvailableTickets(event.getAvailableTickets() - 1);
eventRepository.save(event);
booking.setBookingDate(LocalDateTime.now());
booking.setStatus("BOOKED");
bookingRepository.save(booking);
} else {
throw new IllegalStateException("No tickets available");
}
}
public List<Booking> getBookingHistory(Long userId) {
return bookingRepository.findByUserId(userId);
}
}
Step 5: Create Controllers
Create controllers to handle HTTP requests.
EventController.java
@RestController
@RequestMapping("/events")
public class EventController {
@Autowired
private EventService eventService;
@GetMapping
public List<Event> getAllEvents() {
return eventService.getAllEvents();
}
@PostMapping
public void addEvent(@RequestBody Event event) {
eventService.addEvent(event);
}
@PutMapping("/{eventId}")
public void updateEvent(@PathVariable Long eventId, @RequestBody Event event) {
eventService.updateEvent(eventId, event);
}
@DeleteMapping("/{eventId}")
public void deleteEvent(@PathVariable Long eventId) {
eventService.deleteEvent(eventId);
}
}
BookingController.java
@RestController
@RequestMapping("/bookings")
public class BookingController {
@Autowired
private BookingService bookingService;
@PostMapping
public void bookTicket(@RequestBody Booking booking) {
bookingService.bookTicket(booking);
}
@GetMapping("/history/{userId}")
public List<Booking> getBookingHistory(@PathVariable Long userId) {
return bookingService.getBookingHistory(userId);
}
}
Step 6: Implement Security
Use Spring Security to secure the application.
SecurityConfig.java
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserRepository userRepository;
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.userDetailsService(username -> userRepository.findByUsername(username)
.orElseThrow(() -> new UsernameNotFoundException("User not found")));
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable()
.authorizeRequests()
.antMatchers("/events/**").hasRole("ADMIN")
.antMatchers("/bookings/**").hasRole("CUSTOMER")
.anyRequest().authenticated()
.and()
.httpBasic();
}
}
Step 7: Frontend (Optional)
Use Thymeleaf or a frontend framework like Angular/React to create a user interface for the system.
5. Testing
- Use JUnit and Mockito for unit testing.
- Test the application using Postman or Swagger for API testing.
6. Deployment
- Package the application as a JAR/WAR file and deploy it to a server (e.g., Tomcat).
- Use Docker for containerization and Kubernetes for orchestration (optional).
Example Use Cases
- Add an Event
- Admin adds a new event with details like name, description, date, location, and total tickets.
- Book a Ticket
- Customer books a ticket for an event, and the system updates the available tickets.
- View Booking History
- Customer views their booking history.