有没有办法自己插入主键而不是在hibernate中自动生成 此类包含员工详细信息。

有没有办法自己插入主键而不是在hibernate中自动生成 此类包含员工详细信息。,hibernate,hibernate-mapping,Hibernate,Hibernate Mapping,正如您在上面的映射中所看到的,使用generator class=“native”自动生成文件ID 那么有没有一种方法可以根据java中的逻辑设置这个ID呢。 我不想让它自动生成,我想用我自己的逻辑生成它,然后插入到表中,还有可能当我运行代码在表中插入值时,表会自动在数据库中创建,如果它不存在,我听说有一种方法可以做到这一点 查看来自的官方文档:所有id生成器都有很好的解释。 您还可以检查如果没有为主键属性指定任何生成器,hibernate将假定您使用分配策略。assign策略告诉hiberna

正如您在上面的映射中所看到的,使用generator class=“native”自动生成文件ID

那么有没有一种方法可以根据java中的逻辑设置这个ID呢。 我不想让它自动生成,我想用我自己的逻辑生成它,然后插入到表中,还有可能当我运行代码在表中插入值时,表会自动在数据库中创建,如果它不存在,我听说有一种方法可以做到这一点

查看来自的官方文档:所有id生成器都有很好的解释。

您还可以检查

如果没有为主键属性指定任何生成器,hibernate将假定您使用
分配
策略。
assign
策略告诉hibernate您将自己设置id,因此hibernate不会帮助您定义id值。(如果您试图持久化一个id为null/已经存在的实体,hibernate只会抛出一个异常)

因此,请按如下方式定义映射:

<hibernate-mapping>
   <class name="Employee" table="EMPLOYEE">
      <meta attribute="class-description">
         This class contains the employee detail. 
      </meta>
      <id name="id" type="int" column="id">
         <generator class="native"/>
      </id>
      <property name="firstName" column="first_name" type="string"/>
      <property name="lastName" column="last_name" type="string"/>
      <property name="salary" column="salary" type="int"/>
   </class>
</hibernate-mapping>

此类包含员工详细信息。
那么您认为“已分配”是我的发电机吗?
<hibernate-mapping>
 <class name="Employee" table="EMPLOYEE">
  <meta attribute="class-description">
     This class contains the employee detail. 
  </meta>
  <id name="id" type="int" column="id"/>
  <property name="firstName" column="first_name" type="string"/>
  <property name="lastName" column="last_name" type="string"/>
  <property name="salary" column="salary" type="int"/>
 </class>
</hibernate-mapping>