org.hibernate.PersistentObjectException:分离的实体传递给持久化:com.bookstore.entity.City

时间:2019-04-26 11:49:34

标签: java hibernate entity one-to-many one-to-one

我有3个表分别以客户城市地区命名。当客户表与城市连接时,城市被连接彼此。

当我通过hibernate保存客户信息时,错误如下所示。

org.hibernate.PersistentObjectException: detached entity passed to persist: com.bookstore.entity.City

我可以对所有这些表使用EAGER和Cascade选项,但没有任何方法可以解决问题。

这是桌子。

客户分类

@Entity
@Table(name="CUSTOMER",catalog = "JSPPROJECTDATABASE")
public class Customer implements Serializable{ 

...

@OneToOne(fetch = FetchType.EAGER,cascade = CascadeType.ALL)
@JoinColumn(name = "CITY")
private City city;

@OneToOne(fetch = FetchType.EAGER,cascade = CascadeType.ALL)
@JoinColumn(name = "DISTRICT")
private District district;

}

城市阶层

@Entity
@Table(name="CITY",catalog = "JSPPROJECTDATABASE")
public class City implements Serializable{

...

@OneToMany(fetch = FetchType.EAGER, mappedBy = "districtCity",cascade = CascadeType.ALL)
private Set<District> districts = new HashSet<District>();

@OneToOne(fetch = FetchType.EAGER, mappedBy = "city",cascade = CascadeType.ALL)
private Customer customer;
}

区级

@Entity
@Table(name = "DISTRICT", catalog = "JSPPROJECTDATABASE")
public class District implements Serializable {

...

@ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
@JoinColumn(name = "CITY_ID")
private City districtCity;


@OneToOne(fetch = FetchType.EAGER, mappedBy = "district")
private Customer customer;

}

这是客户的创建选项

String customerName = request.getParameter("customer_name");
            String customerSurname = request.getParameter("customer_surname");
            String customerPhoneNumber = request.getParameter("customer_phoneNumber");
            int cityId = Integer.parseInt(request.getParameter("city"));
            int districtId = Integer.parseInt(request.getParameter("district"));
            String customerAddress = request.getParameter("customer_address");
            String customerZipcode = request.getParameter("customer_zipCode");

            Customer newCustomer = new Customer();
            newCustomer.setName(customerName);
            newCustomer.setSurname(customerSurname);
            newCustomer.setPhoneNumber(customerPhoneNumber);
            newCustomer.setAddress(customerAddress);
            newCustomer.setZipCode(customerZipcode);

            City city = cityService.getCityById(cityId);
            District district = districtService.getDistrictById(districtId);

            newCustomer.setCity(city);
            newCustomer.setDistrict(district);

            customerService.createBook(newCustomer);

0 个答案:

没有答案