[英]Unable to add an element to “one-to-many” relationship, hibernate.
I have the following problem: I am not able to add a new Car
to the corresponding Customer
entity. 我有以下问题:我无法将新的Car
添加到相应的Customer
实体。 The error is the following: 错误如下:
Duplicate entry 'test_login' for key 'UK_l4t3rudi0h7ibnjpnbvcnkcbf'
where 'test_login'
is the Customer
login. 其中'test_login'
是Customer
登录名。
Here the code for the Customer
entity 这是Customer
实体的代码
public class Customer{
@Id
@GeneratedValue
@Column (name = "id")
private int id;
@Column (name = "login", nullable = false, unique = true)
private String login;
@OneToMany(mappedBy = "customer", cascade = CascadeType.ALL)
private List<Vehicle> vehicles = new ArrayList<>();
public void addVehicle(Vehicle vehicle){
vehicle.setCustomer(this);
vehicles.add(vehicle);
}
}
For Vehicle
entity 对于Vehicle
实体
@Entity
@Table(name = "vehicle")
public class Vehicle implements Serializable {
@Id
@GeneratedValue
@Column (name = "id")
private int id;
@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
@JoinColumn(name = "customer_id")
private Customer customer;
}
DAO implementation class: DAO实现类:
public void addANewVehicle(Vehicle vehicle, Customer customer) {
customer.addVehicle(vehicle);
Session session = sessionFactory.openSession();
try {
session.getTransaction().begin();
session.save(customer);
session.getTransaction().commit();
} catch (Exception e) {
session.getTransaction().rollback();
logger.error("Error occurred while adding a new car. Error stack trace: " + e.toString());
} finally {
session.close();
}
@Column (name = "login", nullable = false, unique = true)
private String login;
Field login is set to unique, when save customer without primary key hibernate will create insert statement and Field login will duplicate. 字段登录设置为唯一,当没有主键的保存客户休眠时,hibernate将创建插入语句,并且字段登录将重复。
try to load customer and save it 尝试加载并保存客户
public void addANewVehicle(Vehicle vehicle, Customer customer) { public void addANewVehicle(车辆,客户)
Session session = sessionFactory.openSession();
try {
session.getTransaction().begin();
Customer cust = session.get(Customer.class,customer.getId());
cust.addVehicle(vehicle);
session.getTransaction().commit();
} catch (Exception e) {
session.getTransaction().rollback();
logger.error("Error occurred while adding a new car. Error stack trace: " + e.toString());
} finally {
session.close();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.