Hibernate中,一对多的查询和修改。

下面是我的测试用例,仅供大家参考。

package com.xaygc;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Set;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

public class Test {
public void FindStudent() {
Session session = HibernateSessionFactory.getSession();
Student student = (Student) session.get(Student.class, 6);
System.out.println(student.getStuId() + " " + student.getStuName()
+ " " + student.getStuAddress());
Set<Event> events = student.getEvents();
for (Event event : events) {
System.out.println(event);
}
System.exit(0);
HibernateSessionFactory.closeSession();
}

public void FindEvent() {
Session session = HibernateSessionFactory.getSession();
Event event = (Event) session.get(Event.class, 2);
System.out.println(event);
System.out.println(event.getStudent());
System.exit(0);
HibernateSessionFactory.closeSession();
}

public void SaveStudent() {
Session session = HibernateSessionFactory.getSession();
Transaction t = session.beginTransaction();
Event event = new Event("编写代码");
event.setStudent(new Student("郭卫东", 24, "男", "13217979535", "北京市海淀区"));
try {
session.save(event);
t.commit();
} catch (Exception e) {
t.rollback();
} finally {
HibernateSessionFactory.closeSession();
}
}

public void save() {
Session session = HibernateSessionFactory.getSession();
Transaction t = session.beginTransaction();
Event event = new Event("编写代码");
try {
session.save(event);
t.commit();
} catch (Exception e) {
t.rollback();
} finally {
HibernateSessionFactory.closeSession();
}
}

public void changeEvent(){
Session session=HibernateSessionFactory.getSession();
Transaction t=session.beginTransaction();
Student student1=(Student)session.get(Student.class, 6);
Student student2=(Student)session.get(Student.class, 7);
Event event=(Event)session.get(Event.class, 1);
try{
student1.getEvents().remove(event);
student2.getEvents().add(event);
event.setStudent(student2);
t.commit();
}catch(Exception e){
t.rollback();
}finally{
HibernateSessionFactory.closeSession();
}
}

public void changeEvent2(){
Session session=HibernateSessionFactory.getSession();
Transaction t=session.beginTransaction();
Student student1=(Student)session.get(Student.class, 6);
// Student student2=(Student)session.get(Student.class, 7);
Event event=(Event)session.get(Event.class, 1);
try{
// student1.getEvents().remove(event);
// student2.getEvents().add(event);
event.setStudent(student1);
t.commit();
}catch(Exception e){
t.rollback();
}finally{
HibernateSessionFactory.closeSession();
}
}

public static void main(String[] args) {
Test test = new Test();
// test.FindStudent();
// test.FindEvent();
// test.SaveStudent();
// test.save();
// test.changeEvent();
test.changeEvent2();
}
}
展开阅读全文

没有更多推荐了,返回首页