如何使用外键插入新记录?

时间:2017-08-14 14:03:30

标签: java hibernate

数据库:

enter image description here

User_Monhoc表中,user_id是外键。 我需要在User_Monhoc中插入1条新记录(user_id是用户中的存在记录。)

User_Monhoc Map:

<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

2 个答案:

答案 0 :(得分:1)

您需要先开始交易。 JavaDoc for Session详述了通常的流程。我为你稍微改了一下:

Session sess = sf.openSession();
Transaction tx;
try {
     tx = sess.beginTransaction();

     // Your query etc.         
     Query query = sess.createSQLQuery(hql2);
     //...

     tx.commit();
}
catch (Exception e) {
     if (tx != null) tx.rollback();
     throw e;
}
finally {
     sess.close();
}

答案 1 :(得分:0)

您的代码与实体无关。您正在尝试调用SQL并且没有活动事务。你应该在插入后启动一个并提交。

Transaction tx = sf.getCurrentSession().beginTransaction();
...

tx.commit();