hibernate总是自己删除表中的所有数据

时间:2010-09-14 14:53:18

标签: java hibernate orm

您好我正在开发一个使用hibernate连接到存储文件的mysql数据库的spring mvc应用程序。

我有两种方法。一个添加我选择的特定文件路径中的所有文件,另一个调用查询的方法返回一个从mysql存储的文件列表。

问题是这个。当我自己执行第一个方法,即填充数据库,它工作正常我可以从mysql命令行看到该表的内容。然而,当我在填充后立即执行查询方法时,该表的内容立即完全消失。好像hibernate只是暂时将数据存储在mysql中或者mysql中的某个地方,它会删除数据并且不会保留它们。

这是填充表格的方法:

/**
     * Test Method: ideal for another class to do this kind of work and this
     * pass the FileObject into this class
     */
    public void addSomeFiles() {
        System.out.println("addSomeFiles");
        File dir = new File(picturesPath);
        String[] fileNames = dir.list();

        for (int i = 0; i < fileNames.length; i++) {

            System.out.println(fileNames[i]);
            File file = new File(picturesPath + "\\" + fileNames[i]);
            if (file.isFile()) {
                FileObject fileO = contstructFileObject(file);
                if (fileO == null) {
                    System.out.println("fileO is null!!!!!");
                } else {
                    // addFile(fileO);

                    dbFileHelper.addFile(fileO);
                }
            }

        }

        System.out.println("//////////////");
        // File file;

    }

......... Hibernate模板类........

public class DbFileHelper implements DbFileWrapper {


    private HibernateTemplate hbTemplate;
    //private static final String SQL_GET_FILE_LIST = "select filename, size, id, type from fileobject";
    private static final String SQL_GET_FILE_LIST = "select new FileObject(filename, size, id, type) from FileObject";

    public DbFileHelper() {

    }

    public void setHbTemplate(HibernateTemplate hbTemplate) {
        System.out.println("setHbTemplate");
        System.out.println("///////////////////");
        System.out.println("///////////////////");
        System.out.println("///////////////////");

        this.hbTemplate = hbTemplate;
    }





    // ////////////////////////////////////////////////

    @Override
    public String addFile(FileObject file) {
        // TODO Auto-generated method stub
        System.out.println("addFile using hibernate");

        if (hbTemplate == null) {
            System.out.println("hbTemplate is null!! why?");
        }
        hbTemplate.saveOrUpdate(file);
        hbTemplate.flush();

        return "added succesfuly";
    }

以下是进行查询的另一种方法:

........................

public JSONArray getFileList(String type){

    return constructJsonArray(dbFileHelper.getFileList(ALL));
}

private JSONArray constructJsonArray(List<FileObject> fileList ){

    JSONArray mJsonArray = new JSONArray();

    for (int i = 0; i < fileList.size(); i++) {
        System.out.println("fileName = " + fileList.get(i).getFilename() );
        //mJson.put("Filename", fileList.get(i).getFileName() );

        mJsonArray.add( new JSONObject().put("File ID", fileList.get(i).getId() ));
        mJsonArray.add( new JSONObject().put("Filename", fileList.get(i).getFilename() ));
        mJsonArray.add( new JSONObject().put("File type", fileList.get(i).getType()));
        mJsonArray.add( new JSONObject().put("File Size", fileList.get(i).getSize()));
    }

    return mJsonArray;
}

.......... hibernate Template类.......

private static final String SQL_GET_FILE_LIST = "select new FileObject(filename, size, id, type) from FileObject";

@Override
public List<FileObject> getFileList(String type) {
    // TODO Auto-generated method stub
    List<FileObject> files = hbTemplate.find(SQL_GET_FILE_LIST);
    //hbTemplate.flush();
    return files;
}

..........

最后,这是一个打印屏幕,显示我最初放在我的桌子里但是自己消失了:

http://img411.imageshack.us/img411/9553/filelisti.jpg

我在这里遗漏了什么吗?

编辑:其他信息。

我的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 package="com.kc.models.FileObject" >

