我试图将简单的hibernate保存数据保存到我的表中,但我在控制台中有Transaction Exception,这是我的代码:
logging.java
@Entity
@Table(name = "Logging")
public class Logging implements Serializable {
private int id;
private String user;
private String action;
private Date date;
@Column(name = "ID")
@Id
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column(name = "USER_NAME")
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
@Column(name = "action")
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
@Column(name = "DATE")
@Temporal(TemporalType.DATE)
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
这就是我的插入方法:
public class BaseDAO {
public SessionFactory factory;
public Session session;
public BaseDAO() {
factory = new AnnotationConfiguration().configure(
"hibernate.cfg.xml").buildSessionFactory();
}
public void save(Object obj) throws Throwable {
session = factory.openSession();
Transaction tx = null;
tx = session.beginTransaction();
session.save(obj);
tx.commit();
}
我的loginServlet,我保存了我的数据:
Logging loggingdto = new Logging ();
try {
loggingdto.setId(1);
loggingdto.setUser(loggedInUserDTO.getUserName());
loggingdto.setAction("USER LOGGED IN");
loggingdto.setDate(new Date());
base.save(loggingdto);
} catch (Throwable e) {
e.printStackTrace();
}
我在DB中的表
create table Logging(
id int not null,
user_name varchar(50) not null,
action varchar(50) not null,
Date date
primary key (id)
);
控制台中出现的另一个问题是hibernate打印数据插入到表中但是顺序错误
Hibernate: insert into Logging (action, DATE, USER_NAME, ID) values (?, ?, ?, ?)
它应该是那样的
Hibernate: insert into Logging (id, user_name, action, date) values (?, ?, ?, ?)
当我检查表时我发现它是空的?
答案 0 :(得分:0)
查询中指定的列名称与创建表和Logging.java文件有所不同。 这就是你的控制台显示
的原因_Hibernate: insert into Logging (action, DATE, USER_NAME, ID) values (?, ?, ?, ?)_
而不是
_Hibernate:插入Logging(id,user_name,action,date)值(?,?,?,?)_