Контроллер DAO для внешнего ключа в java jstl - PullRequest
0 голосов
/ 24 апреля 2020

У меня есть 2 таблицы, чтобы присоединиться. Первая таблица называется students с несколькими полями => (идентификатор студента, имя, имя, пол, дата рождения, адрес, телефон, электронная почта, статус, дата регистрации, идентификатор лицензии)

Моя вторая таблица называется licenses с 2 полями => (licenseID, type_license).

Мой SQL запрос кажется правильным, вот ниже:

SELECT students.studentID, students.name, students.firstname, students.dateofbirth, students.sex, students.address, 
students.phone, students.email, students.status, students.dateofbirth, licenses.type_license 

FROM students 

INNER JOIN licenses 

ON students.licenseID = licenses.licenseID

Я думаю, что мои модели тоже в порядке *

Модель студента

package com.autoecole.model;


public class Student {

    private int studentID;
    private String name;
    private String firstname;
    private String dateofbirth;
    private String sex;
    private String address;
    private String phone;
    private String email;
    private String status;
    private String dateregister;
    private int licenseID;

    public void setStudentID(int studentID) {
        this.studentID = studentID;
    }

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

    public void setFirstname(String firstname) {
        this.firstname = firstname;
    }

    public void setDateofbirth(String dateofbirth) {
        this.dateofbirth = dateofbirth;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public void setDateregister(String dateregister) {
        this.dateregister = dateregister;
    }

    public void setLicenseID(int licenseID) {
        this.licenseID = licenseID;
    }
    public int getStudentID() {
        return studentID;
    }

    public String getName() {
        return name;
    }

    public String getFirstname() {
        return firstname;
    }

    public String getDateofbirth() {
        return dateofbirth;
    }

    public String getSex() {
        return sex;
    }

    public String getAddress() {
        return address;
    }

    public String getPhone() {
        return phone;
    }

    public String getEmail() {
        return email;
    }

    public String getStatus() {
        return status;
    }

    public String getDateregister() {
        return dateregister;
    }

    public int getLicenseID() {
        return licenseID;
    }   

}

Лицензия на модель

public class License {

    private int licenseID;
    private String type_license;

    public void setLicenseID(int licenseID) {
        this.licenseID = licenseID;
    }

    public void setTypeLicense(String type_license) {
        this.type_license = type_license;
    }

    public int getLicenseID() {
        return licenseID;
    }

    public String getTypeLicense() {
        return type_license;
    }

}

В моем методе getAllRecordsStudents () у меня есть сообщение об ошибке на этом строка:

 studentBean.setTypeLicense(rs.getString("licenses.type_license"));

" Метод setTypeLicense (String) не определен для типа Student "

public static List getAllRecordsStudents(){  
        List <Student> list=new ArrayList<Student>();  

        try{  
            Connection con=getConnection();  
            PreparedStatement ps=con.prepareStatement("SELECT students.studentID, students.name, students.firstname, students.dateofbirth, students.sex, students.address, students.phone, students.email, students.status, students.dateofbirth, licenses.type_license FROM students INNER JOIN licenses ON students.licenseID = licenses.licenseID");  
            ResultSet rs=ps.executeQuery();  
            while(rs.next()){  
                Student studentBean =new Student();  
                studentBean.setStudentID(rs.getInt("studentID"));  
                studentBean.setName(rs.getString("name"));  
                studentBean.setFirstname(rs.getString("firstname")); 
                studentBean.setDateofbirth(rs.getString("dateofbirth"));  
                studentBean.setSex(rs.getString("sex"));  
                studentBean.setAddress(rs.getString("address")); 
                studentBean.setPhone(rs.getString("phone")); 
                studentBean.setEmail(rs.getString("email")); 
                studentBean.setStatus(rs.getString("status")); 
                studentBean.setDateregister(rs.getString("dateregister")); 
                studentBean.setTypeLicense(rs.getString("licenses.type_license"));
                list.add(studentBean);  
            }  
        }catch(Exception e){System.out.println(e);}  
        return list;  
    }  

Редактировать : Вот скриншот

enter image description here

Метод AddStudent ()

public static int addStudent(Student studentBean){  
        int status=0;  
        try{  
            Connection con=getConnection();  
            PreparedStatement ps=con.prepareStatement("insert into students(name, firstname, sex, dateofbirth, address, phone, email, status, dateregister, licenseID) values(?,?,?,?,?,?,?,?,?,?)");  
            ps.setString(1,studentBean.getName());   
            ps.setString(2,studentBean.getFirstname());   
            ps.setString(3,studentBean.getDateofbirth());    
            ps.setString(4,studentBean.getSex());  
            ps.setString(5,studentBean.getAddress());
            ps.setString(6, studentBean.getPhone());
            ps.setString(7, studentBean.getEmail());
            ps.setString(8, studentBean.getStatus());
            ps.setString(9, studentBean.getDateregister());
            ps.setInt(10, studentBean.getLicenseID());
            status=ps.executeUpdate();  
        }catch(Exception e){System.out.println(e);}  
        return status;  
    }

С уважением, я не понимаю, что мне делать?

1 Ответ

1 голос
/ 24 апреля 2020

с объединением вам не нужно определять имя таблицы в поиске набора результатов, так как оно возвращает новое представление обеих таблиц.

rs.getString("licenses.type_license");

измените его на

rs.getString("type_license");

и должно работать.

Если вы можете, взгляните на полную таблицу в базе данных, которая возвращается при выполнении этого запроса

** EDIT Это неправильные типы. type_license - это строка в лицензии, а int в студенте.

, чтобы получить значение, которое вам потребуется для его анализа или изменения одного из типов. Мне нравится;

studentBean.setTypeLicense(Integer.valueOf(rs.getString("type_license")));

но есть несколько разных способов сделать это.

...