日期:2014-05-19 浏览次数:20892 次
package com.model;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToMany;
@Entity
public class Classes {
private int id;
private List<Student> student = new ArrayList<Student>();
@OneToMany(mappedBy = "clas", cascade = { CascadeType.ALL })
public List<Student> getStudent() {
return student;
}
public void setStudent(List<Student> student) {
this.student = student;
}
@Id
@GeneratedValue
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
package com.model;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
@Entity
public class Student {
private int id;
private String name;
private String age;
private Classes clas;
@Id
@GeneratedValue
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
@ManyToOne(cascade = { CascadeType.ALL })
public Classes getClas() {
return clas;
}
public void setClas(Classes clas) {
this.clas = clas;
}
}
package com;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Configuration;
import com.model.Classes;
import com.model.Student;
public class Main {
/**
* @param args
*/
public static void main(String[] args) {
Student s= new Student();
Classes c = new Classes();
s.setClas(c);
System.out.println(s.getId()+"1");
// TODO Auto-generated method stub
SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
session.save(s);
session.save(c);
System.out.println(s.getId()+"2");
session.getTransaction().commit();
System.out.println(s.getId()+"4");
}
}