本文介绍了java hibernate插入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在网上看到一个教程,告诉你可以做这样的事情来删除和更新Hibernate:

 查询查询= session.createQuery(删除股票在哪里stockCode =:stockCode); 
query.setParameter(stockCode,7277);
int result = query.executeUpdate();

在同一个教程中,我遇到了用于插入的代码:

 查询查询= session.createQuery(insert into Stock(stock_code,stock_name)+ 
select stock_code,stock_name from backup_stock);
int result = query.executeUpdate();

我的问题是,是否可以执行类似于教程中的删除示例,但对于插入方法,而使用 setParameter ?我试过类似的东西,并得到一个错误:

  Query q = session.createQuery(insert into test(:testname) ); 
q.setParameter(testname,tester);

错误与属性有关。我之所以使用上面的代码是因为

  int result = query.executeUpdate()

可以返回结果来验证我是否通过SQL命令成功插入。


第一件事:

已为HQL查询中的参数创建,而不是字段名称。第二件事:

>

您的请求: insert into test(:testname)似乎不完整,应该像插入到[TABLE_NAME]([FIELD_NAME],...)值([VALUE],...),并且在这种情况下,您应该使用SQL查询:

请参阅:

为什么你需要使你的查询如此动态?



并且插入到数据库中会更省钱:

  session.save(youHibernateObject); 

与youHibernateObject一个映射有hibernate模型映射模式的对象。祝你好运。


I saw a tutorial in the web showing you can do something like this for deletes and updates in Hibernate:

Query query = session.createQuery("delete Stock where stockCode = :stockCode");
query.setParameter("stockCode", "7277");
int result = query.executeUpdate();

In the same tutorial I came across this code for insertion:

Query query = session.createQuery("insert into Stock(stock_code, stock_name)" +
            "select stock_code, stock_name from backup_stock");
int result = query.executeUpdate();

My question is, is it possible to do something like the delete example from the tutorial, but for the insertion method instead, by using setParameter? I tried something like this and got an error:

Query q = session.createQuery("insert into test(:testname)");
q.setParameter("testname", "tester");

The error was regarding properties. One of my reason to use the above code is because of the

 int result =  query.executeUpdate()

which can return a result to verify whether I successfully inserted via the SQL command or not.

解决方案

First thing :

has been create for parameters in HQL queries, not field name.

Second thing :

Your request : insert into test(:testname) seems incomplete, it should be something like insert into [TABLE_NAME]([FIELD_NAME],...) values ([VALUE],...) and In that case you should use SQL queries with :

See: http://docs.jboss.org/hibernate/orm/3.5/api/org/hibernate/Session.html#createSQLQuery(java.lang.String)

. Why do you need to make your query so dynamic ?

And an insert into the database would be better with a save :

session.save(youHibernateObject);

with youHibernateObject an object mapped with hibernate model mapping schemas. Good luck.

这篇关于java hibernate插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 02:05