在Hibernate中插入新行

huangapple go评论82阅读模式
英文:

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>

下面是每个值的描述链接:
https://stackoverflow.com/questions/438146/what-are-the-possible-values-of-the-hibernate-hbm2ddl-auto-configuration-and-wha

英文:

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

&lt;properties&gt;
  &lt;property name=&quot;hibernate.hbm2ddl.auto&quot; value=&quot;update&quot;/&gt;
&lt;/properties&gt;

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

huangapple
  • 本文由 发表于 2020年10月15日 02:01:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/64359048.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定