大家好,我是一个真正的菜鸟和外行。我需要有关如何将项目从预订复制到bookinghist的帮助。
  假设我的Java类具有部分不同的字段。如何才能做到这一点?


List<Booking> booking= new ArrayList<Booking>();
List<BookingHist> bookinghist = new ArrayList<BookingHist>();


这是下面的预订类。
在这里,两个类之间唯一不同的字段是BookingHist有一个“额外”列。

public class Booking implements Serializable {

        @Temporal(TemporalType.TIMESTAMP)
        @Column(name = "dt")
        private Date dt = new Date();
        @Column(name = "bookingname")
        private String bookingname;

        public Booking(Date dt, String bookingname) {

            this.dt=dt;
            this.bookingname=bookingname;
        }

        public Date getDt() {
            return Dt;
        }

        public void setDt(Date Dt) {
            this.Dt = Dt;
        }

        public String getBookingname() {
            return Bookingname;
        }

        public void setBookingname(String Bookingname) {
            this.Bookingname = Bookingname;
        }
    }


这是BookingHist类。

public class BookingHist implements Serializable {

        @Temporal(TemporalType.TIMESTAMP)
        @Column(name = "dt")
        private Date dt = new Date();
        @Column(name = "bookingname")
        private String bookingname;
        @Column(name = "createdDt")
        private Date createdDt;

        public BookingHist(Date dt, String bookingname, Date createdDt) {

            this.dt=dt;
            this.bookingname=bookingname;
            this.createdDt=createdDt;
        }

        public Date getDt() {
            return Dt;
        }

        public void setDt(Date Dt) {
            this.Dt = Dt;
        }

        public String getBookingname() {
            return Bookingname;
        }

        public void setBookingname(String Bookingname) {
            this.Bookingname = Bookingname;
        }

        public Date getCreatedDt() {
            return createdDt;
        }

        public void setCreatedDt(Date createdDt) {
            this.createdDt = createdDt;
        }

    }

最佳答案

如果您在BookingHist中具有所有args构造函数,如下所示

public BookingHist(Date dt, String bookingname, String extras) {

     this.dt=dt;
     this.bookingname=bookingname;
     this.extras=extras;
 }


然后,您可以使用流将Booking转换为BookingHist

List<BookingHist> bookinghist = booking.stream()
                                       .map(b-> new BookingHist(b.getDate(), b.getBookingname(), "extra value");
                                       .collect(Collectors.toList());

10-04 17:16