如何使用JPA 2.1转换连接元素集合?

时间:2015-02-05 12:47:30

标签: java entity-framework jpa

我有3个表useruser_teamteam ...

user
--------
id (number)
name (varchar)

team
--------
name (varchar)

user_team
--------
user_id (number) FK -> user.id
team_name (varchar) FK -> team.name

我希望加载User实体,以便将团队转换为正确的类型。

@Entity
public class User implements Serializable {

    @Id
    @GeneratedValue( strategy = IDENTITY )
    private Long id;

    @Column( name = "name" )
    private String name;

    @ElementCollection
    @JoinTable( name = "user_team", 
            joinColumns = @JoinColumn( name = "user_id" ) )
    @Column( name = "team_name" )
    @Convert( converter = TeamToStringConverter.class )
    private Set<Team> teams;
}

public enum Team { NOTEAM, GEEKS, FREAKS, etc ... }

@Converter
public class TeamToStringConverter implements AttributeConverter<Team, String> {

    @Override
    public String convertToDatabaseColumn( Team value ) {
        return value == null ? NOTEAM.name() : value.name();
    }
    @Override
    public TEAM convertToEntityAttribute( String value ) {
        return Team.from( value );
    }
}

我认为问题在于它使用TeamToStringConverter转换user_team.user_id字段而不是user_team.team_name字段(在@Column注释中指定),结果是异常:

sql.SqlUtils - Attempted to convert SQLException to SQLException. Leaving it alone. [SQLState: null; errorCode: 0]
com.microsoft.sqlserver.jdbc.SQLServerException: An error occurred while converting the nvarchar value to JDBC data type INTEGER.
at com.microsoft.sqlserver.jdbc.DDC.convertStreamToObject(DDC.java:475)
at com.microsoft.sqlserver.jdbc.ServerDTVImpl.getValue(dtv.java:2536)
...
Caused by: java.lang.NumberFormatException: For input string: "NOTEAM"
at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.lang.Integer.parseInt(Integer.java:580)
...

2 个答案:

答案 0 :(得分:2)

将映射更改为

@ElementCollection
@CollectionTable( name = "user_team", 
        joinColumns = @JoinColumn( name = "user_id" ) )
@Column( name = "team_name" )
@Enumerated(EnumType.STRING)
@Convert( converter = TeamToStringConverter.class )
private Set<Team> teams;
应该使用

@CollectionTable代替@JoinTable@Enumerated(EnumType.STRING)告诉JPA枚举值在数据库中存储为String,而不是Integer default(枚举常量的索引)。

请注意,在此设置中,表格team对JPA没有任何意义,因为它没有映射到任何内容。

答案 1 :(得分:0)

在Hibernate版本中,低于4.3.9注释@Convert不适用于集合字段。

请参见https://hibernate.atlassian.net/browse/HHH-9495

对于Hibernate较低版本4.3.9,请使用autoApply属性:

@Converter(autoApply = true)
public class TeamToStringConverter implements AttributeConverter<Team, String> {...}

对于Hibernate 4.3.9以上版本,请使用:

@ElementCollection
@CollectionTable( name = "user_team", joinColumns = @JoinColumn( name = "user_id" ) )
@Column( name = "team_name" )
@Convert( converter = TeamToStringConverter.class )
private Set<Team> teams;