我试图使用Spring引导程序来使用Spring JPA存储库。我对春天来说是全新的,我只知道Spring到目前为止暴露给我的那么多冬眠。这不是很多。 这就是我正在尝试的
@Configuration
@EnableJpaRepositories
@Import(RepositoryRestMvcConfiguration.class)
@EnableAutoConfiguration
public class Application {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(Application.class);
UserRepo repo = context.getBean(UserRepo.class);
seedDB(repo);
for (User u: repo.findAll())
System.out.println(u);
}
private static void seedDB(UserRepo repo) {
Doctor jones = repo.save(new Doctor("Fred", "Jones"));
Doctor smith = repo.save(new Doctor("Rebbecca", "Smith"));
Patient balboa = repo.save(new Patient("Rocky", "Balboa", new Date()));
Patient locke = repo.save(new Patient("John", "Locke", new Date()));
Patient linus = repo.save(new Patient("Ben", "Linus", new Date()));
balboa.addDr2Ways(jones);//this adds jones to balboa's list of doctors and balboa to jones' list of patients
locke.addDr2Ways(smith);
locke.addDr2Ways(jones);
linus.addDr2Ways(smith);
repo.save(jones);
repo.save(smith);
repo.save(balboa);
repo.save(locke);
repo.save(linus);
}
在我尝试打印的循环中,我得到一个hibernate延迟初始化异常,因为没有会话。我做错了什么?
以下是对评论的回应:
医生和患者都继承用户如下:
@Entity
public abstract class User {
@Id @GeneratedValue private long ID;
private String firstName, lastName;
public User(){}
public User(String firstName, String lastName){
this.firstName = firstName;
this.lastName = lastName;
}
...
@Entity
public class Doctor extends User {
public Doctor(){}
public Doctor(String firstName, String lastName) {
super(firstName, lastName);
}
@ManyToMany
private List<Patient> patients = new ArrayList<>();
public String toString(){
String result = "dr " + super.getFirstName() + " has the following patients\n";
for (Patient p: patients)
result += p.getFirstName() + "\n";
return result;
}
public void addPatient1Way(Patient patient) {
patients.add(patient);
}
}
@Entity
public class Patient extends User {
public Patient(){}
public Patient(String firstName, String lastName, Date birthday) {
super(firstName, lastName);
this.birthday = birthday;
}
private Date birthday;
@ManyToMany(mappedBy = "patients")
private List<Doctor> doctors= new ArrayList<>();
public String toString(){
return "patient " + super.getFirstName();
}
public void addDr2Ways(Doctor dr) {
// TODO Auto-generated method stub
doctors.add(dr);
dr.addPatient1Way(this);
}
}