【问题标题】:Hibernate Row is not being saved to database休眠行未保存到数据库
【发布时间】:2021-02-02 20:19:47
【问题描述】:

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;
}

【问题讨论】:

  • 你能在变量中写 session.beginTransaction() 并为该变量调用 .commit() 吗?当你调用 session.getTransaction() 时,你可能会得到新的 Transaction 对象?
  • 抱歉,我不确定您要我做什么。 “将 session.beginTransaction() 写入变量”,变量中是什么意思?
  • 例如:Transaction tr = session.beginTransaction();之后不要调用 session.getTransaction().commit();尝试调用 tr.commit();
  • 您应该显示学生实体的代码。还要提高休眠日志级别,看看休眠实际在做什么。
  • 好的,我已经更新了帖子并包含了学生实体。至于日志记录级别,我认为 Hibernate 甚至不知道我要求它插入的学生对象的值。它说 org.hibernate.SQL - insert into student (email, first_name, last_name) values (?, ?, ?) 我知道它知道我正在使用哪个数据库,因为它在 MySQL 中自动为我创建学生表想要它。我不想成为那个人,但我对 Hibernate 也很陌生,不知道日志记录的大部分含义

标签: java spring hibernate


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-12
    • 2013-05-22
    相关资源
    最近更新 更多