Reputation: 39
I want to insert a new record to MySQL. database: enter image description here Entity class:`package entites; // Generated Aug 11, 2017 1:32:55 PM by Hibernate Tools 4.3.1
import java.util.Date;
/** * UserMonhoc generated by hbm2java */ public class UserMonhoc implements 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;
}
}
`
Code:
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;
}
}
it don't work. Thank you.
Upvotes: 0
Views: 1586
Reputation: 131346
Insert with HQL query
You don't use a HQL query.
This invocation :
Session.createSQLQuery(...)
creates a native SQL Query.
Anyway, you could not use INSERT in this way in HQL.
According to Hibernate documentation :
Only the INSERT INTO ... SELECT ... form is supported. You cannot specify explicit values to insert.
But using a HQL query will not solve your problem as you want to specify values to insert.
To persist an entity, the most natural way of doing in Hibernate is invoking theSession.persist()
method :
UserMonhoc umh = new UserMonhoc();
... // set fields of the object
sf.getCurrentSession().persist(umh);
But to do it, UserMonhoc
of course has to be declared as an entity.
I specify it as I don't see any Hibernate annotation in your actual entity. These are maybe declared in the xml configuration...
Upvotes: 1