1

I have the follow legacy database structure and content:

order parameter        value
--------------------------------
1     user_login       user
1     user_password    123456
1     user_level       basic
2     user_login       admin
2     user_password    s3k42k
2     user_level       advanced

I would like to represent this as below and utilize a entity called 'User' so that i can abstract the complexity of the legacy structure:

id    user  password  level
-------------------------------
1     user  123456    basic
2     admin s3k42k    advanced

I got it do this using a view in database, but i couldnt update using this view. Is there a way to represent the legacy structure using Hibernate so than i can update too?

deldev
  • 1,296
  • 18
  • 27
  • 1
    I don't think Hibernate can do this. It would probably be easier in the long run to do the opposite; normalize the table and create a view that replicates the key-value representation for legacy code. – Zutty May 14 '13 at 16:45

1 Answers1

1

Your best approach probably is to normalize the table. It will make things much easier in the long run. One thing you could try it this is not an option, is to create another table called user that holds at least a primary key and the id of the users information in your parameter table. This would allow you to treat the relationship as a one-to-many and map it with hibernate. For example you could do something like the following:

Note I might have the mapping wrong I just did this off of the top of my head to illustrate the point.

@Entity
class Parameter{

    @Column(name="order")
    private int order;

    @column(name="parameter")
    private String parameter;

    @column(name="value")
    private String value;

} 

@Entity
class User{

    @column(name="id")
    private int id;

    @OneToMany(cascade=ALL)
    @JoinTable(name="SECONDARY", 
        joinColumns={@JoinColumn(name="id")},
        inverseJoinColumns=@JoinColumn(name="order"))
    @MapKeyJoinColumn(name="parameter")
    private Map<String,Parameter> userData;

    public String getUserName(){
        return userdata.get("user_login")
    }

    etc.

}
John Kane
  • 4,383
  • 1
  • 24
  • 42
  • This is useful, but i could update the legacy table trough the entity User? – deldev May 14 '13 at 19:38
  • 1
    Setting the cascade type to all should do that on persist, merge, and delete. Just save everything through the user object (and test it to make sure). It would be much more efficient over time though to normalize the table if thats an option. – John Kane May 14 '13 at 19:53