0

I have created a number of entity classes from the database using the JPA.

These are the classes:

  1. Flights
  2. Passengers
  3. PassengersFlights (containing primary key of passengers and flights)
  4. Users

In the database, there are two foreign keys in the PassengersFlights table - one to Flights and one to Passengers.

The only problem I have is that the primary keys of passengers and flights are of data type Passengers and Flights in the PassengersFlights entity class. However, the data types of these in their respective entity classes are String and int, as defined in the database.

I have the following code to update the PassengersFlights table:

// Updating the Passengers_Flights table
try
{
    Class.forName("com.mysql.jdbc.Driver");
    Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/flights_db", "root", "hello");

    EntityManagerFactory emFactory = Persistence.createEntityManagerFactory("Flights_AssignmentPU");
    EntityManager em = emFactory.createEntityManager();

    PassengersFlights booking = new PassengersFlights();
    booking.setPassportNum(passport);
    booking.setFlightId(flight_id);
    em.getTransaction().begin();
    em.persist(booking);
    em.getTransaction().commit();
    em.close();
}
catch (Exception e)
{
    response.sendRedirect("ErrorPage.html");
}

The problem I am having is when setting the passport number and the flight id. In the project, they are defined as string and int. However, it is expecting Passenger and Flights data types. How can I solve this problem please?

1
  • Is PassengersFlights a table with two columns(passenger and flight) you should not design a extra class for PassengersFlights. Use an n-m relation between Flights and Passengers. Commented Dec 7, 2012 at 10:40

1 Answer 1

1

If passport and flight_id are primary keys of their respectable entities, you can use getReference() to obtain a proxy object of required type with the given primary key:

booking.setPassportNum(em.getReference(Passenger.class, passport));
booking.setFlightId(em.getReference(Flight.class, flight_id));

Also note that if Passengers_Flights is just a link table without extra fields you can model the relationship between passengers and flights using @ManyToMany, without separate entity for the link table.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.