Mit Hibernate mehrere Datensätze löschen

Presler

Mitglied
In der Hibernate Doku bin ich zwar auf session.delete( object ) gestoßen, aber wenn ich z.B. mehrere IDs habe, hat Hibernate hierfür auch eine Funktion? Insebesondere auf Hinblick auf SQL Injection.
 
Du kannst delete() für jedes zu löschende Objekt aufrufen, oder du bastelst dir eine HQL-Query zum Löschen mit einer entsprechenden Where-Klausel.
 
die Ids werden offensichtlich von Nutzern irgendwo eingetippt,
bisschen mehr Infos (reiner String?) wären aber in der Tat nützlich
 
Hier nochmal zum besseren Verständis.
Ich bin gerad dabei mir eine DAO zuschreiben. Diese basiert noch zum größten Teil auf der GenericDAO aus dem Hibernate Tutorial.

Die Domain:
Code:
@Entity
@Table(name="T_USER")
public class User {
      /** integer primary key */
	  private long   id;
	
       /** string First name */
	  private String FirstName;

      /** string Middlename */
	  private String MiddleName;
	  
      /** string Last Name */
	  private String LastName;

      /** string Registration Email */
	  private String Email;
	  
      /** string Loginname */
	  private String Loginname;

      /** string Password */
	  private String Password;

      /** string activecode */
	  private String activecode;
	  
	  /** boolean active */
      private boolean active;

  	/**
  	 * constructor
  	 */      
     public User(String firstname, String lastname, String email) {
            this.FirstName = firstname;
            this.LastName  = lastname;
            this.Email     = email;
     }

	@Id
	@GeneratedValue
	/**
	 * @return the id
	 */
	public long getId() {
		return id;
	}

	/**
	 * @param id the id to set
	 */
	public void setId(long id) {
		this.id = id;
	}

	/**
	 * @return the firstName
	 */
	public String getFirstName() {
		return FirstName;
	}

	/**
	 * @param firstName the firstName to set
	 */
	public void setFirstName(String firstName) {
		FirstName = firstName;
	}

	/**
	 * @return the middleName
	 */
	public String getMiddleName() {
		return MiddleName;
	}

	/**
	 * @param middleName the middleName to set
	 */
	public void setMiddleName(String middleName) {
		MiddleName = middleName;
	}

	/**
	 * @return the lastName
	 */
	public String getLastName() {
		return LastName;
	}

	/**
	 * @param lastName the lastName to set
	 */
	public void setLastName(String lastName) {
		LastName = lastName;
	}

	/**
	 * @return the email
	 */
	public String getEmail() {
		return Email;
	}

	/**
	 * @param email the email to set
	 */
	public void setEmail(String email) {
		Email = email;
	}

	/**
	 * @return the loginname
	 */
	public String getLoginname() {
		return Loginname;
	}

	/**
	 * @param loginname the loginname to set
	 */
	public void setLoginname(String loginname) {
		Loginname = loginname;
	}

	/**
	 * @return the password
	 */
	public String getPassword() {
		return Password;
	}

	/**
	 * @param password the password to set
	 */
	public void setPassword(String password) {
		Password = password;
	}

	/**
	 * @return the activecode
	 */
	public String getActivecode() {
		return activecode;
	}

	/**
	 * @param activecode the activecode to set
	 */
	public void setActivecode(String activecode) {
		this.activecode = activecode;
	}

	/**
	 * @return the active
	 */
	public boolean isActive() {
		return active;
	}

	/**
	 * @param active the active to set
	 */
	public void setActive(boolean active) {
		this.active = active;
	}

	/* (non-Javadoc)
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		return "User [id=" + id + ", FirstName=" + FirstName + ", MiddleName="
				+ MiddleName + ", LastName=" + LastName + ", Email=" + Email
				+ ", Loginname=" + Loginname + ", Password=" + Password
				+ ", activecode=" + activecode + ", active=" + active + "]";
	}	  
	  
}

Das Interface:
Code:
import org.hibernate.criterion.Criterion;

public interface GenericDAO<T, ID extends Serializable> {
    public String   getTablename();    
	public int      doQuery( String query );          // SQL Statment absetzen
	public void     save(T obj);                      // save Object
	public T        load(ID id);                      // load Object
	public void     delete(ID[] ids);                 // Löschen mehrerer Datensätze anhand der ID
    public List<T>  find(int offset, int count, Criterion ... criterion);  // find objects
    public void     remove(ID[] ids, boolean remove); // mehrere Datensätze auf gelöscht setzen
    public void     publish(ID[] ids, boolean publish); // Publishing
    // Deleting
    // Ordering
}

Die DAO:
Code:
public abstract class GenericDAOImpl<T, ID extends Serializable>
       implements GenericDAO<T, ID> {
	   private Class<T> persistentClass;
	   private Session  session;
	   
	   /**
	    * Constructor
	    */
	   public GenericDAOImpl() {
	          this.persistentClass = (Class<T>) ((ParameterizedType) getClass()
	                                .getGenericSuperclass()).getActualTypeArguments()[0];
	   }

