我試圖建立一個雙向關係。我使用Spring Boot 1.5.4.RELEASE和Spring Boot JPA來生成我的倉庫。我嘗試保存兩個相互關聯的實體,但它不起作用。我評論了那些失敗的測試報告。JPA雙向OneToOne不工作
我的entites:
司機:
@Entity
@ToString
@EqualsAndHashCode
public class Driver {
public static final String COLUMN_CAR = "car";
@Id
@GeneratedValue
private long id;
@Getter
@Setter
@OneToOne(cascade = CascadeType.ALL)
@JoinColumn(name = COLUMN_CAR)
private Car car;
}
汽車:
@Entity
@ToString
@EqualsAndHashCode
public class Car {
@Id
@GeneratedValue
private long id;
@Getter
@Setter
@OneToOne(mappedBy = Driver.COLUMN_CAR)
private Driver driver;
}
我使用過Spring JPA生成庫。
DriverRepository:
@Repository
public interface DriverRepository extends CrudRepository<Driver, Long> { }
CarRepository:
@Repository
public interface CarRepository extends CrudRepository<Car, Long> { }
測試:
@RunWith(SpringRunner.class)
@SpringBootTest
@Transactional
public class StackoverflowTest {
@Autowired
private DriverRepository driverRepository;
@Autowired
private CarRepository carRepository;
@Test
public void test1() {
Driver driver = driverRepository.save(new Driver());
Car car = carRepository.save(new Car());
driver.setCar(car);
driverRepository.save(driver);
/* Success, so the driver got the car */
driverRepository.findAll().forEach(eachDriver -> Assert.assertNotNull(eachDriver.getCar()));
/* Fails, so the car doesnt got the driver */
carRepository.findAll().forEach(eachCar -> Assert.assertNotNull(eachCar.getDriver()));
}
@Test
public void test2() {
Driver driver = driverRepository.save(new Driver());
Car car = carRepository.save(new Car());
car.setDriver(driver);
carRepository.save(car);
/* Success, so the car got the driver */
carRepository.findAll().forEach(eachCar -> Assert.assertNotNull(eachCar.getDriver()));
/* Fails, so the driver doesnt got the car */
driverRepository.findAll().forEach(eachDriver -> Assert.assertNotNull(eachDriver.getCar()));
}
}
在兩個測試中的最後一條語句失敗。有任何想法嗎?感謝您的建議。
你可以發佈你創建/獲取User和UserBan的代碼嗎?你如何保存它以及如何從數據庫中獲取? – Matt
我改變了我的實體,發佈了我的存儲庫類和我的單元測試。 :)希望你能幫助我出去。 –