gpt4 book ai didi

java - 表 "vehicle"上的插入或更新违反了外键约束,车辆与用户表具有多对一关系

转载 作者:行者123 更新时间:2023-12-02 03:10:55 25 4
gpt4 key购买 nike

我有两个表“用户”和“车辆”。

  • 用户与车辆具有一对多关系,并且
  • 车辆与用户具有多对一的关系。

第一次添加用户和车辆运行良好。当我尝试向现有用户添加新车辆时出现异常

ERROR: insert or update on table "vehicle" violates foreign key constraint "fk2q70uto2vl2oh4enr071s58yb"
Detail: Key (vehicleid)=(4) is not present in table "usertraveldo".
UserDO
@Entity
@Table(name="usertraveldo")
public class UserTravelDO implements Serializable {
@GenericGenerator(name = "gen", strategy = "increment")
@GeneratedValue(generator = "gen")
@Id
private int id;
private String username;
private String password;
private String hint;
private String firstname;
private String middlename;
private String lastname;
private Boolean status;

@JoinColumn(name="addressid")
@OneToOne(cascade = CascadeType.ALL)
private AddressTravelDO address;

@JoinColumn(name="roleid")
@ManyToOne(cascade = CascadeType.ALL)
private RoleMasterDO role;

@Column (name = "vehicleid",updatable=false, insertable=false)
@JsonIgnore
@JoinColumn(name="vehicleid")
@OneToMany(cascade = CascadeType.ALL ,fetch =FetchType.EAGER)
private List<VehicleTravelDO> vehicle = new ArrayList<VehicleTravelDO>();
}

车辆DO

@Entity
@Table(name="vehicle")
public class VehicleTravelDO implements Serializable {


@GenericGenerator(name = "gen", strategy="increment")
@GeneratedValue(generator = "gen")
@Id
//@Column (name = "vehicleid")
private int vehicleid;
private String vehicletype;
private String vehiclenumber;
private int totalseats;
private int availableseats;
@JsonIgnore
@JoinColumn(name="id")
@ManyToOne(cascade = CascadeType.ALL, fetch =FetchType.EAGER)
private UserTravelDO user;
}

异常

Hibernate: insert into vehicle (availableseats, totalseats, id, vehiclenumber, vehicletype, vehicleid) values (?, ?, ?, ?, ?, ?)
2016-12-09 12:58:59.742 WARN 5872 --- [nio-9001-exec-6] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 0, SQLState: 23503
2016-12-09 12:58:59.743 ERROR 5872 --- [nio-9001-exec-6] o.h.engine.jdbc.spi.SqlExceptionHelper: ERROR: insert or update on table "vehicle" violates foreign key constraint "fk2q70uto2vl2oh4enr071s58yb"
Detail: Key (vehicleid)=(4) is not present in table "usertraveldo".
2016-12-09 12:58:59.743 INFO 5872 --- [nio-9001-exec-6] o.h.e.j.b.internal.AbstractBatchImpl: HHH000010: On release of batch it still contained JDBC statements
2016-12-09 12:58:59.743 ERROR 5872 --- [nio-9001-exec-6] org.hibernate.internal.SessionImpl: HHH000346: Error during managed flush [could not execute statement]
2016-12-09 12:58:59.751 WARN 5872 --- [nio-9001-exec-6] o.a.cxf.phase.PhaseInterceptorChain: Application {}TravelServiceImpl has thrown exception, unwinding now

服务代码

   public Response addVehicle(VehicleTravelBo vehicle) {
// TODO Auto-generated method stub
UserTravelDO userDO = new UserTravelDO();
Session session = travelHibernateDao.getSessionFactory().getCurrentSession();
/*Query query = session.createQuery(HQL_LOAD_ALL_USER_ID);
query.setParameter("id", vehicle.getUserid());
userDO = (UserTravelDO) query.uniqueResult();*/

userDO = session.get(UserTravelDO.class, vehicle.getUserid());
if(userDO == null)
{
System.out.println("notexist");
}
else
{
System.out.println(userDO.getId());
VehicleTravelDO vehicleDO = ProfileDtoConverter.convertBOtoDO(vehicle);
vehicleDO.setUser(userDO);
session.save(vehicleDO);
}
HashMap praf= new HashMap();
praf.put("message", "user updated");
//System.out.println("Leavetable updated successfully");
return Response.ok(praf).build();

}

从两天开始,我就在为此奋斗。

最佳答案

首先,您应该在事务中工作。

public Response addVehicle(VehicleTravelBo vehicle) {
Session session = travelHibernateDao.getSessionFactory().getCurrentSession();
session.getTransaction().begin();


UserTravelDO userDO = session.get(UserTravelDO.class, vehicle.getUserid());
if(userDO == null)
{
System.out.println("notexist");
}
else
{
System.out.println(userDO.getId());
VehicleTravelDO vehicleDO = ProfileDtoConverter.convertBOtoDO(vehicle);
userDO.addVehicle(vehicleDO);
}

session.getTransaction().commit();
HashMap praf= new HashMap();
praf.put("message", "user updated");
//System.out.println("Leavetable updated successfully");
return Response.ok(praf).build();

}

第二。您的类 UserTravelDO 应该具有以下方法

public void addVehicle(VehicleTravelDO vehicleTravelDO){
vehicleTravelDO.setUser(this);
vehicle.add(vehicleTravelDO);
}

当您在 tx 中工作时,Hibernate 会进行脏检查,因此当您添加新车辆时,它会检测到它,然后执行相应的调用(可能在 tx 提交时执行)。

第三。不要在您的 private UserTravelDO user; 字段上使用 cascade = CascadeType.ALL。让我们考虑一下您想要删除单个车辆;那么由于级联,适当的用户也应该被删除。

第四。您的映射不正确。在您的 UserTravelDO 类 中使用

@JsonIgnore
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
private List<VehicleTravelDO> vehicle = new ArrayList<VehicleTravelDO>();

同时更改类VehicleTraverDO。使用以下映射

@JsonIgnore
@ManyToOne
@JoinColumn(name="user_id")
private UserTravelDO user;

请明确您的关联。如果您有 oneToMany(就像许多 VehicleTravelDO 与一个 UserTravelDO 关联一样,那么您应该在 vehicle 表中包含列 user_id ,代表用户的外键。

现在,您的车辆表中应该有 user_id 列,这是用户表的外键。

关于java - 表 "vehicle"上的插入或更新违反了外键约束,车辆与用户表具有多对一关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41073381/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com