使用Hibernate从MySql表中删除行

时间:2016-07-28 11:19:51

标签: mysql hibernate

你好我是一个更新鲜的我只是从网上拿了我的应用程序试图运行它我正在使用的参数是

的Maven 用SpringMVC Mysql的 Java的 蚀

我能够使用此代码和delet在数据库中创建一个表但是当我尝试使用保存选项检测它时它会给我错误 **** org.hibernate.event.def.DefaultDeleteEventListener deleteTransientEntity INFO:在删除处理中处理瞬态实体**** 当我在线检查它显示在app.java页面中获取行的对象然后删除该对象以删除行我不知道如何获取该对象以及如何传递该数据库的行对象(如何将该字段嵌入到对象中以及如何获取该对象)plz帮助我想要的是从数据库中删除某些列名特定值的行

App.java类

package com.mkyong.common;
import org.hibernate.Session;
import com.mkyong.persistence.HibernateUtil;

public class App 
{
    public static void main( String[] args )
    {
        System.out.println("Maven + Hibernate + MySQL");
        Session session = HibernateUtil.getSessionFactory().openSession();

        session.beginTransaction();
        Stock stock = new Stock();

        stock.setStockCode("4715");
        stock.setStockName("GENM");

        stock.getStockCode();
        stock.getStockName();

        //session.save(stock);

        session.delete(stock);

        session.getTransaction().commit();


    }
}

AppTest.java

package com.mkyong.common;

import junit.framework.Test;
import junit.framework.TestCase;
import junit.framework.TestSuite;

/**
 * Unit test for simple App.
 */
public class AppTest 
    extends TestCase
{
    /**
     * Create the test case
     *
     * @param testName name of the test case
     */
    public AppTest( String testName )
    {
        super( testName );
    }

    /**
     * @return the suite of tests being tested
     */

public static Test suite()
{
    return new TestSuite( AppTest.class );
}

/**
 * Rigourous Test :-)
 */
public void testApp()
{
    assertTrue( true );
}

}

Stock.java

package com.mkyong.common;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;

@Entity
@Table(name = "stock", catalog = "gagan", uniqueConstraints = {
        @UniqueConstraint(columnNames = "STOCK_NAME"),
        @UniqueConstraint(columnNames = "STOCK_CODE") })
public class Stock implements java.io.Serializable {

    private Integer stockId;
    private String stockCode;
    private String stockName;

    public Stock() {
    }

    public Stock(String stockCode, String stockName) {
        this.stockCode = stockCode;
        this.stockName = stockName;
    }

    @Id
    @GeneratedValue(strategy = IDENTITY)
    @Column(name = "STOCK_ID", unique = true, nullable = false)
    public Integer getStockId() {
        return this.stockId;
    }

    public void setStockId(Integer stockId) {
        this.stockId = stockId;
    }

    @Column(name = "STOCK_CODE", unique = true, nullable = false, length = 10)
    public String getStockCode() {
        return this.stockCode;
    }

    public void setStockCode(String stockCode) {
        this.stockCode = stockCode;
    }

    @Column(name = "STOCK_NAME", unique = true, nullable = false, length = 20)
    public String getStockName() {
        return this.stockName;
    }

    public void setStockName(String stockName) {
        this.stockName = stockName;
    }

}

 HibernateUtil.java 



   package com.mkyong.persistence;

    import org.hibernate.SessionFactory;
    import org.hibernate.cfg.AnnotationConfiguration;

    public class HibernateUtil {

        private static final SessionFactory sessionFactory = buildSessionFactory();

        private static SessionFactory buildSessionFactory() {
            try {
                // Create the SessionFactory from hibernate.cfg.xml
                return new AnnotationConfiguration().configure().buildSessionFactory();

            }
            catch (Throwable ex) {
                // Make sure you log the exception, as it might be swallowed
                System.err.println("Initial SessionFactory creation failed." + ex);
                throw new ExceptionInInitializerError(ex);
            }
        }

        public static SessionFactory getSessionFactory() {
            return sessionFactory;
        }

        public static void shutdown() {
            // Close caches and connection pools
            getSessionFactory().close();
        }

    }

hibernatecfg.xml

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
    <session-factory>
      <!-- Database connection settings -->
     <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
     <!-- Database connection settings -->

     <!-- UAT Database connection settings -->
  <property name="connection.url">jdbc:mysql://localhost:3306/gagan</property>
     <property name="connection.username">root</property>
     <property name="connection.password">123456</property>
     <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
  <property name="show_sql">true</property>
         <property name="hibernate.hbm2ddl.auto">update</property>
         <!-- Think Before made any change in below flag may that clean you   complete database -->
        <mapping class="com.mkyong.common.Stock"></mapping>
    </session-factory>
</hibernate-configuration>

的pom.xml

 <project xmlns="http://maven.apache.org/POM/4.0.0"         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
      <modelVersion>4.0.0</modelVersion>
      <groupId>com.mkyong.common</groupId>
      <artifactId>HibernateExample</artifactId>
      <packaging>jar</packaging>
      <version>1.0-SNAPSHOT</version>
      <name>HibernateExample</name>
      <url>http://maven.apache.org</url>

      <repositories>
        <repository>
          <id>JBoss repository</id>
          <url>http://repository.jboss.com/maven2/</url>
        </repository>
      </repositories>



      <dependencies>


        <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>3.8.1</version>
          <scope>test</scope>
        </dependency>

        <!-- MySQL database driver -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.9</version>
        </dependency>

        <!-- Hibernate core -->
        <dependency>
            <groupId>hibernate</groupId>
            <artifactId>hibernate3</artifactId>
            <version>3.2.3.GA</version>
        </dependency>

        <!-- Hibernate annotation -->
     <dependency>
       <groupId>org.hibernate</groupId>
       <artifactId>hibernate-entitymanager</artifactId>
       <version>4.3.5.Final</version>
      </dependency>
      <dependency>
       <groupId>org.hibernate</groupId>
       <artifactId>hibernate-c3p0</artifactId>
       <version>4.3.5.Final</version>
      </dependency>
        <!-- Hibernate library dependecy start -->
        <dependency>
            <groupId>dom4j</groupId>
            <artifactId>dom4j</artifactId>
            <version>1.6.1</version>
        </dependency>

        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.1.1</version>
        </dependency>

        <dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
            <version>3.2.1</version>
        </dependency>


        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>2.2</version>
        </dependency>
        <!-- Hibernate library dependecy end -->

      </dependencies>
    </project>
[1]: http://i.stack.imgur.com/tkv2h.png

2 个答案:

答案 0 :(得分:0)

您无法删除瞬态对象。您需要首先将对象与数据库同步。例如,您获得了库存组件的ID。以下是基于stockId删除对象的示例代码。即使使用hibernate创建对象,它也会返回ID。使用此ID从数据库中删除行。

Session session = HibernateUtil.getSessionFactory().openSession();
    try {
        session.beginTransaction();
        Serializable id =  stockId;
        Object persistentInstance = session.load(Stock.class, id);
        if (persistentInstance != null)  {
            session.delete(persistentInstance);
            session.getTransaction().commit();
            System.out.println ("Deleted Sucessfully"); 

        }
        else {
            System.out.println ("Did not find the  Stock Object in persistance");

        }

    } 
    catch (HibernateException e) {
        e.printStackTrace();

    }

    finally {
        if(session!=null){
            session.close();
        }
    }

答案 1 :(得分:0)

Stock对象处于Transient状态,要删除它,它应该在数据库中保留,还要注意当你尝试删除任何对象时,它的主键应该用它来设置,否则它不会将任何变化反映到数据库中< strong> STOCK_ID 是主键。