hibernate annotation 一对多保存对象时不能插入外键
各位大侠,请帮帮小弟吧:在做一对多保存对象时出现不能插入外键的现象,这怎么解决,
@Entity@Table(name="TEACHERS")@SequenceGenerator(name="SEQ_TEACHERS",sequenceName="SEQ_TEACHERS")public class Teacher { private Long id; private String code; private String name; private String type; private List<Student> students; @Id @GeneratedValue(generator="SEQ_TEACHERS",strategy=GenerationType.SEQUENCE) @Column(name="id") public Long getId() { return id; } public void setId(Long id) { this.id = id; } @Column(name="CODE") public String getCode() { return code; } public void setCode(String code) { this.code = code; } @Column(name="NAME") public String getName() { return name; } public void setName(String name) { this.name = name; } @Column(name="TYPE") public String getType() { return type; } public void setType(String type) { this.type = type; } @OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER) @JoinColumn(name="TECH_ID",nullable=true,updatable=true) public List<Student> getStudents() { return students; } public void setStudents(List<Student> students) { this.students = students; }}
@Entity@Table(name="STUDENTS")@SequenceGenerator(name="SEQ_STUDENTS",sequenceName="SEQ_STUDENTS")public class Student { private Long id; private String code; private String name;// @Column(name="TECH_ID")// private Long techId; private Teacher teacher; @Id @GeneratedValue(generator="SEQ_STUDENTS",strategy=GenerationType.SEQUENCE) @Column(name="id") public Long getId() { return id; } public void setId(Long id) { this.id = id; } @Column(name="CODE") public String getCode() { return code; } public void setCode(String code) { this.code = code; } @Column(name="NAME") public String getName() { return name; } public void setName(String name) { this.name = name; } // public Long getTechId() {// return techId;// }// public void setTechId(Long techId) {// this.techId = techId;// } @ManyToOne(cascade=CascadeType.ALL) @JoinColumn(name="TECH_ID") public Teacher getTeacher() { return teacher; } public void setTeacher(Teacher teacher) { this.teacher = teacher; }}
public class AssociationsTest { /** * @param args */ public static void main(String[] args) {// SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory(); SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory(); Session session = sessionFactory.openSession(); Transaction trans = session.beginTransaction(); Teacher t = new Teacher(); t.setCode("000001"); t.setName("xiaoxue"); t.setType("shuxue"); List<Student> list = new ArrayList<Student>(); Student s0 = new Student(); s0.setCode("000001"); s0.setName("xioali"); list.add(s0); Student s1 = new Student(); s1.setCode("000002"); s1.setName("zhangsan"); list.add(s1); t.setStudents(list); session.save(t); trans.commit(); }}