我正在试用Spring Boot(最新版本,使用Hibernate 4.3.7),我的User
实体出现了问题。这里是(最重要的部分)。
@Entity
@Table("usr")
public class User {
public static enum Role {
UNVERIFIED, BLOCKED, ADMIN
}
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column
@ElementCollection
private Set<Role> roles = new HashSet<Role>();
(rest of properties, getters and setters etc)
}
我也在使用Spring Boot JPA repositories
来保存我的entities
@Repository
public interface UserRepository extends JpaRepository<User, Long> {
User findByEmail(String email);
}
他的问题是,当我把一些角色添加到角色集时,Hibernate不会保存它。它将创建参考表,但它只将数据插入到用户表中。
我试图解决这个问题,所以我创建了纯Java+Hibernate项目,并将我的User类复制到其中。你猜怎么着?它成功了!
有趣的是,当我在第二个项目中使用纯Hibernate时,创建的角色表看起来与Spring Boot项目中的不同。
在我的纯Hibernate项目中,我有这样的表。
User_roles:
User_Id bigInt(20)
roles int(11)
在使用Spring JPA时,我得到了
user_roles (notice lower case)
User (no "_id" part)
roles
发生了什么事?我做错了什么?是否与Spring Boot的配置有关?谢谢。
StackOverflow:hibernate - Spring Data JPA won't handle Set<Enum> correctly - Stack Overflow