<分区>
数据库:
在User_Monhoc
表中,user_id
是一个外键。
我需要将 1 条新记录插入 User_Monhoc
(user_id
是用户中存在的记录)。
User_Monhoc 映射:
<hibernate-mapping>
<class name="entites.UserMonhoc" table="user_monhoc" catalog="bthibernate" optimistic-lock="version">
<composite-id name="id" class="entites.UserMonhocId">
<key-property name="userId" type="string">
<column name="user_id" length="100" />
</key-property>
<key-property name="mhId" type="string">
<column name="mh_id" length="100" />
</key-property>
</composite-id>
<many-to-one name="monhoc" class="entites.Monhoc" update="false" insert="false" fetch="select">
<column name="mh_id" length="100" not-null="true" />
</many-to-one>
<many-to-one name="user" class="entites.User" update="false" insert="false" fetch="select">
<column name="user_id" length="100" not-null="true" />
</many-to-one>
</class>
</hibernate-mapping>
我的代码:
private final SessionFactory sf = HibernateUtil.getSessionFactory();
public boolean InsertStudent(String idUS, String idMH) {
try {
String xxxx = "";
String hql2 = "INSERT INTO User_Monhoc(user_id,mh_id,tuan1, tuan2, tuan3, tuan4, tuan5, tuan6, tuan7, tuan8, tuan9, tuan10, tuan11, tuan12, tuan13, tuan14, tuan15) VALUES('" + idUS + "','" + idMH + "', 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0 )";
System.out.println(hql2);
Query query = sf.getCurrentSession().createSQLQuery(hql2);
int cc = query.executeUpdate();
System.out.println(cc + "Dong");
sf.getCurrentSession().getTransaction().commit();
return true;
} catch (Exception e) {
return false;
}
}
错误信息:
org.hibernate.HibernateException: createSQLQuery is not valid without active transaction