【发布时间】:2017-07-26 15:57:10
【问题描述】:
我尝试建立双向关系。我正在使用 Spring Boot 1.5.4.RELEASE 和 Spring Boot JPA 来生成我的存储库。我尝试保存两个相互关联的实体,但它不起作用。我评论了失败的测试语句。
我的实体:
司机:
@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> { }
汽车存储库:
@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的代码,如何持久化以及如何从数据库中取回代码? -
我更改了我的实体,发布了我的存储库类和我的单元测试。 :) 希望你能帮助我。
标签: java jpa entity bidirectional