java - 休眠行未保存到数据库
问题描述
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;
}
解决方案
也许您没有将 Hibernate 配置为在提交时进行刷新。尝试session.flush()
在提交前使用。
推荐阅读
- integration - 如何在 Visual Studio ssdt 中修复“在输入列集合中找不到指定的输入列”
- docker - 如何使用 jenkins x 在 kubernetes 上部署 docker 镜像
- python - 将 Pandas 数据绘制为条形图数组不符合 sharex = True
- python - 如何在不添加报价的情况下附加列表
- php - adobe echosine :create webhook from api 给出了 INVALID_API_ACCESS_POINT 的响应
- javascript - JS:如何从base64创建图像类型的文件
- java - 我正在获取 MySQL 服务器版本,以便在“.null”附近使用正确的语法
- android - 由于缺少 JAR 签名,Android Studio 不允许我上传 APK
- ember.js - 尝试将 Ember 2.14.2 更新到 Ember 2.18.2 时出错
- web-services - 如何在短时间内从 GAE 服务轮询 Web 服务?