       /**
        * setSession
        * 
        * set the Session
        * 
        * @param  Session             the session
        */
	   @SuppressWarnings("unchecked")
	    public void setSession(Session s) {
	         this.session = s;
	    }

       /**
        * getSession
        * 
        * get the Session
        * 
        * @param  Session             the session
        */	   
	    protected Session getSession() {
	         if (session == null)
	            throw new IllegalStateException("Session has not been set on DAO before usage");
	         return session;
	    }

	   /**
	    * getPersistentClass
	    * 
	    * get the persistent class
	    * 
	    * @param  Class<T>             the class
	    */	   
	    public Class<T> getPersistentClass() {
	        return persistentClass;
	    }

	   /**
	    * save
	    * 
	    * save the given Object to the Database. It throw an
	    * HibernateException if an error occur
	    * 
	    * @param  Object             the to save Domain
	    */
	    public int doQuery( String sql ) {
		       Session     session = null;
               int         rows    = 0;
               
	    	    try {
	    	    	session     = getSession();
	    	    	Query query = session.createQuery( sql );
    			    rows        = query.executeUpdate();
	    	    } finally {
	    	 		   if (session != null) {
	     	 	 		  session.close();
	     	 	       }
	    	    }
	    	    
	    	    return rows;
	    }
	    
       /**
        * save
        * 
        * save the given Object to the Database. It throw an
        * HibernateException if an error occur
        * 
        * @param  Object             the to save Domain
        */
        public void save( T obj ) {
		      Session     session = null;
		      Transaction transaction = null;

    	      try {
    	    	  session     = getSession();
    	 		  transaction = session.beginTransaction();
    	    	  
    	 		  session.save( obj );
    	 		  transaction.commit();
    	      } catch ( HibernateException e ) {
    	 		   if (transaction != null) {
    	 	 		   transaction.rollback();
    	 	 		    throw e;
    	 		   }	  
    	      } finally {
    	 		   if (session != null) {
    	 	 		  session.close();
    	 	       }
    	      }
        }

        /**
         * load
         * 
         * load from database
         * 
         * @param   ID                 the id of the object to load
         * @return  Object             the to save Domain
         */        
        @SuppressWarnings("unchecked")
        public T load(ID id, boolean lock) {
            T entity;
            if (lock)
                entity = (T) getSession().load(getPersistentClass(), id, LockMode.UPGRADE);
            else
                entity = (T) getSession().load(getPersistentClass(), id);
     
            return entity;
        }
        
        /**
         * delete
         * 
         * deletes data rows, who is given by ID
         * 
         * @param   ID                 array of ids to delete
         * @return  Object             the to save Domain
         */        
        @SuppressWarnings("unchecked")
        public void delete(ID[] ids) {
               String str = Arrays.toString( ids );
               String query = "";
        }
        
        /**
         * find
         * 
         * get a list of selected data rows
         * 
         * @param   ID                 the id of the object to load
         * @return  Object             the to save Domain
         */        
        @SuppressWarnings("unchecked")
        public List<T> find(int offset, int count, Criterion ... criterion) {
                  Criteria crit = getSession().createCriteria(getPersistentClass());

                  for (Criterion c : criterion) {
                      crit.add(c);
                  }

                  if ( offset > 0 )
                     crit.setFirstResult( offset );
                  
                  if ( count > -1)
                     crit.setMaxResults( count );
                  
                  return crit.list();
        }
}

Mein Idee die dahinter steckt, ist auf einer Website werden die Benutzer als Tabelle zum selektieren per ID ausgegeben. D.h. bei z.B. löschen wird mir über den Request die IDs zurückgegeben. Diese werden an die Funktion "delete" an die DAO-Klasse zurückgegeben.

SQL Injection safed um es vor entsprechenden Hack-Angriffen zu schützen.

OK, hab mir kurz HSQL angesehen, um eine entsprechend SQL - Anweisung zusammenzusetzen, allerdings würde mir hierzu noch die Info fehlen wie ich aus der Domain den Tabellennamen erhalte, um eine allgemeingültige SQL - Anweisung zu erzeugen.

Hoffe diese Infos hilft etwas Licht ins Dunkel zu bringen.
 
Der Tabellenname ist entweder per default der Klassenname deines Entities oder kann mit der @Table Annotation festgelegt werden.

Wenn du im HQL Query mit Parametern und nicht mit String Konkanetation o.ä. arbeitest, sollte das in den meisten Fällen reichen um gegen SQL Injection abzusichern
 

Neue Themen


Zurück
Oben