简体   繁体   English

Java-持久性和实体类

[英]Java - Persistence and Entity Classes

I have created a number of entity classes from the database using the JPA. 我已经使用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. 在数据库中,PassengersFlights表中有两个外键-一个到Flights,一个到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. 我唯一的问题是旅客和航班的主键是PassengersFlights实体类中的数据类型“旅客”和“航班”。 However, the data types of these in their respective entity classes are String and int, as defined in the database. 但是,它们各自的实体类中的数据类型为String和int,如数据库中所定义。

I have the following code to update the PassengersFlights table: 我有以下代码来更新PassengersFlights表:

// 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. 我遇到的问题是在设置护照号码和航班ID时。 In the project, they are defined as string and int. 在项目中,它们被定义为string和int。 However, it is expecting Passenger and Flights data types. 但是,它需要旅客和航班数据类型。 How can I solve this problem please? 请问该如何解决?

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: 如果passportflight_id是他们尊敬的实体的主键,你可以使用getReference()来获得所需要的类型与所定的主键的代理对象:

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. 还要注意,如果Passengers_Flights只是一个没有额外字段的链接表,则可以使用@ManyToMany为乘客和航班之间的关系@ManyToMany ,而无需为链接表提供单独的实体。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM