java - 使用java在mysql数据库中创建和插入文件

标签 java mysql hibernate

<分区>

我想同时使用 hibernate 创建我的文件(只是 .txt 文件)并将其插入到 MySQL 数据库中,我卡在了这一部分插入它:

这是创建文件的部分:

BufferedWriter out = null;
        try  
        {
            FileWriter fstream = new FileWriter("out"+new Date().getHours()+""+new Date().getMinutes()+""+new Date().getSeconds()+".txt", true); 
            out = new BufferedWriter(fstream);

            out.write("======== Date: "+new Date() +" ========");
            out.write("\n==================================================");
            out.write("\n===============Construction of file ==============");
            out.write("\n==================================================");
           //out.write( ... 
          //.... other lines      
        } 
        finally {
            out.write("\n=================================================");
            }

        }
        catch (IOException e)
         {

        System.out.println("ERROR");
                }
         finally {
            if(out != null) {
                out.close();
            }
        }

//.....

我的类(class):

public class A   {

private Long AId;
private byte[] AFile;
//.. getters and setters 
}

最佳答案

您必须先将变量映射到数据库中的列
例如

@Column(name="column name in the database")
@Lob(type = LobType.BLOB)
private byte[] AFile;

然后就可以使用普通的条件查询来插入数据了。

读取文件并放入AFile 例如

IOUtils.toByteArray(InputStream input)

保存到数据库 例如

Session session = HibernateUtil.getSessionFactory().openSession();
session.beginTransaction();
//Add new Employee object
A a = new A();
a.setAFile("your byte array")

//Save the employee in database
session.save(a);

//Commit the transaction
session.getTransaction().commit();
HibernateUtil.shutdown();

关于java - 使用java在mysql数据库中创建和插入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29557930/

相关文章:

java - 数组中存在重复值,但未找到重复值

mysql - 为什么 MySQL 不使用我的 FULLTEXT 索引?

java - Hibernate session.contains(类 clazz,序列化 id)

hibernate - 在Grails 3中按WHERE子句过滤hasMany结果

java - 安卓错误 : recreate() must be called from main thread

java - 正则表达式仅阻止数字或空格,但允许数字和空格作为输入

php - 使用 jquery ajax 进行编辑和更新

PHP WHERE 子句中的许多变量 MySQL

java - 在 Hibernate 中使用 HQL 在一个表中插入数据

java - 检查一个数组的所有元素是否与另一个数组的所有元素具有相同的值