I'm using a test spring boot project to learn some hibernate. I have 2 interfaces extending CrudRepository - Address and Student both annotated with @Transactional and @Repository. Many students should share the same address.
@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;
etc.
@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;
etc. and the main class:
@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);
}
}
Problem is every time I run this code 2 new students are added and I don't see addressDao.delete(1) being executed, no exception is thrown, no log from hibernate is printed that it tries to delete the record. Also transaction is not rolled back. I can see both addressDao.delete(1) and exception if I remove (cascade = CascadeType.ALL) from Student.java but it also means I have to manually save address first before saving student. What do I do wrong?
Edit: I added Long removeByCity(String city); to my AddressDao and replaced addressDao.delete(1) with it. I see it returns 1 so looks like it gets executed but I still don't get any exception here. I'm getting exception only if I don't use save before.