    <class name="com.kc.models.FileObject" table="fileobject">
        <id name="id" column="ID">
            <generator class="native" />
        </id>
        <property name="filename" type="string" column="FILENAME" />
        <property name="type" type="string" column="TYPE" />
        <property name="size" type="double" column="SIZE" />
        <property name="file" type="blob" length="1000000000" column="FILE" />
    </class> 

</hibernate-mapping> 

我的控制员:

@Override
public ModelAndView handleRequest(HttpServletRequest request,
        HttpServletResponse response) throws Exception {
    // TODO call a method that returns a list of Mobile Apps.


    testAddingSomeFilesToDb();
    return new ModelAndView("" + "testJsonResponse", "jsonArray",
            getFileList() );

}


private void testAddingSomeFilesToDb() {
    ctx = new ClassPathXmlApplicationContext("zang-file-service.xml");
    FileHelper file = (FileHelper) ctx.getBean("fileHelper");
    file.addSomeFiles();
}

/**
 * Get file list from sql server based on type
 * @return file list in json
 */ 
private JSONArray getFileList() {
    // TODO: Get request parameter that states what type of file extensions
    // the client wants to recieve

    ctx = new ClassPathXmlApplicationContext("zang-file-service.xml");
    FileHelper file = (FileHelper) ctx.getBean("fileHelper");

    return file.getFileList("all");
}

另一个编辑:

我的.xml文件配置会话工厂和休眠模板

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:jee="http://www.springframework.org/schema/jee"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
       http://www.springframework.org/schema/jee
       http://www.springframework.org/schema/jee/spring-jee-2.0.xsd">

    <!-- http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-2.0.xsd -->

    <!-- Config properties files -->



    <!-- Hibernate database stuff -->



    <!-- <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> 
        <property name="locations"> <list> <value>/properties/jdbc.properties</value> 
        </list> </property> </bean> -->


    <!-- <bean id="dataSource1" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> 
        <property name="driverClassName" value="${database.driver}" /> <property 
        name="url" value="${database.url}" /> <property name="username" value="${database.user}" 
        /> <property name="password" value="${database.password}" /> </bean> -->


    <bean id="dataSource1"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.jdbc.Driver" />
        <property name="url" value="jdbc:mysql://localhost:3306/zangshop" />
        <property name="username" value="root" />
        <property name="password" value="password" />

    </bean>


    <!-- LocalSessionFactoryBean u need to put the hbm files in the WEB-INF/classes 
        root director -->

    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource1"></property>
        <property name="mappingResources">
            <list>
                <value>FileObject.hbm.xml</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.hbm2ddl.auto">create</prop>
            </props>
        </property>
    </bean>


    <bean id="hbTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
        <property name="sessionFactory" ref="sessionFactory"></property>
    </bean>

    <bean id="dbFileHelper" class="com.kc.models.DbFileHelper">
        <property name="hbTemplate" ref="hbTemplate"></property>
    </bean>

    <bean id="fileHelper" class="com.kc.models.FileHelper">
        <property name="dbFileHelper" ref="dbFileHelper"></property>
    </bean>

</beans>

3 个答案:

答案 0 :(得分:8)

我已经修复了问题

我改变了<prop key="hibernate.hbm2ddl.auto">create</prop>

<prop key="hibernate.hbm2ddl.auto">update</prop>并且有效

答案 1 :(得分:0)

您是否在通话之间创建/销毁SessionFactory?您可以将hbm2ddl.auto属性设置为create-drop吗?

实际上,你可以显示Hibernate设置吗?

参考

答案 2 :(得分:0)

在我的情况下,表也被自动删除,以下解决方案对我有用: org.hibernate.dialect.MySQL8Dialect 使用 MySQL 方言附加版本号。 因为提交没有被 org.hibernate.dialect.MySQLDialect 提前执行。