How to instantiate artemis-odb entities with components

Some time ago I played around with the Artemis framework. Artemis is an ECS, short for Entity-Component System. It’s a system in which you favor composition over inheritance. The components are data containers tied to a very light-weight entity and the game logic goes into the systems. That’s a very brief overview of what ECS is and does. Artemis is a well known one for Java and it was easy to use. Now coming back to it after a few years, things have changed. There’s a few spin-offs, among which artemis-odb.

Artemis-odb seemed the most interesting and I dove right in. And I instantiated entities and set up systems without issue. But what I couldn’t find was how to attach components to an entity without being in a system. The documentation is rather unclear about this and kept telling me to put component creation in a system, while I didn’t want to do that. Turns out it’s very easy to do, just not documented very well:

public class Health extends Component {
public int current;
public int maximum;

You just use world.getComponentMapper(Class) to retrieve the mapper:

final int playerId = world.create();
final ComponentMapper<Health> healthComponentMapper = world.getMapper(Health.class);
final Health health = healthComponentMapper.create(playerId);
health.maximum = HEALTH;
health.current = HEALTH;

It’s that easy!