简体   繁体   中英

Multiple representations of the same entity are being merged (Hibernate)

I have two tables in my database - Restaurant and RestaurantTable. There is a @OneToMany relationship between them (a restaurant can have many tables). I am trying to add a table to my restaurant. I can add the first table, but as soon as I try to add another table it gives me the following error:

HTTP Status 500 - Request processing failed; nested exception is java.lang.IllegalStateException: Multiple representations of the same entity [RestaurantTable#6] are being merged. Detached: [Table number 6]; Detached: [Table number 5]

This is how my database looks like:

DROP TABLE IF EXISTS `restaurant`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `restaurant` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `restaurant_name` TEXT,
  `address` TEXT,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

DROP TABLE IF EXISTS `restaurant_table`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `restaurant_table` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `table_size` int,
  `table_number` int,
  `restaurant_id` int(11),
  PRIMARY KEY (`id`),
  FOREIGN KEY (`restaurant_id`) references `restaurant`(`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
/*!40101 SET character_set_client = @saved_cs_client */;

My Restaurant.java file:

@Entity
@Table(name="restaurant")
public class Restaurant {

    @Id
    @Column(name="id")
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    private Long id;

    @Column(name="restaurant_name")
    private String restaurantName;

    @Column(name="address")
    private String address;

    @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @JoinColumn(name="restaurant_id")
    private List<RestaurantTable> table = new ArrayList<RestaurantTable>();

    // Getters and setters

RestaurantTable.java:

@Entity
@Table(name="restaurant_table")
public class RestaurantTable {

    @Id
    @Column(name="id")
    @GeneratedValue(strategy= GenerationType.IDENTITY)
    private Long id;

    @Column(name="table_size")
    private int tableSize;

    @Column(name="table_number")
    private int tableNumber;

    @ManyToOne
    @JoinColumn(name="restaurant_id")
    private Restaurant restaurant;

    // Getters and setters

My RestaurantTableController.java:

@Controller
public class RestaurantTableController {

    @Autowired
    private RestaurantService restaurantService;

    @Autowired
    private RestaurantTableService restaurantTableService;

    @RequestMapping(value="restaurant/table/{id}", method = RequestMethod.GET)
    public String addRestaurantTable(Model model, @PathVariable Long id) {
        model.addAttribute("table", new RestaurantTable());
        return "newTable";
    }

    @RequestMapping(value = "restaurant/table/{id}", method = RequestMethod.POST)
    public String addRestaurantTable(@PathVariable Long id, @ModelAttribute ("table") RestaurantTable table) {
        Restaurant restaurant = restaurantService.getRestaurant(id);
        table.setRestaurant(restaurant);
        restaurant.getTable().add(table);
        restaurantService.updateRestaurant(restaurant);
        return "redirect:/bookings";
    }

}

And my updateRestaurant() method in RestaurantDaoImpl.java:

@Override
public void updateRestaurant(Restaurant restaurant) {
    Session session = this.sessionFactory.getCurrentSession();
    session.merge(restaurant);
    logger.info("Restaurant record updated successfully, Restaurant Details=" + restaurant);
}

Any help is appreciated!

EDIT: The Hibernate version I am using is 4.3.6.

Also, changed my Restaurant table declaration to:

@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER , mappedBy = "restaurant")
private List<RestaurantTable> table = new ArrayList<RestaurantTable>();

And it gives me the same error as before.

EDIT: I read that one solution for that is to change Cascade.ALL to not include MERGE, so the code would look like this:

@OneToMany(cascade = {CascadeType.PERSIST, CascadeType.REMOVE, CascadeType.DETACH, CascadeType.REFRESH}, fetch = FetchType.EAGER , mappedBy = "restaurant")
private List<RestaurantTable> table = new ArrayList<RestaurantTable>();

It doesn't give me an error, but it just doesn't do anything, nothing is changing.

Your Restaurant -> RestaurantTable relationship is being managed on both sides. Only one side of the relationship can be the owner of the relationship. In this case the RestaurantTable should be the owner of the relationship since its table will have the foreign key to the other table.

You need to change the Restaurant table property to indicate that the relationship is being managed by RestaurantTable restaurant property. JPA will now use that property for persisting.

Change the property declaration to

 @OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER , mappedBy = "restaurant")
 private List<RestaurantTable> table = new ArrayList<RestaurantTable>();

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