0

私はhibernateを初めて使用し、マップされたオブジェクトを次のコードで更新しようとしましたが、更新されません

factory = config.buildSessionFactory();
session = factory.getCurrentSession();
Transaction t = session.beginTransaction();
String hql = "UPDATE  "+tableName+" SET  "+columnName+" =  '"+columnValue+"' WHERE  id ="+id+";";
Query query=session.createSQLQuery(hql);
t.commit();

私は何かが足りないのですか?クラッシュしたり、レコードを更新したりすることはありません。

注:私はHibernate3とMysqlを使用しています

4

2 に答える 2

9

You're missing query.executeUpdate();

Also, if you're updating a mapped object I would recommend you to make the changes to the java object, and let Hibernate do the update for you. Or at least use a hql query, not a native one.

Make sure that your persistence.xml file has show_sql set to true and watch the log to see if the update is executed.

<property name="hibernate.show_sql" value="true"/>
于 2012-05-25T17:48:09.320 に答える
3

query.executeUpdate()クエリを実行するには、 を使用する必要があります。
またparameters、インライン引数の代わりに使用することをお勧めします。たとえば。その場合、columnName = O'Reillyクエリ全体がうまくいきません。また、マップされたオブジェクトの場合は、SQL クエリではなく HQL を使用できます

代わりにこれを使用できます

//entity is your hibernate entity obj
String hql = "UPDATE  " + entity.getClass().getName + " as entity SET entity." + fieldName  + "= :columnValue WHERE  entity = :entity";
Query query=session.createQuery(hql).setParameter("columnValue", columnValue).setParameter("entity", entity);
query.executeUpdate();

一重引用符を使用する必要がないことに注意してください。setParameterそれを処理します。

于 2012-05-25T20:24:39.773 に答える