我正在使用测试弹簧启动项目来学习一些休眠。我有2个扩展CrudRepository的接口 - Address和Student都用@Transactional和@Repository注释。许多学生应该共享相同的地址。
@Transactional
@Repository
public interface AddressDao extends CrudRepository<Address, Integer> {}
@Entity
public class Address {
@Id
@GeneratedValue
private int addressId;
private String street;
private String city;
private String state;
private String zipcode;
等
@Entity
public class Student {
@Id
@GeneratedValue
private long studentId;
@Column(nullable = false, length = 70)
private String studentName;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "studentAddress")
private Address studentAddress;
等。 和主要班级:
@SpringBootApplication
public class MainSpringBootClass extends SpringBootServletInitializer implements CommandLineRunner {
@Autowired
StudentDao studentDao;
@Autowired
AddressDao addressDao;
public static void main(String[] args) {
SpringApplication.run(MainSpringBootClass.class, args);
}
@Override
@Transactional
public void run(String... args) {
List<Address> list = new ArrayList<>();
addressDao.findAll().forEach(list::add);
Address address;
if (list.size() > 0) {
address = list.get(0);
} else {
address = new Address().withCity("London").withZipcode("W1J 9LL")
.withStreet("Piccadilly").withState("UK");
}
Student student1 = new Student().withName("Ann").withAddress(address);
Student student2 = new Student().withName("James").withAddress(address);
studentDao.save(student1);
studentDao.save(student2);
addressDao.delete(1);
addressDao.findAll().forEach(System.out::println);
}
}
问题是我每次运行此代码时都会添加2个新学生,并且我没有看到addressDao.delete(1)正在执行,没有抛出异常,没有打印来自hibernate的日志,它试图删除记录。事务也不会回滚。 如果我从Student.java中删除(cascade = CascadeType.ALL),我可以看到addressDao.delete(1)和异常,但这也意味着我必须在保存学生之前先手动保存地址。 我做错了什么?
编辑: 我补充道 long removeByCity(String city); 到我的AddressDao并用它替换了地址D.ao.delete(1)。我看到它返回1所以看起来它被执行但我仍然没有在这里得到任何异常。 只有在我之前不使用保存的情况下,我才会获得例外。