@webserverby
Java junior

Как в Spring mvc сохранить данные из двух таблиц связанные @OneToOne?

Помогите советом. При отправке данных с jps страницы не получается сохранить в базу данных MySQL объект Client в состав которого входит объект Passport.
Страница выдает ошибку
HTTP Status 500 - Request processing failed; nested exception is java.lang.NullPointerException


Класс Client
@Entity
@Table(name = "client")
public class Client {

    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Basic
    @Column(name = "surname")
    private String surname;

    @Basic
    @Column(name = "name")
    private String name;

    @Basic
    @Column(name = "patronymic")
    private String patronymic;

    @Basic
    @Column(name = "phoneMobile")
    private String phoneMobile;    

    @OneToOne(cascade = CascadeType.ALL)
    @JoinColumn(name = "passport_id")
    private Passport passport;

    public Client() {    }
 
    public int getId() {    return id;    }

    public void setId(int id) {       this.id = id;   }

    public String getSurname() {      return surname;   }

    public void setSurname(String surname) {      this.surname = surname;   }

    public String getName() {     return name;   }

    public void setName(String name) {      this.name = name;   }

    public String getPatronymic() {    return patronymic;   }

    public void setPatronymic(String patronymic) {     this.patronymic = patronymic;   }

    public String getPhoneMobile() {    return phoneMobile;   }

    public void setPhoneMobile(String phoneMobile) {     this.phoneMobile = phoneMobile;   }  

    public Passport getPassport() {        return this.passport;    }

    public void setPassport(Passport passport) {       this.passport = passport;   }
}


Класс Passport
@Entity
@Table(name = "passport")
public class Passport {
    @Id
    @Column(name = "id")
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Basic
    @Column(name = "series")
    private String series;

    @Basic
    @Column(name = "number")
    private String number;

    @Basic
    @Column(name = "received")
    private String received;  

    @OneToOne(mappedBy = "passport")
    private Client client;

    public Passport() {
    }
   
    public Client getClient() {      return client;   }

    public void setClient(Client client) {       this.client = client;   }


    public int getId() {      return id;   }

    public void setId(int id) {      this.id = id;   }

    public String getSeries() {      return series;  }

    public void setSeries(String series) {     this.series = series;   }


    public String getNumber() {     return number;  }

    public void setNumber(String number) {     this.number = number;  }


    public String getReceived() {      return received;  }

    public void setReceived(String received) {    this.received = received;   }
}


Контролер
@Controller
public class ClientController {
    @Autowired
    private ClientService clientService;
       
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String addClient(@ModelAttribute Client client) {
        clientService.addClient(client);
        return "redirect:/client";
    }
}


Дао класс
@Repository
public class ClientDaoImpl implements ClientDao{

    @Autowired
    PassportService passportService;
    @Autowired
    private SessionFactory sessionFactory;

    public void addClient(Client client){
       Passport passport = passportService.getPassportById(client.getPassport().getId());
        client.setPassport(passport);
        sessionFactory.getCurrentSession().save(client);
    }

/* Этот метод тоже не работает
public void addClient(Client client){       
        sessionFactory.getCurrentSession().save(client);
    }
*/
}

Код страницы отправки jsp
<%@ page language="java" contentType="text/html"	pageEncoding="utf8"%>
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

<!DOCTYPE html>
<html lang="ru">
<body>
<form action="${pageContext.servletContext.contextPath}/add" method="post">
    
    <table  >
        <tr>           
            <th><input type="text" name="surname" placeholder="Фамилия" ></th>
        </tr>
        <tr>           
            <th><input type="text" name="name" placeholder="Имя" ></th>
        </tr>
        <tr>           
            <th><input type="text" name="patronymic" placeholder="Отчество" ></th>
        </tr>
        <tr>            
            <th><input type="text" name="phoneMobile" placeholder="Телефон" ></th>
        </tr>
        <tr>           
            <th><input type="text" name="series" id="series"  placeholder="Серия" ></th>
        </tr>
        <tr>           
            <th><input type="text" name="number" id="number"  placeholder="Номер" ></th>
        </tr>
        <tr>            
            <th><input type="text" name="received" id="received"  placeholder="Кем выдан" ></th>
        </tr>

    </table>
	
    <input type="submit"  value="Создать">
    </div>
</form>
</body>
</html>
  • Вопрос задан
  • 496 просмотров
Решения вопроса 1
@webserverby Автор вопроса
Java junior
Вопрос снимается, я нашел решение. Изменил на jsp странице имена полей добавив к данным из второй таблицы приставку passport.
<form action="${pageContext.servletContext.contextPath}/add" method="post">  
    <table >            
            <th><input type="text" name="surname"  placeholder="Фамилия" ></th>    
            <th><input type="text" name="name"   placeholder="Имя" ></th>          
            <th><input type="text" name="patronymic"   placeholder="Отчество" ></th>      
            <th><input type="text" name="phoneMobile"  placeholder="Телефон" ></th>
             
            <th><input type="text" name="passport.series"  placeholder="Серия" ></th>        
            <th><input type="text" name="passport.number" placeholder="Номер" ></th>         
            <th><input type="text" name="passport.received"   placeholder="Выдан" ></th>       
    </table>
    <input type="submit"  value="Создать">
    </div>
</form>
Ответ написан
Комментировать
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы
Bell Integrator Хабаровск
До 400 000 ₽
Bell Integrator Ульяновск
До 400 000 ₽
Bell Integrator Ижевск
До 400 000 ₽