简体   繁体   中英

Adding values from another table

Simple app with spring boot so I'm using jpa, hibernate etc.

User is adding values to trip_data, two of this values are in columns shown below.

| ID | trip_data_begin | trip_data_end | 

|  1  |     x1         |     y1        |

|  2  |     x2         |     y2        |



|  ID | counter_data_begin | counter_data_end |

|  1  |        x1          |        y2        |

x1 - smallest value

y2 - highest value

What I want is to copy two of this values to counter_data. I was able to this with query but when user add another row and y3 is higher than y2 then values in counter_data are incorrect. Maybe operate only on the last copied row in counter_data?

I would be very grateful for your help

@Entity
@Table(name = "trip_data")
public class TripData {
    @Id
    @GeneratedValue(generator = "inc")
    @GenericGenerator(name = "inc", strategy = "increment")
    private int id;
    private int tripDateBegin;
    private int hourBegin;
    private String townBegin;
    private String countryBegin;
    private long tripCounterBegin;
    private int tripDateEnd;
    private int hourEnd;
    private String townEnd;
    private String countryEnd;
    private long tripCounterEnd;

    public TripData() {
    }

   //getters and setters



@Entity
@Table(name = "counters_data")
public class CountersData {
    @Id
    @GeneratedValue(generator = "inc")
    @GenericGenerator(name = "inc", strategy = "increment")
    private int id;
    private long counterDataBegin;
    private long counterDataEnd;

    public CountersData() {
    }
// getters adn setters

What I understood:

You have a table trip_data and want to store the lowest value of trip_data_begin and the highest value of trip_data_end in another table.

This approach is possible but not a good idea since every time the trip_data table is updated, you have to update the trip_counter table. Instead of keeping this information in a separate table, a better design would be to calculate these fields whenever they are needed. You can do this directly in the database or in a service.

I suggest going with the first option. Therefore, you'd have to create a method in your TripDataRepository . Here is some (kind-of) pseudo code for the method in your TripDataRepository interface (supposed to depict the idea, the syntax may not be 100% correct)

@Query("SELECT Min(d.tripDateBegin) FROM TripData d")
int getTripBegin();

Every time you get a new TripData, and you need to create/or/update your tripCounter;

Select min(date_col),max(second_date_col) from tripdata;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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