hibernate没有将我的对象保存到数据库。为什么会这样?我是否没有正确执行事务?至于hibernate的日志记录,它说“org.hibernate.sql-insert into student(email,first\u name,last\u name)values(?,?)”。我认为这意味着它甚至不知道要放入什么值,即使我已经用参数构造函数创建了student对象。
这是我的密码
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(AnimalConfig.class, HibernateConfig.class); // Makes the sessionFactory bean known to the IOC
SessionFactory sessionFactory = (SessionFactory)ctx.getBean("sessionFactory");
Session session = sessionFactory.getCurrentSession();
Student aStudent = new Student("test","TEstinfdasddadas","bob@gmail.com"); //This is a transient instance which means that It's not related to the database, it's temporary
try {
session.beginTransaction();
session.save(aStudent);
session.getTransaction().commit();
}catch(Exception e){
System.out.println(e.getMessage());
}finally{
session.close();
}
(( ConfigurableApplicationContext )ctx).close(); //Close the applicationContext
SpringApplication.run(DemoApplication.class, args);
}
}
这是我的学生实体
@Entity(name = "student")
@Table(name = "student")
public class Student {
@Id
@GeneratedValue( strategy = GenerationType.IDENTITY)
@Column(name = "id")
private int id;
@Column(name = "first_name")
private String firstName;
@Column(name = "last_name")
private String lastName;
@Column(name = "email")
private String email;
public Student() {
}
public Student(String firstName, String lastName, String email) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
1条答案
按热度按时间xwbd5t1u1#
可能您没有配置hibernate在提交时进行刷新。尝试使用
session.flush()
在提交之前。