为什么如果我运行此代码:
Student st = new Student();
st.setFirstName("First");
st.setLastName("Last");
st.setIndexNr("11");
st.setStudentPK(new StudentPK(0, user.getIdUser()));
studentFacade.create(st);
Mail m = new Mail();
m.setContent("con");
m.setRecipient("rec");
m.setIdMail(0);
mailFacade.create(m);
List<Mail> l = new ArrayList<Mail>();
l.add(m);
st.setMailList(l);
studentFacade.edit(st); // st have mailList property set to l
stud=studentFacade.findByIndex("11"); //after edit and get student he has mailList equal null
为什么在持久化和编辑对象后,我在 OneToMany 关系的属性中得到空值?
在数据库 MySql 我有STUDENT
表和MAIL
表:
CREATE TABLE IF NOT EXISTS `STUDENT` (
`id_student` MEDIUMINT UNSIGNED NOT NULL AUTO_INCREMENT ,
`first_name` VARCHAR(65) NULL ,
`last_name` VARCHAR(65) NULL ,
`index_nr` VARCHAR(45) NULL
)
ENGINE = InnoDB
CREATE TABLE IF NOT EXISTS `MAIL` (
`id_mail` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
`recipient` TEXT NULL ,
`content` TEXT NULL ,
`sender_student` MEDIUMINT UNSIGNED NULL ,
PRIMARY KEY (`id_mail`) ,
INDEX `fk_STUDENT_id_idx` (`sender_student` ASC) ,
CONSTRAINT `fk_STUDENT`
FOREIGN KEY (`sender_student` )
REFERENCES `jkitaj`.`STUDENT` (`id_student` )
ON DELETE CASCADE
ON UPDATE CASCADE
)
ENGINE = InnoDB
从数据库我在netbeans中生成实体:
@Entity
@Table(name = "STUDENT")
public class Student implements Serializable {
private static final long serialVersionUID = 1L;
@EmbeddedId
protected StudentPK studentPK;
@Size(max = 65)
@Column(name = "first_name")
private String firstName;
@Size(max = 65)
@Column(name = "last_name")
private String lastName;
@Size(max = 45)
@Column(name = "index_nr")
private String indexNr;
@OneToMany(mappedBy = "senderStudent",fetch=FetchType.EAGER)
private List<Mail> mailList;
//getters, setters ...
}
public class Mail implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue
@Basic(optional = false)
@Column(name = " id_mail")
private Integer idMail;
@Lob
@Size(max = 65535)
@Column(name = "recipient")
private String recipient;
@Lob
@Size(max = 65535)
@Column(name = "content")
private String content;
@JoinColumn(name = "sender_student", referencedColumnName = "id_student")
@ManyToOne
private Student senderStudent;
//getters, setters...
}
编辑:
我想我忘记了实体fetch
的@OneToMany
注释。Student
但是当我设置为fetch=FetchType.LAZY
我在编辑后再次获得空值并从数据库中获取已编辑的对象。当设置fetch=FetchType.EAGER
mailList
字段不为空时。为什么 ?