插入HQL查询

时间:2017-08-14 10:35:32

标签: java hibernate

我想向MySQL插入一条新记录。 数据库:enter image description here 实体类:`package entites; //由Hibernate Tools 4.3.1生成于2017年8月11日下午1:32:55

import java.util.Date;

/ **  *由hbm2java生成的UserMonhoc  * / 公共类UserMonhoc实现了java.io.Serializable {

 private UserMonhocId id;
 private Monhoc monhoc;
 private User user;
 private Date thoigianDk;

public UserMonhoc() {
}

public UserMonhoc(UserMonhocId id, Monhoc monhoc, User user, Date thoigianDk) {
   this.id = id;
   this.monhoc = monhoc;
   this.user = user;
   this.thoigianDk = thoigianDk;
}

public UserMonhocId getId() {
    return this.id;
}

public void setId(UserMonhocId id) {
    this.id = id;
}
public Monhoc getMonhoc() {
    return this.monhoc;
}

public void setMonhoc(Monhoc monhoc) {
    this.monhoc = monhoc;
}
public User getUser() {
    return this.user;
}

public void setUser(User user) {
    this.user = user;
}
public Date getThoigianDk() {
    return this.thoigianDk;
}

public void setThoigianDk(Date thoigianDk) {
    this.thoigianDk = thoigianDk;
}

}

`

代码:

public boolean InsertStudent(String idUS, String idMH) {

    try {
        sf.getCurrentSession().beginTransaction();
        UserMonhoc umh = new UserMonhoc();
        String hql2 = "INSERT INTO User_Monhoc(user_id,mh_id) VALUES('" + idUS + "','" + idMH + "')";
        System.out.println(hql2);
        Query query = sf.getCurrentSession().createSQLQuery(hql2);
        query.executeUpdate();
        return true;
    } catch (Exception e) {
        return false;
    }
}
它不起作用。 谢谢。

1 个答案:

答案 0 :(得分:1)

  

使用HQL查询插入

您不使用HQL查询。

此调用:

Session.createSQLQuery(...)

创建本机SQL查询。

无论如何,你不能在HQL中以这种方式使用INSERT。

根据Hibernate documentation

  

仅支持INSERT INTO ... SELECT ...表单。你不能   指定要插入的显式值。

但是,使用HQL查询无法解决您的问题,因为您要指定要插入的值。

要保持实体,在Hibernate中最自然的做法是调用Session.persist()方法:

UserMonhoc umh = new UserMonhoc();
... // set fields of the object
sf.getCurrentSession().persist(umh);

但要做到这一点,UserMonhoc当然必须被宣布为实体 我指定它,因为我没有在您的实际实体中看到任何Hibernate注释。这些可以在xml配置中声明...