Hibernate session.save()总是返回1

时间:2014-12-17 11:19:02

标签: java spring hibernate

我在session.save()中得到了一个奇怪的结果。它始终返回1.但正确插入数据库中的值。请提出您认为可疑的任何内容

代码

session = getSessionFactory().openSession();
Transaction transaction = session.beginTransaction();
userId = (Long)session.save(user);
transaction.commit();

用户 - 持久性

@Id
@GeneratedValue(strategy=GenerationType.SEQUENCE)
@GenericGenerator(name = "increment", strategy = "increment")
@Column(name = "ID")
public Long getId() {
    return id;
}

public void setId(Long id) {
    this.id = id;
}

@Column(name = "USERNAME", length = 100)
public String getUsername() {
    return username;
}

public void setUsername(String username) {
    this.username = username;
}

@Column(name = "PASSWORD", length = 100)
public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

@OneToOne(fetch = FetchType.EAGER)
@MapsId
@JoinColumn(name = "ROLEID")
public Role getRole() {
    return role;
}

public void setRole(Role role) {
    this.role = role;
}

@Column(name = "IMAGEURL", length = 2000)
public String getImageUrl() {
    return imageUrl;
}

public void setImageUrl(String imageUrl) {
    this.imageUrl = imageUrl;
}

Hibernate:4.3.7 final

春天:4.1.2

2 个答案:

答案 0 :(得分:2)

参考此问题Difference between @GeneratedValue and @GenericGenerator

问题可能在于您的@GeneratedValue

所以你可以改变

@GeneratedValue(strategy=GenerationType.SEQUENCE)

@GeneratedValue(generator="increment")

注意:您可以参考 this 将数据库序列分配给@GeneratedValue

答案 1 :(得分:1)

从代码中我看到你的生成策略是Sequence。但你错过了将序列映射到注释。

https://docs.oracle.com/javaee/5/api/javax/persistence/GeneratedValue.html

@Id
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="YOUR_SEQ")
@Column(name = "ID")
public Long getId() {
    return id;
}

否则,如果您使用的是自定义生成器,那么您应该映射如下:

@Id
@GeneratedValue(generator= "increment")
@GenericGenerator(name = "increment", strategy = "increment")
@Column(name = "ID")
public Long getId() {
    return id;
}