I am trying to have unidirectional OneToOne relationship b/w two classes "Restaurant" and "Manager". "Manager" is child class which has one attribute called restaurantId. here is my code and problem is explained below it:
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}
I am trying to test add method for Manager.java in below test class:
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);
}
}
With above code I am expecting a new entry in Manager table, but It is trying to make entry in Restaurant Table.
here is console error in 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
please help me out here. Any suggestion would be great.:)