Class.hbm.xml--------
<!DOCTYPE hibernate-mapping PUBLIC 
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping>

<class name="entity.Class" table="CLASS">
<id name="id">
<generator class="native"/>
</id>
<property name="name" column="NAME"/>
<set name="students" inverse="true" cascade="all">
<key column="CLASS_ID"/>
<one-to-many class="entity.Student" />
</set>
</class></hibernate-mapping>
Student.hbm.xml---------
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC 
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"><hibernate-mapping>

<class name="entity.Student" table="STUDENT">
<id name="id">
<generator class="native"/>
</id>
<property name="name" column="NAME"/>
<many-to-one name="cls" class="entity.Class" column="CLASS_ID"/>
</class></hibernate-mapping>
hibernate.cjg.xml-----
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory name="foo">
<!-- Database connection setting -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
        <property name="connection.url">jdbc:mysql://localhost:3306/ssh</property>
        <property name="connection.username">root</property>
        <property name="connection.password">oyp</property>        <!-- JDBC connection pool (use the built-in) -->
        <property name="connection.pool_size">2</property>        <!-- SQL dialect -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
        
<!-- Enable Hibernate's current session context -->
<property name="current_session_context_class">org.hibernate.context.ManagedSession</property>

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>        <!-- Echo all executed SQL to stdout -->
        <property name="show_sql">true</property>        <!-- Drop and re-create the database schema on startup -->
        <property name="hbm2ddl.auto">update</property>

        <mapping resource="entity/Class.hbm.xml"/>
       <mapping resource="entity/Student.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Student.java----实体类
package entity;public class Student {
private Long id;
private String name;
private Class cls; public Long getId() {
return id;
} public void setId(Long id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public Class getCls() {
return cls;
} public void setCls(Class cls) {
this.cls = cls;
}
}
Class.java---实体类
package entity;public class Student {
private Long id;
private String name;
private Class cls; public Long getId() {
return id;
} public void setId(Long id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public Class getCls() {
return cls;
} public void setCls(Class cls) {
this.cls = cls;
}
}
StudentDAO--student的数据访问层
package dao;import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;import util.CreateSession;import entity.Student;public class StudentDAO { public void add(Student student){
Session session = CreateSession.getSession();
if(session == null){
return;
}
Transaction t = session.beginTransaction();
try{
session.save(student);
t.commit();
}catch(Exception e){
t.rollback();
e.printStackTrace();
}finally{
session.close();
}
}

public void update(Student student){
Session session = CreateSession.getSession();
if(session == null){
return;
}
Transaction t = session.beginTransaction();
try{
session.update(student);
t.commit();
}catch(Exception e){
t.rollback();
e.printStackTrace();
}finally{
session.close();
}
}

public void delete(Student student){
Session session = CreateSession.getSession();
if(session == null){
return;
}
Transaction t = session.beginTransaction();
try{
session.delete(student);
t.commit();
}catch(Exception e){
t.rollback();
e.printStackTrace();
}finally{
session.close();
}
}

}
ClassDAO.java-----class类的数据访问层
package dao;import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;import util.CreateSession;
import entity.Class;public class ClassDAO {

public void add(Class cls){
Session session = CreateSession.getSession();
if(session == null){
return;
}
Transaction t = session.beginTransaction();
try{
session.save(cls);
t.commit();
}catch(Exception e){
t.rollback();
e.printStackTrace();
}finally{
session.close();
}
}

public void update(Class cls){
Session session = CreateSession.getSession();
if(session == null){
return;
}
Transaction t = session.beginTransaction();
try{
session.update(cls);
t.commit();
}catch(Exception e){
t.rollback();
e.printStackTrace();
}finally{
session.close();
}
}

public void delete(Class cls){
Session session = CreateSession.getSession();
if(session == null){
return;
}
Transaction t = session.beginTransaction();
try{
session.delete(cls);
t.commit();
}catch(Exception e){
t.rollback();
e.printStackTrace();
}finally{
session.close();
}
}
}
Test.java------测试类package test;import java.util.*;import dao.ClassDAO;
import dao.StudentDAO;
import entity.Class;
import entity.Student;public class Test { public static void main(String[] args) {
//add();
//updateClass();
//updateStudent();
deleteClass();
}

public static void add(){
Class c = new Class();
c.setName("班级1");

Student s =  new Student();
s.setName("学生1");
s.setCls(c);
Set<Student> set = new HashSet<Student>(); 
set.add(s);
c.setStudents(set);
new ClassDAO().add(c);
//new StudentDAO().add(s);
}

public static void updateClass(){
Class c = new Class();
c.setId(1L);
c.setName("class1");
c.setStudents(null);
new ClassDAO().update(c);
} public static void updateStudent(){
Student s = new Student();
s.setId(1L);
s.setName("student1");
Class c = new Class();
c.setId(1L);
s.setCls(c);
new StudentDAO().update(s);
}

public static void deleteClass(){
Class c = new Class();
c.setId(1L);
new ClassDAO().delete(c);
}

public static void deleteStudent(){
Student s = new Student();
s.setId(1L);
new StudentDAO().delete(s);
}

}
================================================================
删除class表中的数据报错----
org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:94)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:275)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:266)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:172)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:50)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1027)
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:365)
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:137)
at dao.ClassDAO.delete(ClassDAO.java:55)
at test.Test.deleteClass(Test.java:54)
at test.Test.main(Test.java:16)
Caused by: java.sql.BatchUpdateException: Cannot delete or update a parent row: a foreign key constraint fails (`ssh`.`student`, CONSTRAINT `FKBACA0E1B133588CF` FOREIGN KEY (`CLASS_ID`) REFERENCES `class` (`id`))
at com.mysql.jdbc.ServerPreparedStatement.executeBatch(ServerPreparedStatement.java:657)
at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:70)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:268)
... 10 more
高手帮忙啊!!!!

解决方案 »

  1.   

    package util;import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.cfg.Configuration;public class CreateSession {

    public static Session getSession(){
    SessionFactory sessionFactory = null;
    try{
    sessionFactory = new Configuration().configure().buildSessionFactory();
    return sessionFactory.openSession();
    }catch (Exception e) {
    e.printStackTrace();
    }finally{
    sessionFactory.close();
    }
    return null;
    }

    }
    还有这sessionFactory生成类
      

  2.   


    Caused by: java.sql.BatchUpdateException: Cannot delete or update a parent row: a foreign key constraint fails (`ssh`.`student`, CONSTRAINT `FKBACA0E1B133588CF` FOREIGN KEY (`CLASS_ID`) REFERENCES `class` (`id`))
    删除一个类时 这个类有外键关联
      

  3.   

    首先获取对象,如果对象不为空,则更新操作
    如果对象为空,则Could not execute JDBC batch update错误
      

  4.   

    那怎么配置级联删除啊?
    比如有一个id=1的class,he一个class_id为1的student,现在我要删除class,同时这个student也要删除!该怎么配置?!
      

  5.   

    级联删除中,通过配置关系从来达到级联删除的功能。。
    <set name="students" inverse="true" cascade="all">
     cascade="all" 这句代码代表可以级联删除
      

  6.   

    可以将cascade="all"或者设置为cascade="delete"这也会级联的删除