简体   繁体   English

使用Spring Data JPA初始化存储库

[英]Initializing repository with Spring Data JPA

image attached after answer from Lorelorelore 图片来自Lorelorelore

basically, I tried to use hibernate in my project, but it became pretty chaotic, so I decided to test it again, so I created a new spring project. 基本上,我尝试在项目中使用休眠模式,但是它变得非常混乱,因此我决定再次对其进行测试,因此创建了一个新的Spring项目。 I have a POJO - Car class and a CarRepository. 我有一个POJO-汽车类和CarRepository。 As far as I understand, it should use basic methods from the CRUD repository - but, when I want to save a object (or use any other method) it just doesn't work (it shows that I should initialize variable "carRepository"). 据我了解,它应该使用CRUD存储库中的基本方法-但是,当我想保存一个对象(或使用任何其他方法)时,它根本不起作用(它表明我应该初始化变量“ carRepository”) 。 Could you please help me with that? 你能帮我吗? Thanks in advance 提前致谢

//CARTESTER CLASS

public class CarTester {
    public static void main(String[] args) {

        @Autowired
        CarRepository carRepository;
//I want to use a method from crudrepository here
        carRepository.save(new Car(1, "AAA", "BBB", 1111));
        carRepository.findAll();
    }
}

//CAR CLASS
@Table(name = "CARS")
@Entity
    public class Car {

        @Id
        private Integer id;
        private String brand;
        private String model;
        private int manufactureYear;
//constructors, getters, setters, toString()

//CARREPOSITORY CLASS
@Repository
public interface CarRepository extends CrudRepository<Car, Integer> {


}

Your test class should look like this: 您的测试类应如下所示:

@RunWith(SpringRunner.class)
@DataJPATest
public class CarTester {

 @Autowired
 CarRepository carRepository;

 @Test
 public void test() {
    carRepository.save(new Car(1, "AAA", "BBB", 1111));
    carRepository.findAll();
 }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM