开发者

How to override AccessType on a single field

I have a class which contains a number of fields, and all are annotated by property. For one of those fields, though, I want to present a double to the database and a Date to the user.

I've tried any number of combinations here but hbm2ddl (and thus, hibernate) keep treating the dwell property as a timestamp. How should I be implementing this if not via annotations similar to what I have below (this is a simplified version of the class in question)?

I'd consider moving all the annotations to fields, but the class that needs this sits at the top of an inheritance hierarchy involving another 25 classes and many, many annotations. It would take the better part of a day to move all the annotations and that seems like an inelegant way to deal with this.

@Entity
@AccessType("property")
public class Test {

    private long id;
    private Double dwell;

    @Id
    @Column(name = "ID", nullable = false)
    @GeneratedValue(strategy = GenerationType.AUTO)
    @NotNull
    public long getId() {
        return id;
    }

    public void setId(long id) {
        this开发者_Go百科.id = id;
    }

    @AccessType("field")
    @Column(name = "DWELL_ID", precision = 10, scale = 3)
    public Date getDwell() {
        return new Date();
    }

    public void setDwell(Double dwell) {
        this.dwell = dwell;
    }

}


This looks a bit strange. I'm not sure that changing the access type will actually work for you.

You are breaking the javabeans convention, which is risky. Don't do it - let getters and setters be purely getters and setters, without hidden extras like constructing objects.

I would just write another method - getDwellAsDate() and do the conversion there. You can also define a custom hibernate Type to handle that (but it's not worth it)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