所以我在尝试让我的创建用户函数工作时遇到了一点麻烦。我正在尝试从扫描仪控制台为每个新用户条目创建一个新用户,但我的 Hibernate 正在更新相同的人员 ID,而不是为新用户分配新的人员 ID。
我的DAO类:
public void createDoctor(Doctor doctor) {
sessionFactory = HibernateUtil.getSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
session.save(doctor);
session.getTransaction().commit();
session.close();
sessionFactory.close();
}
我的主要课程:
int adminNum = sc.nextInt();
if (adminNum == 1) {
System.out.print("Please enter doctor's first name: ");
sc.nextLine();
String firstName = sc.nextLine();
System.out.print("Please enter doctor's last name: ");
String lastName = sc.nextLine();
Doctor d = new Doctor();
d.setFirstName(firstName);
d.setLastName(lastName);
doctorList.add(d);
int index = doctorList.indexOf(d);
dao.createDoctor(doctorList.get(index));
}
医生类:
import java.util.*;
import javax.persistence.*;
@Entity
public class Doctor extends Person {
@OneToOne
@JoinColumn(name = "SPECIALTY_ID")
private Specialty specialty;
@OneToMany(mappedBy = "doctor", targetEntity = Patient.class,fetch=FetchType.EAGER, cascade= CascadeType.ALL )
private List<Patient> patients;
private double salary;
public Doctor(){
patients = new ArrayList<Patient>();
}
public void setSalary(double salary) {
this.salary = salary;
}
public double getSalary() {
return salary;
}
public void setSpecialty(Specialty specialty) {
this.specialty = specialty;
}
public Specialty getspecialty() {
return specialty;
}
public void setPatient(Patient patient){
patients.add(patient);
}
public List<Patient> getPatients(){
return patients;
}
}
人员类:
package edu.cs157b.medicalSystem;
import javax.persistence.*;
@Entity
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class Person {
@Id
@GeneratedValue(strategy = GenerationType.TABLE)
@Column(name = "PERSON_ID")
private int personId;
private String first_name;
private String last_name;
private char sex;
public Person() {
}
public int getPersonId() {
return personId;
}
public void setPersonId(int personId) {
this.personId = personId;
}
public void setFirstName(String first_name) {
this.first_name = first_name;
}
public String getFirstName() {
return first_name;
}
public void setLastName(String last_name) {
this.last_name = last_name;
}
public String getLastName() {
return last_name;
}
public void setSex(char sex){
this.sex = sex;
}
public char getSex(){
return sex;
}
}
在您的Person
类中将 id 字段声明为 Integer
,以便新创建的实例将具有空值作为personId
。基元 int
类型将始终具有 0
作为初始值。
@Id
@GeneratedValue(strategy = GenerationType.TABLE)
@Column(name = "PERSON_ID")
private Integer personId;
我不太喜欢这段代码。
就个人而言,我更喜欢有一个做某事的 ctor 而不是一个无所事事的默认 ctor 并且不得不调用 setter。
我会保留医生,然后将其添加到列表中。
这是同步的吗? 如果该列表是共享的可变数据,则看起来线程不安全。
我在这里没有看到等价或哈希代码。 这也许可以解释它。 最好使用主键字段来确定相等性。
我认为您迫切需要一个教程。 暂时忘记你的作业,做一些简单的事情:
http://docs.jboss.org/hibernate/core/3.3/reference/en-US/html/tutorial.html