2017-08-14 174 views
0

我想向MySQL插入新記錄。 數據庫:enter image description here 實體類:`package entites; // Generated Aug 11,2017 1:32:55 PM by Hibernate Tools 4.3.1使用HQL查詢插入

import java.util.Date;

/** * 通過UserMonhoc調用:hbm2java */ 公共類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; 
    } 
} 

它不起作用。 謝謝。

+0

您應該顯示實體類並給出確切的錯誤消息。 – davidxxx

+0

好的。它已更新! –

+0

爲什麼哦爲什麼?只需使用'session.persist(umh)'。如果你想使用SQL查詢在你的數據庫中插入數據,你不應該使用Hibernate,而應該使用JDBC。 –

回答

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配置中聲明的...