2

I have the following entity class that before creating an object should call the getUniqueSlug method to check if there are already items with the same name.

@Entity public class Category {
@Column private Long id;

@Column(nullable = false) private String name;

@Column(nullable = false) private String slug;

@Autowired private CategoryRepository categoryRepository;

public String getUniqueSlug(String name) {
    int i = 1;

    while (this.categoryRepository.findBySlug(Slug.toSlug(name)) != null) {
        name = name + " " + i;
        i++;
    }

    return Slug.toSlug(name);
}

// Constructors

public Category() {
}

public Category(String name) {
    this.name = name;
    this.slug = getUniqueSlug(name);
}

// Getters and setters

I also have the following test to check if it does it properly:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = Application.class)
@WebAppConfiguration public class CategoryTest {

private MockMvc mockMvc;

@Autowired private CategoryRepository categoryRepository;

@Autowired ObjectMapper objectMapper;

@Autowired private WebApplicationContext webApplicationContext;

@Before public void setUp() throws Exception {
    this.mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();

    this.categoryRepository.deleteAll();
    this.categoryRepository.save(new Category("My category name"));
}

@Test public void testUniqueSlug() throws Exception {
    String slug = "My category name";
    int integer = 1;
    while (categoryRepository.findBySlug(Slug.toSlug(slug)) != null) {
        slug = slug + " " + integer;
        integer++;
    }
    this.categoryRepository.save(new Category(slug));
    System.out.println(this.categoryRepository.findAll());
}

When I run that test, I get the NullPointerException, so I assume that the problem is somewhere in autowiring the repository in the Category class. Where exactly?

Maciej Szlosarczyk
  • 789
  • 2
  • 7
  • 21
  • 1
    The duplicate explains what the core problem is, but it's bad form to mix the data object with service dependencies, especially hidden ones. If you *must* implement your slug logic in that manner, pass the `CategoryRepository` to the generator method as a parameter. – chrylis -cautiouslyoptimistic- Apr 02 '16 at 11:02

2 Answers2

1

You should separate all methods from entity class according to MVC concept. All methods locate into Service class with autowired repository. Also check that application context contains you repository bean.

svichkar
  • 1,806
  • 1
  • 17
  • 23
0

you dont use spring beans in entity class,because spring not manage entity clases so not autowired private CategoryRepository categoryRepository; this line all time throw null pointer exception

kakashi hatake
  • 1,175
  • 2
  • 10
  • 18