Menu

orm_save

Luis M. Villa

Saving objects

(Return to examples index)

Saving objects is a trivial thing. Just create the objects and, checking if their id attribute is null or not, MILK will save or update the objects.

In any case, the save() method will return an object with its id attribute set with the id created by the database.

... but, how is the id obtained? To customize this, MILK uses IdGenerationStrategy (and provides you with some useful already implemented). In our case, we'll use MySqlIdGenerationStrategy. This strategy saves a row and, in the same transaction, calls "select LAST_INSERT_ID()" to retrieve the last inserted id. This is just one strategy: you can implement your own at any time. Now, let's set the stategy for our database:

import javax.sql.DataSource;
import net.sourceforge.milk.DbWithOrm;
import net.sourceforge.milk.Filter;
import net.sourceforge.milk.orm.configuration.OrmConfigurationBuilder;
import net.sourceforge.milk.orm.primarykeys.MySqlIdGenerationStrategy;
import net.sourceforge.milk.sql.Select;
import net.sourceforge.milk.tests.common.Issue;

@Override
protected void configureOrm(final OrmConfiguration ormConfig) {

    ormConfig
        .idAttributeIs("id")
        .idGenerationStrategyIs(new MySqlIdGenerationStrategy())
        .entity(Issue.class)
            .idAttributeIs("issueId")
            .mapsToTable("issues")
            .mapsAttribute("issueId").with("id")
        .entity(User.class)
            .mapsAttribute("id").with("userId");
}

Now, we are ready to save our entities:

// Inserts a new user
final User user = new IssuesDb().orm().save(new User("Luis", "Villa"));

// We change a value and, as the object has not null id, it will be updated.
Orm orm = new IssuesDbExamples().orm();
final Integer idInsertedUser = user.getId();
user.setName("Luis2");
orm.save(user);
user = orm.loadById(User.class, idInsertedUser);
Assert.assertEquals("Luis2", user.getName());

And that's it. Nothing more is needed. Now, let's check a nice feature: Logical deletion support


Related

Wiki: Examples
Wiki: examples_toc
Wiki: orm_collection
Wiki: orm_logical_delete

Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.