Reputation: 1826
I want to populate the repository with user roles and two initial users related to those roles.
This is the JSON I want to upload:
[
{
"_class": "models.Role",
"@id": 1,
"name": "ROLE_BLOG_ADMIN",
"description": "Rol de los administradores del blog"
},
{
"_class": "models.Role",
"@id": 2,
"name": "ROLE_BLOG_CONTRIBUTOR",
"description": "Rol de los editores de artículos"
},
{
"_class": "models.User",
"username": "test1",
"password": "$2a$10$0eCQpFRdw8i6jJzjj/IuNuKpJYnLaO5Yp9xSJ3itcfPmQNXVhmNyu",
"email": "[email protected]",
"fullName": "User adming",
"roles": [1, 2]
},
{
"_class": "models.User",
"username": "test2",
"password": "$2a$10$0eCQpFRdw8i6jJzjj/IuNuKpJYnLaO5Yp9xSJ3itcfPmQNXVhmNyu",
"email": "[email protected]",
"fullName": "User",
"roles": [2]
}
]
I am using JsonIdentityInfo
in the Roles entity:
@Entity
@Table(name = "roles")
@JsonIdentityInfo(generator=IntSequenceGenerator.class, property="@id")
public class Role implements Serializable
I have included Jackson2RepositoryPopulatorFactoryBean
in the context:
@Bean(name="repositoryPopulator")
public Jackson2RepositoryPopulatorFactoryBean provideJackson2RepositoryPopulatorFactoryBean(){
Resource sourceData = new ClassPathResource("data.json");
Jackson2RepositoryPopulatorFactoryBean factory = new Jackson2RepositoryPopulatorFactoryBean();
factory.setResources(new Resource[] { sourceData });
return factory;
}
But, no role is associated with any user.
This is the association:
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(
name="USER_ROLES",
joinColumns=@JoinColumn(name="USER_ID", referencedColumnName="ID"),
inverseJoinColumns=@JoinColumn(name="ROLE_ID", referencedColumnName="ID"))
private Set<Role> roles;
Does anyone know how to fix them?
Upvotes: 1
Views: 967
Reputation: 863
It should only complain about a missing constructor for the Role entity, for me everything went smoothly with the following :
@Entity
@Table(name = "roles")
public class Role implements Serializable {
public Role() {
}
public Role(Integer id) {
this.id = id;
}
@Id
@JsonProperty("@id")
private Integer id;
//additional properties, getters & setters
...
}
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(
name="USER_ROLES",
joinColumns=@JoinColumn(name="USER_ID", referencedColumnName="ID"),
inverseJoinColumns=@JoinColumn(name="ROLE_ID", referencedColumnName="ID"))
private Set<Role> roles;
//additional properties, getters & setters
...
}
And I properly get :
[
{
"id":1,
"roles":[
{
"name":"ROLE_BLOG_ADMIN",
"@id":1
},
{
"name":"ROLE_BLOG_CONTRIBUTOR",
"@id":2
}
],
"email":"[email protected]"
},
{
"id":2,
"roles":[
{
"name":"ROLE_BLOG_CONTRIBUTOR",
"@id":2
}
],
"email":"[email protected]"
}
]
Can you provide more of your entities code if this isn't working for you ? Do you encounter any exception ?
Upvotes: 2