Spring Boot “Failed to execute CommandLineRunner Error”

huangapple go评论76阅读模式
英文:

Spring Boot "Failed to execute CommandLineRunner Error"

问题

我尝试为我的Spring Boot项目添加了OneToMany注解但是当我运行项目时出现了Failed to execute CommandLineRunner错误
我希望用户表中的用户可以拥有多个城市因此我尝试添加了OneToMany注解

用户类User Class

package io.javabrains.springsecurity.jpa.models;

import com.spring.weather.*;
import java.util.*;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.OneToMany;
import javax.persistence.Table;

@Entity
@Table(name="app_user")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;
    private String userName;
    private String password;
    private boolean active;
    private String role;
    private String city;
    
    @OneToMany(targetEntity = UserCity.class, cascade = CascadeType.ALL)
    @JoinTable(name="USER_CITY", joinColumns=@JoinColumn(name="m_user_id"),
               inverseJoinColumns=@JoinColumn(name="cityId"))
    private List<UserCity> usercity;
    
    public User() {
        super();
    }
    
    // Getters and setters...
}

用户城市类User City Class

package io.javabrains.springsecurity.jpa.models;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Table;

@Entity
@Table(name="user_city")
public class UserCity {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int cityId;
    private String cityName;

    public UserCity() {
        super();
    }
    
    // Constructors...
    
    @ManyToOne
    private User mUser;
    
    // Getters and setters...
}

用户Repository

package io.javabrains.springsecurity.jpa;

import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import io.javabrains.springsecurity.jpa.models.User;

public interface UserRepository extends JpaRepository<User, Integer> {
    Optional<User> findByUserName(String userName);
}

用户城市Repository

package io.javabrains.springsecurity.jpa;

import org.springframework.data.jpa.repository.JpaRepository;
import io.javabrains.springsecurity.jpa.models.User;
import io.javabrains.springsecurity.jpa.models.UserCity;

public interface CityRepository extends JpaRepository<UserCity, Integer> {
}

Spring应用类Spring Application Class

package io.javabrains.springsecurity.jpa;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import com.spring.weather.WeatherService;
import io.javabrains.springsecurity.jpa.models.User;
import io.javabrains.springsecurity.jpa.models.UserCity;

@SpringBootApplication
@EnableJpaRepositories(basePackageClasses = UserRepository.class)
public class SpringsecurityApplication implements CommandLineRunner {
    @Bean
    public WeatherService ws() {
        return new WeatherService();
    }
    
    @Autowired
    UserRepository userRepository;
    
    @Autowired
    CityRepository cityRepository;
    
    public static void main(String[] args) {
        SpringApplication.run(SpringsecurityApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        // TODO Auto-generated method stub
        System.out.println("Application Running.");
        User adminUser = new User();
        UserCity ucity = new UserCity();
        UserCity ucity2 = new UserCity();
        ucity.setCityName("amsterdam");
        
        // 设置管理员用户信息...
        
        userRepository.save(adminUser);
        cityRepository.save(ucity);

        User newUser = new User();
        newUser.setUserName("User");
        newUser.setPassword(new BCryptPasswordEncoder().encode("pass"));
        newUser.setRole("ROLE_USER");
        newUser.setActive(true);
        newUser.setCity("maribor");
        ucity2.setmUser(newUser);
        userRepository.save(newUser);
        cityRepository.save(ucity2);
    }
}

错误截图链接:点击此处查看错误截图

英文:

I tried to add One To Many Annotation to my spring boot project, but when I run my project I get "Failed to execute CommandLineRunner " error.
I wanted users in the user's table to have more than one city. So, I tried to add OneToMany Annotation.

You can see the error at the attachment.

User Class

package io.javabrains.springsecurity.jpa.models;
import com.spring.weather.*;
import java.util.*;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Table(name=&quot;app_user&quot;)
public class User {
@Id
@GeneratedValue(strategy =GenerationType.AUTO)
private int id;
private String userName;
private String password;
private boolean active;
private String role;
private String city;
@OneToMany(targetEntity = UserCity.class,cascade = CascadeType.ALL)
@JoinTable(name=&quot;USER_CITY&quot;,joinColumns=@JoinColumn(name=&quot;m_user_id&quot;),
inverseJoinColumns=@JoinColumn(name=&quot;cityId&quot;))
private List&lt;UserCity&gt; usercity;
public User() {
super();
// TODO Auto-generated constructor stub
}
public List&lt;UserCity&gt; getUsercity() {
return usercity;
}
public void setUsercity(List&lt;UserCity&gt; usercity) {
this.usercity = usercity;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}

User City Class

