【问题标题】:Delete Row from MySql Table using Hibernate使用 Hibernate 从 MySql 表中删除行
【发布时间】:2016-07-28 11:19:50
【问题描述】:

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

马文 SpringMVC mysql 爪哇 日食

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

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

【问题讨论】:

    标签: mysql hibernate


    【解决方案1】:

    您不能删除瞬态对象。您需要先将对象与数据库同步。例如,您获得了库存组件的 id。这是一段示例代码,用于根据 stockId 删除对象。即使您使用休眠创建对象,它也会返回 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();
            }
        }
    

    【讨论】:

      【解决方案2】:

      Stock 对象处于瞬态状态,要删除它,它应该保留在数据库中还请注意,当您尝试删除任何对象时,应设置其主键,否则它将不会反映任何更改到数据库中 STOCK_ID 是这里的主键。

      【讨论】:

        猜你喜欢
        • 2016-10-29
        • 2016-10-01
        • 2012-10-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-11-12
        • 2011-07-18
        • 2015-08-23
        相关资源
        最近更新 更多