-
Notifications
You must be signed in to change notification settings - Fork 4
Tutorial 3: (Configuration) Adding Generators
Random-JPA provides mechanism to configure generation of random values. This can be done by adding custom generator. You need to provide generator to the JPAContextFactory in order to create JPAContext.
final JPAContextFactory jpaContextFactory = JPAContextFactory.newInstance(Database.ORACLE, entityManager);
final Generator generator = Generator.newInstance();
jpaContextFactory.with(generator);
There are two types of generator supported
- Class Generator
- Attribute Generator
Add random class generator which controls, how random object is generated for a given class type.
RandomClassGenerator has two methods
- getTypes() - List of all the classes for which this generator will be applied.
- doGenerate(Class<?> type) - provides method to generate random object, you are provided with a handle of the class for which generation is taking place.
Let us say that you want your restrict numerical values to range from 0-10000 system wide, i.e, all random values for type Integer/Long/int/long should be between 0-10000
generator.addClassGenerator(new RandomClassGenerator() {
@Override
public Collection<Class<?>> getTypes() {
final List<Class<?>> classes = Lists.newArrayList();
classes.add(Integer.class);
classes.add(Integer.TYPE);
classes.add(Long.class);
classes.add(Long.TYPE);
return classes;
}
@Override
public Object doGenerate(Class<?> aClass) {
if (aClass == Integer.class || aClass == Integer.TYPE) {
return RandomUtils.nextInt(10000);
}
return RandomUtils.nextLong(10000);
}
});
As the name states you can explicitly manage random generation of specific attribute.
RandomAttributeGenerator has two methods
- getAttributes() - List of all the attributes for which this generator is applicable.
- doGenerate() - how to generate random values.
Let us say you want to every Person's name & Account's name to start with "Test-"
generator.addAttributeGenerator(new RandomAttributeGenerator() {
@Override
public List<? extends Attribute> getAttributes() {
final List<Attribute<?, ?>> attributes = Lists.newArrayList();
attributes.add(Person_.FirstName);
attributes.add(Person_.lastName);
attributes.add(Account_.name);
return attributes;
}
@Override
public Object doGenerate() {
return "Test-" + RandomStringUtils.randomAlphanumeric(10);
}
});
Below is the following order in which generation takes place. If the condition is met, next step is not evaluated.
- Apply specific value (if provided in Plan).
- Set null values for attribute (if provided in plan).
- Apply RandomAttributeGenerator (if available).
- Apply RandomClassGenerator (if available).
- Apply default random generator.