首页 > 解决方案 > 休眠行未保存到数据库

问题描述

Hibernate 没有将我的对象保存到数据库中。为什么会这样?我没有正确执行交易吗?至于 hibernate 正在做什么的日志记录,它说“org.hibernate.SQL - 插入学生(电子邮件,名字,姓氏)值(?,?,?)”。我认为这意味着即使我使用参数构造函数创建了 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;
}

标签: javaspringhibernate

解决方案


也许您没有将 Hibernate 配置为在提交时进行刷新。尝试session.flush()在提交前使用。


推荐阅读