user2053760
user2053760

Reputation: 1713

mybatis insert a object which contains another object

Let's say I have two tables: userHeader and userDetail,the corresponding domain classes are as follows:

    UserHeader:
    String user_id;
    String user_password;
    UserDetail userDetail;

    UserDetail:
    String user_id;
    String user_name;
    String phone;

for selection, I can use association tag in xml so I can get a userHeader object which contains a userDetail object.

for insert, I have a userHeader object, which contains a userDetail object, what can I do in order to insert record to both tables? shall I write two insert method to insert record seperately or there is something similar to association tag?

Upvotes: 2

Views: 1427

Answers (1)

corlaez
corlaez

Reputation: 1423

There is no association tag or mapping. You could take two approaches (in case you want to stick with MyBatis instead of going for an ORM lib):

1 Define a new method on the Mapper interface and on the xml. You can access each property like userHeader.userdetail.user_name on the xml to compose your inserts as you please

benefits: a single call to the SQL for any number of SQL insertions (variation: create and call a DB procedure)

cons: Must do manual changes on the Mapper XML if the DB adds columns (and procedure if you define one)

2 Use MyBatis generator, then on the Service layer define your custom insertion. Compose each insert and commit sqlsession.commit();

benefits: Easier to maintain DB and java model updated (which will give you CRUD and selects upon generation)

cons: separate SQL calls (from java code to DB - although i think performance impact is minimal specially in a non distributed system), generator will overwrite your custom changes (like UserDetail userDetail;) unless you are using mybatis generator Eclipse plugin or define custom relationships on a wrappedObject with a generator pluggin.

No association mappings source: Messages with Jeff Butler and wikipedia (Unlike ORM frameworks, MyBatis does not map Java objects to database tables but Java methods to SQL statements)

Approaches source: Personal experience.

Upvotes: 1

Related Questions