英文:
Insert new row in Hibernate
问题
以下是翻译好的内容:
当前代码将一行添加到数据库。如果我重用此代码,它将更新现有行,而不是创建新行。如何在使用相同代码时创建新行?
SessionFactory sessionFactory = HibernateFactory.getSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
Item item = new Item();
item.setName("name");
item.setPrice(122.3);
item.setCount(225);
session.persist(item);
session.getTransaction().commit();
session.close();
public abstract class AbstractEntity {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
}
Item 继承自 AbstractEntity。
英文:
The current code adds a row to the DB. If I reuse this code, it will update the existing row instead of creating a new one. How to create a new row using the same code?
SessionFactory sessionFactory = HibernateFactory.getSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
Item item = new Item();
item.setName("name");
item.setPrice(122.3);
item.setCount(225);
session.persist(item);
session.getTransaction().commit();
session.close();
public abstract class AbstractEntity {
@Id
@GeneratedValue(strategy= GenerationType.IDENTITY)
@Column(name="id")
private Long id;
}
Item extended AbstractEntity
答案1
得分: 0
Hibernate使用persistence.xml
或者hibernate.cfg.xml
来读取数据库属性。
要插入新行,hibernate.hbm2ddl.auto
必须设置为update
,而不是create-drop
或者create
。
<properties>
<property name="hibernate.hbm2ddl.auto" value="update"/>
</properties>
英文:
Hibernate uses persistence.xml
or hibernate.cfg.xml
to read the database properties.
To insert a new row the hibernate.hbm2ddl.auto
has to be set to update
instead of create-drop
or create
<properties>
<property name="hibernate.hbm2ddl.auto" value="update"/>
</properties>
Below you will find a link with the description for every value:
https://stackoverflow.com/questions/438146/what-are-the-possible-values-of-the-hibernate-hbm2ddl-auto-configuration-and-wha
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论