    package io.javabrains.springsecurity.jpa.models;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name=&quot;user_city&quot;)
public class UserCity {
@Id
@GeneratedValue(strategy =GenerationType.AUTO)	
private int cityId;
private String cityName;
public UserCity() {
super();
// TODO Auto-generated constructor stub
}
public UserCity(int cityId, String cityName, User mUser) {
super();
this.cityId = cityId;
this.cityName = cityName;
this.mUser = mUser;
}
@ManyToOne
private User mUser;
public int getCityId() {
return cityId;
}
public void setCityId(int cityId) {
this.cityId = cityId;
}
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public User getmUser() {
return mUser;
}
public void setmUser(User mUser) {
this.mUser = mUser;
}
}

User Repository

package io.javabrains.springsecurity.jpa;
import java.util.Optional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import io.javabrains.springsecurity.jpa.models.User;
public interface UserRepository extends JpaRepository&lt;User, Integer&gt; {
Optional&lt;User&gt; findByUserName(String userName);
}

User City Repository

package io.javabrains.springsecurity.jpa;
import org.springframework.data.jpa.repository.JpaRepository;
import io.javabrains.springsecurity.jpa.models.User;
import io.javabrains.springsecurity.jpa.models.UserCity;
public interface CityRepository extends JpaRepository&lt;UserCity,id&gt;{
}

Spring Application Class

package io.javabrains.springsecurity.jpa;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import com.spring.weather.WeatherService;
import io.javabrains.springsecurity.jpa.models.User;
import io.javabrains.springsecurity.jpa.models.UserCity;
@SpringBootApplication
@EnableJpaRepositories(basePackageClasses = UserRepository.class)
public class SpringsecurityApplication implements CommandLineRunner{
@Bean
public WeatherService ws() {
return new WeatherService ();
}
@Autowired
UserRepository userRepository;
CityRepository cityRepository;
public static void main(String[] args) {
SpringApplication.run(SpringsecurityApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
// TODO Auto-generated method stub
System.out.println(&quot;Application Running.&quot;);
User adminUser= new User();
UserCity ucity=new UserCity();
UserCity ucity2=new UserCity();
ucity.setCityName(&quot;amsterdam&quot;);
adminUser.setUserName(&quot;Admin&quot;);
adminUser.setPassword(new BCryptPasswordEncoder().encode(&quot;pass&quot;));
adminUser.setRole(&quot;ROLE_ADMIN&quot;);
adminUser.setActive(true);
adminUser.setCity(&quot;bologna&quot;);
ucity.setmUser(adminUser);
userRepository.save(adminUser);
cityRepository.save(ucity);
User newUser= new User();
newUser.setUserName(&quot;User&quot;);
newUser.setPassword(new BCryptPasswordEncoder().encode(&quot;pass&quot;));
newUser.setRole(&quot;ROLE_USER&quot;);
newUser.setActive(true);
newUser.setCity(&quot;maribor&quot;);
ucity2.setmUser(newUser);
userRepository.save(newUser);
cityRepository.save(ucity2);
}
}

答案1

得分: 0

遇到的问题,更具体地说,在您的主应用程序的第54行出现了NullPointerException,是由于cityRepository未被实例化。

通过查看您的配置,我发现您只使用了@EnableJpaRepositories注解注册了UserRepository

尝试将CityRepository也添加到@EnableJpaRepositories中,并将此bean指定为自动连接的候选对象(就像您为UserRepository所做的那样,还要为此bean添加@Autowired)。

按照良好的实践,遵循MVC结构,最好是将所有与数据库执行CRUD操作的bean,也就是您的Spring repositories,都放在同一个包下。

英文:

The problem you are encountering, more specifically the NullPointerException at line 54 of your main application, is caused by the fact that the cityRepository is not
instantiated.

Looking through your configuration, I see that you only register the UserRepository with the @EnableJpaRepositories annotation.

Try adding also the CityRepository to the @EnableJpaRepositories, and also specify this bean as a candidate for autowiring( also add @Autowired to this bean, as you did for UserRepository)

For a good practice, following the MVC structure, it would be nice is all your spring repositories, the beans responsible for all CRUD operations with the database to be under the same package

huangapple
  • 本文由 发表于 2020年8月29日 04:29:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/63640492.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定