Java Hibernate Session.save() 不返回值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4290220/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 15:26:38  来源:igfitidea点击:

Hibernate Session.save() doesn't return a value?

javahibernate

提问by Dustin Sun

Below code throws a casting error

下面的代码抛出一个转换错误

Long newID = (Long)session.save(object);

Long newID = (Long)session.save(object);

I am new to hibernate. Don't know why.

我是休眠的新手。不知道为什么。

采纳答案by Martin Algesten

The return value of session.save()depends on your mapping. Most likely you have a type of ID that isn't a Long. Try doing this:

的返回值session.save()取决于您的映射。很可能您的 ID 类型不是 Long。尝试这样做:

System.out.println(session.save(object).getClass().getName());

Then you'll see the type name.

然后你会看到类型名称。

回答by Sourabh Sharma

There are two methods:

有两种方法:

  1. public Serializable save(Object object) throws HibernateException
    Persist the given transient instance, first assigning a generated identifier. (Or using the current value of the identifier property if the assigned generator is used.) This operation cascades to associated instances if the association is mapped with cascade="save-update".
    Parameters:object - a transient instance of a persistent class
    Returns:the generated identifier

  2. public Serializable save(String entityName, Object object) throws HibernateException
    Persist the given transient instance, first assigning a generated identifier. (Or using the current value of the identifier property if the assigned generator is used.) This operation cascades to associated instances if the association is mapped with cascade="save-update".
    Parameters:object - a transient instance of a persistent class
    Returns:the generated identifier

  1. public Serializable save(Object object) throws HibernateException
    保留给定的瞬态实例,首先分配一个生成的标识符。(或者,如果使用分配的生成器,则使用标识符属性的当前值。)如果关联被映射到关联实例,则此操作级联到关联实例cascade="save-update"
    参数:object - 持久类的瞬态实例
    返回:生成的标识符

  2. public Serializable save(String entityName, Object object) throws HibernateException
    保留给定的瞬态实例,首先分配一个生成的标识符。(或者,如果使用分配的生成器,则使用标识符属性的当前值。)如果关联被映射到关联实例,则此操作级联到关联实例cascade="save-update"
    参数:object - 持久类的瞬态实例
    返回:生成的标识符