1

可能重复:
相同 JPA 类的多个数据库支持

我有一张桌子

用户(id,姓名);

现在我想为表创建 JPA 类,以便它可以支持两个数据库。

id 应该是自动递增的。

请通过提供一些示例帮助我实现同样的目标。

提前致谢。

4

3 回答 3

2

只需直接转到最便携的GenerationType.TABLE即可。它不太依赖于数据库细节,因为递增值是通过 SQL 完成的。我也发现它比 AUTO 更合适,因为相同的生成类型将独立于数据库提供程序使用。你也可以在没有TableGenerator的情况下使用它,但是因为我们的目标是让它在所有数据库中以完全相同的方式运行,所以我们明确给出了所需的值。

在您的情况下,映射是:

@Entity
@TableGenerator(
    name="usersGenerator",
    table="ID_GENERATOR",
    pkColumnName="GENERATOR_KEY",
    valueColumnName="GENERATOR_VALUE",
    pkColumnValue="USERS_ID",
    initialValue = 1,
    allocationSize=1)
public class Users {
    @Id
    @GeneratedValue(strategy= GenerationType.TABLE, 
                    generator = "usersGenerator")
    private Integer value;

    private String name;

    protected Integer getValue() {
        return value;
    }

    protected void setValue(Integer value) {
        this.value = value;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

多个表生成器可以使用同一个数据库表(在这种情况下为 ID_GENERATOR)。如果需要,例如由于 id 的类型,同一个表可以存储多个 pk 和 value 列。

TableGenerator 的名称对于持久性单元来说是全局的,就像一般的生成器名称一样。如果愿意,注释也可以定位到 id 属性。

可能的警告:如果我没记错的话,一些休眠版本组合不支持初始值。这在一般情况下不限制可移植性。只有当我们必须自动生成表并重现完全相同的一组 id 值时,这才是问题。解决方法是在建表后手动插入初始值。

于 2012-07-23T12:53:55.143 回答
1

发电机类型

增量

This generator supports in all the databases, database independent
This generator is used for generating the id value for the new record by using the 

顺序

Not has the support with MySql
This generator class is database dependent it means, we cannot use this generator class for all the database, we should know whether the database supports sequence or not before we are working with it

参考这个链接,它可能对你有帮助。

http://www.java4s.com/hibernate/generators-in-hibernate/

于 2012-07-23T12:21:03.227 回答
0

您应该选择生成类型 AUTO。我只使用了 .hbm 映射,但我的理解是使用注释它应该看起来像这样:

@Entity
public class Employee {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private long id;
于 2012-07-23T12:25:15.807 回答