我有2个表:Trip and Place(多对一),我的问题是,当我添加2个具有不同数据但同一个地方的旅程时,它将2条记录添加到Trip表中,将2条记录添加到Place表中,应该只将一条记录添加到Place中。

例如,我有两次旅行的日期不同,但是他们在同一地方-意大利,罗马。因此,只有这些数据的地方记录:意大利,罗马。

如何在应用程序中避免此类行为?

行程类别:

public class Trip implements java.io.Serializable {
    private int idTrip;
    private int idHotel;
    private Date date;
    private int cost;
    private int profit;
    private String organisator;
    private int period;
    private String food;
    private String transport;
    private int persons;
    private int kidsAmount;

    private String ownerName;
    private String ownerLastName;

    private Place place;


+构造函数,get()和set()方法,

地方课程:

public class Place implements java.io.Serializable {

    private int idPlace;
    private String country;
    private String city;
    private String island;
    private String information;
    private Set<Trip> trips;


+构造函数,get()和set()方法,

行程映射文件:

<hibernate-mapping>
<class name="pl.th.java.biuro.hibernate.Trip" table="Trip">
    <id column="idTrip" name="idTrip" type="int">
        <generator class="native"/>
    </id>
    <property column="date" name="date" type="date"/>
    <property column="cost" name="cost" type="int"/>
    <property column="profit" name="profit" type="int"/>
    <property column="organisator" name="organisator" type="string"/>
    <property column="period" name="period" type="int"/>
    <property column="food" name="food" type="string"/>
    <property column="transport" name="transport" type="string"/>
    <property column="persons" name="persons" type="int"/>
    <property column="kidsAmount" name="kidsAmount" type="int"/>
    <property column="idHotel" name="idHotel" type="int"/>
    <many-to-one fetch="select" name="place" class="pl.th.java.biuro.hibernate.Place">
        <column name="idPlace" not-null="true"></column>
    </many-to-one>
</class>
</hibernate-mapping>


位置映射文件:

<hibernate-mapping>
<class name="pl.th.java.biuro.hibernate.Place" table="Place">
    <id column="idPlace" name="idPlace" type="int">
        <generator class="native"/>
    </id>
    <property column="country" name="country" type="string"/>
    <property column="city" name="city" type="string"/>
    <property column="island" name="island" type="string"/>
    <property column="information" name="information" type="string"/>
    <set name="trips" table="Trip" inverse="true" lazy="true" fetch="select">
        <key>
            <column name="idPlace" not-null="true" />
        </key>
        <one-to-many class="pl.th.java.biuro.hibernate.Trip" />
    </set>
</class>
</hibernate-mapping>


我还在我的MySQL数据库中添加了一些屏幕截图,也许有一些问题使我无法正确执行此操作:
MySQL database

编辑:在位置映射文件和在位置类中添加了一对多关系,但仍然遇到相同的问题。

EDIT2:将具有持久实体的代码添加到数据库中:

Session session = DatabaseConnection.getFactory().openSession();
        Transaction tx = null;
        try {
            tx = session.beginTransaction();

                trip.setPlace(place);
                session.save(place);
                session.save(trip);

            tx.commit();
        } catch (HibernateException e) {
            if (tx != null) {
                tx.rollback();
            }
            System.out.println("Exception found while adding new trip: " + e.getMessage());
            e.printStackTrace();
        } finally {
            session.close();
        }


但是我仍然遇到同样的问题...我在地点A添加了一次旅行,然后在下一步中添加了同样的旅行,这就是我得到的结果:


EDIT3:创建行程和位置对象:

Trip trip = null;
    Place place = null;

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    String dateInString = tripDateField.getText();
    java.util.Date date = null;
    try {
        date = sdf.parse(dateInString);
        place = new Place(tripCountryField.getText(), tripCityField.getText(), tripIslandField.getText(), tripPlaceInfoTextArea.getText());
        int period = 0, persons = 0, kidsAmount = 0;

        //W razie braku niewymaganych liczbowych danych ustawiane są wartości -1
        if (tripPeriodField.getText().equals("")) {
            period = -1;
        }
        if (tripPersonsField.getText().equals("")) {
            persons = -1;
        }
        if (tripKidsAmountField.getText().equals("")) {
            kidsAmount = -1;
        }

    trip = new Trip(new Date(date.getTime()), Integer.parseInt(tripCostField.getText()), Integer.parseInt(tripProfitField.getText()),
                tripOrganisatorField.getText(), period, tripFoodField.getText(), tripTransportField.getText(),
                persons, kidsAmount, tripClientNameField.getText(), tripClientLastNameField.getText());

} catch (ParseException ex) {
        Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex);
        try {
            date = sdf.parse("0000-00-00");
        } catch (ParseException ex1) {
            Logger.getLogger(MainFrame.class.getName()).log(Level.SEVERE, null, ex1);
        }
    } catch (NumberFormatException e) {
        place = new Place("111", "111", "111", "111");
        trip = new Trip(null, WIDTH, WIDTH, dateInString, WIDTH, dateInString, dateInString, WIDTH, ABORT, dateInString, dateInString);

        System.out.println("Exception while getting trip / place data: " + e.toString());
    }

    dataEdition.addTrip(trip, place, dataEdition.validateTripData(trip, place), addRemoveSearchTripDialog);


我从textFields获得这些对象数据,并在需要时将它们解析为int,所以我猜应该没问题。之后,我将这两个对象传递到另一个方法中,在其中将它们持久保存到数据库中。

最佳答案

您似乎在每个提交中都创建了一个新位置。

Place place = new Place(tripCountryField.getText(), tripCityField.getText(), tripIslandField.getText(), tripPlaceInfoTextArea.getText());


然后您希望Hibernate以某种方式神奇地确定您可能实际上想使用数据库中的现有条目。

这是行不通的。

如果提交的位置已经存在,那么您需要以某种方式加载现有的持久性实体并进行处理。

您可以通过允许用户选择一个现有地点并通过ID发送该地点来解决此问题,也可以查询匹配的地点
在表单提交上。

例如

Place place = myDatabaseService.findPlace(country, name ...) //does not account for misspellings

if(place == null){
     place = new Place(tripCountryField.getText(), tripCityField.getText(), tripIslandField.getText(), tripPlaceInfoTextArea.getText());
}

关于java - hibernate 时冗余数据映射多对一,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30445241/

10-10 16:31
查看更多