多地多关联的增加,修改和删除

package com.score.test;

import java.util.HashSet;
import java.util.Properties;

import javax.naming.InitialContext;
import javax.naming.NamingException;

import com.score.dao.CourseDAO;
import com.score.dao.ScoreDAO;
import com.score.dao.StudentDAO;
import com.score.entity.Course;
import com.score.entity.Score;
import com.score.entity.Student;

public class TestScore {

	/**
	 * @param args
	 * @throws NamingException 
	 */
	public static void main(String[] args) throws NamingException {
		Properties props=new Properties();
	      props.setProperty("java.naming.factory.initial","org.jnp.interfaces.NamingContextFactory");
	      props.setProperty("java.naming.provider.url","localhost:1099");
	      props.setProperty("java.naming.factory.url.pkgs","org.jboss.naming");
		InitialContext cxt=new InitialContext(props);
		try{
		
			ScoreDAO sdao=(ScoreDAO)cxt.lookup("ScoreDAOBean/remote");
			StudentDAO studao=(StudentDAO)cxt.lookup("StudentDAOBean/remote");
			CourseDAO coudao=(CourseDAO)cxt.lookup("CourseDAOBean/remote");
			Score s1=new Score();
			Score s2=new Score();
			Student stu1=studao.findStudentById(new Integer(1));
			Course c1=coudao.findCourseById(new Integer(1));
			Course c2=coudao.findCourseById(new Integer(2));
			
			HashSet<Course> hs=new HashSet<Course>();
			hs.add(c1);
			hs.add(c2);
			
			stu1.setCourses(hs);
			studao.updateStudent(stu1);
			
			s1.setCourse(c1);
			s1.setStudent(stu1);
			s1.setScore(99d);
			
			s2.setCourse(c2);
			s2.setStudent(stu1);
			s2.setScore(98d);
			
			sdao.addScore(s1);
			sdao.addScore(s2);
			
		}catch(Exception e){
			e.printStackTrace();
		}

	}

}
 
由于没有设置级联增加,所有这里手工增加。
修改关联表:
               try{
			ScoreDAO scoredao=(ScoreDAO)cxt.lookup("ScoreDAOBean/remote");
			List<Score> ls=scoredao.findScoreByStudentId(new Integer(1));
			for(Score s:ls){
				s.setScore(100);
				scoredao.updateScore(s);
			}
		}catch(Exception e){
			e.printStackTrace();
		}
 
