Spring-data-jpa OneToOne单向问题

时间:2014-09-16 08:10:22

标签: java eclipse hibernate jpa spring-data-jpa

我正在尝试单向OneToOne关系,而不是两个类“餐厅”和“经理”。 “Manager”是子类,它有一个名为restaurantId的属性。 这是我的代码和问题在下面解释:

Restaurant.java:

    @Entity
    public class Restaurant implements Serializable{

         @Id
         private long id;


    //getters and setters}

RestaurantRepository.java

import java.util.List;

import org.springframework.data.repository.CrudRepository;

public interface RestaurantRepository extends CrudRepository<Restaurant, Long> {
    List<Restaurant> findById(long id);
}

Manager.java:

@Entity
public class Manager implements Serializable {



    @Id
        @GeneratedValue(strategy=GenerationType.AUTO)
        private long id;
        @OneToOne(fetch=FetchType.LAZY,optional=false,cascade = CascadeType.ALL)
        @JoinColumn(name="restaurantId", referencedColumnName="id",nullable=false)
        private Restaurant restaurantId;

        //getters and setters}

我正在尝试在下面的测试类中测试Manager.java的add方法:

public class ManagerTest {

    private CrudRepository repository;
    @Test
    public void testAddManager() {
        AbstractApplicationContext context = new ClassPathXmlApplicationContext("spring-config.xml");

        CrudRepository restaurantRepository = context.getBean(RestaurantRepository.class);

        Date date = new Date();
        Restaurant restaurant = (Restaurant) restaurantRepository.findOne(1L);
        repository = context.getBean(ManagerRepository.class);
        createManager("x","xx","xxxxxxxx","x","x","x","India","null","null", date, "jimish@auberginesolutions.com", restaurant);

        context.close();

    }

    private void createManager(String firstName, String lastName, String contactNo, String addrStreet,String addrCity, String addrState, String addrCountry, String addrLat, String addrLong, Date birthDate, String email, Restaurant restaurant){
        Manager manager = new Manager(firstName, lastName, contactNo, addrStreet, addrCity, addrState, addrCountry, addrLat, addrLong, birthDate, email);
        manager.setRestaurantId(restaurant);
        repository.save(manager);

    }
}

使用上面的代码我希望在Manager表中有一个新条目,但它正在尝试在餐厅表中输入。

这是eclipse中的控制台错误:

    Hibernate: insert into Restaurant (addrCity, addrCountry, addrLat, addrLong, addrState, addrStreet, contactNo, maxCapacity, name, id) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
Sep 16, 2014 2:24:20 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
WARN: SQL Error: 1062, SQLState: 23000
Sep 16, 2014 2:24:20 PM org.hibernate.engine.jdbc.spi.SqlExceptionHelper logExceptions
ERROR: Duplicate entry '1' for key 'PRIMARY'
Sep 16, 2014 2:24:20 PM org.hibernate.engine.jdbc.batch.internal.AbstractBatchImpl release
INFO: HHH000010: On release of batch it still contained JDBC statements

请帮帮我。任何建议都会很棒。:)

1 个答案:

答案 0 :(得分:0)

您可能正在尝试添加包含已存在ID的条目

要么您忘记了AUTO_INCREMENT ID,要么为您的经理/餐厅选择了无效的(已存在的)ID。

您可以在那里找到更多详细信息 Error Code: 1062. Duplicate entry '1' for key 'PRIMARY'