views:

30

answers:

2

Is there a way to convert table entries from an old table to a new one using the same entity class?

To be specfic, here are my entity class' annotations for the new table:

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Basic(optional = false)
@Column(name = "benutzer_id")
private Integer benutzerId;
@Basic(optional = false)
@Column(name = "benutzer_name")
private String benutzerName;
@Column(name = "benutzer_vorname")
private String benutzerVorname;
@Column(name = "benutzer_nachname")
private String benutzerNachname;
@JoinColumn(name = "gruppe_id", referencedColumnName = "gruppe_id")
@ManyToOne(optional = false)
private Gruppe gruppe;
@OneToMany(mappedBy = "benutzer")
private Collection<Bestellung> bestellungen;

The columns "benutzer_vorname" and "benutzer_nachname" are missing in the old table, so Hibernate crashes, if it tries to map the table entries.

Do I have to create a new entity class or is it possible to convert the data using the existing one?

+1  A: 

Do I have to create a new entity class or is it possible to convert the data using the existing one?

You can't map an entity on two tables (I'm not talking about the JOIN inheritance strategy here) so you'll have to create a new entity.

Pascal Thivent
+1  A: 

If you're considering how to migrate from one table structure to another, then Hibernate may not be the best solution.

If the table is flat (no associations) then it might be really simple to copy the entries across using SQL. You can just select the required data and insert it directly into the new table (syntax probably varies by DBMS though, which could be a problem for you).

In standard SQL you can do this as follows

INSERT INTO new_table (
    column1, 
    column2, 
    column3
)
SELECT
    column1 as "Copied value for new entity",
    'a default' as "Default value for new entity",
    some_column * 3 as "Computed Value for new entity"
FROM 
    new_table;

Select column aliases are optional of course, I've just used them as comments for the various things you can do.

Of course if you have a more complicated table structure that you'd like to flatten you can perform a query of any complexity as long as it returns a set of rows you'd like to insert.

Geoff
The problem is I have to "migrate" many times for testing purposes.
You can have hibernate run SQL through the datasource that you have configured it with. Just use `session.createSQLQuery( "SELECT... " ).list();` instead.
Geoff