删除学生:
                      try{
			ScoreDAO scoredao=(ScoreDAO)cxt.lookup("ScoreDAOBean/remote");
			StudentDAO studao=(StudentDAO)cxt.lookup("StudentDAOBean/remote");
			List<Score> ls=scoredao.findScoreByStudentId(new Integer(1));
			for(Score s:ls){
				//s.setScore(100);
				//scoredao.updateScore(s);
				Student stu=s.getStudent();
				studao.deleteStudent(stu.getId());
				s.setStudent(null);
				scoredao.updateScore(s);
			}
报错:
java.lang.reflect.UndeclaredThrowableException
	at $Proxy1.deleteStudent(Unknown Source)
	at com.score.test.TestDelete.main(TestDelete.java:33)
Caused by: java.lang.ClassNotFoundException: javax.persistence.EntityExistsException
	at org.jboss.remoting.serialization.ClassLoaderUtility.loadClass(ClassLoaderUtility.java:82)
	at org.jboss.remoting.loading.RemotingClassLoader.loadClass(RemotingClassLoader.java:76)
	at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:320)
	at java.lang.Class.forName0(Native Method)
	at java.lang.Class.forName(Class.java:247)
	at org.jboss.remoting.loading.ObjectInputStreamWithClassLoader.resolveClass(ObjectInputStreamWithClassLoader.java:174)
	at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1575)
	at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1496)
	at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1732)
	at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1329)
	at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1947)
	at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1871)
	at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1753)
	at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1329)
	at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1947)
	at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1871)
	at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1753)
	at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1329)
	at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1947)
	at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1871)
	at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1753)
	at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1329)
	at java.io.ObjectInputStream.readObject(ObjectInputStream.java:351)
	at org.jboss.remoting.serialization.impl.java.JavaSerializationManager.receiveObjectVersion2_2(JavaSerializationManager.java:239)
	at org.jboss.remoting.serialization.impl.java.JavaSerializationManager.receiveObject(JavaSerializationManager.java:133)
	at org.jboss.remoting.marshal.serializable.SerializableUnMarshaller.read(SerializableUnMarshaller.java:120)
	at org.jboss.remoting.transport.socket.MicroSocketClientInvoker.versionedRead(MicroSocketClientInvoker.java:957)
	at org.jboss.remoting.transport.socket.MicroSocketClientInvoker.transport(MicroSocketClientInvoker.java:586)
	at org.jboss.remoting.MicroRemoteClientInvoker.invoke(MicroRemoteClientInvoker.java:122)
	at org.jboss.remoting.Client.invoke(Client.java:1634)
	at org.jboss.remoting.Client.invoke(Client.java:548)
	at org.jboss.aspects.remoting.InvokeRemoteInterceptor.invoke(InvokeRemoteInterceptor.java:62)
	at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:101)
	at org.jboss.aspects.tx.ClientTxPropagationInterceptor.invoke(ClientTxPropagationInterceptor.java:67)
	at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:101)
	at org.jboss.aspects.security.SecurityClientInterceptor.invoke(SecurityClientInterceptor.java:53)
	at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:101)
	at org.jboss.ejb3.remoting.IsLocalInterceptor.invoke(IsLocalInterceptor.java:74)
	at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:101)
	at org.jboss.ejb3.stateless.StatelessRemoteProxy.invoke(StatelessRemoteProxy.java:107)
	at $Proxy1.deleteStudent(Unknown Source)
	at com.score.test.TestDelete.main(TestDelete.java:33)
	at org.jboss.aspects.remoting.InvokeRemoteInterceptor.invoke(InvokeRemoteInterceptor.java:74)
	at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:101)
	at org.jboss.aspects.tx.ClientTxPropagationInterceptor.invoke(ClientTxPropagationInterceptor.java:67)
	at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:101)
	at org.jboss.aspects.security.SecurityClientInterceptor.invoke(SecurityClientInterceptor.java:53)
	at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:101)
	at org.jboss.ejb3.remoting.IsLocalInterceptor.invoke(IsLocalInterceptor.java:74)
	at org.jboss.aop.joinpoint.MethodInvocation.invokeNext(MethodInvocation.java:101)
	at org.jboss.ejb3.stateless.StatelessRemoteProxy.invoke(StatelessRemoteProxy.java:107)
	... 2 more
 

删除的顺序不对,看JBOSS报错:

Caused by: java.sql.BatchUpdateException: Cannot delete or update a parent row: a foreign key constraint fails (`ejb3/tb_score`, CONSTRAINT `FKFACAA58158DBE5D8` FOREIGN KEY (`student_id`) REFERENCES `tb_student` (`id`))
	at com.mysql.jdbc.PreparedStatement.executeBatchSerially(PreparedStatement.java:1213)
	at com.mysql.jdbc.PreparedStatement.executeBatch(PreparedStatement.java:912)
	at org.jboss.resource.adapter.jdbc.WrappedStatement.executeBatch(WrappedStatement.java:519)
	at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:48)
	at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:246)
	... 36 more

 

先删除关联表的记录后才能删除:

                    try{
			ScoreDAO scoredao=(ScoreDAO)cxt.lookup("ScoreDAOBean/remote");
			StudentDAO studao=(StudentDAO)cxt.lookup("StudentDAOBean/remote");
			List<Score> ls=scoredao.findScoreByStudentId(new Integer(1));
			for(Score s:ls){
				//s.setScore(100);
				//scoredao.updateScore(s);
				scoredao.deleteScore(s.getId());
								
			}

这里还不能删除student,因为他还跟course表有关联。

 

-------------------------------------------------------------------------------------------------------------------------

若是级联删除,可以直接删除student的,若级联删除的是score,score这个关联表被删除了。

@OneToMany(mappedBy="student",cascade=CascadeType.REMOVE)
	public Set<Score> getScores() {
		return scores;
	}
	public void setScores(Set<Score> scores) {
		this.scores = scores;
	}
 

SQL输出:

delete 
    from
        tb_score 
    where
        id=?
23:35:22,343 INFO  [STDOUT] Hibernate: 
    delete 
    from
        tb_score 
    where
        id=?
23:35:22,343 INFO  [STDOUT] Hibernate: 
    delete 
    from
        tb_student 
    where
        id=?
但是怎么连student和course的关联表也删除了呢?----级联的意思:不仅删除自己,
也删除与自己关联的对象(关联表)---暂且这么理解,有待严格的验证。
这里由于student对course没有设置级联删除,否则连同course表的级联也没有了。。。
 

你可能感兴趣的:(删除)