Обновление пользователя через HTML-форму удаляет роль пользователя в базе данных - PullRequest
0 голосов
/ 13 марта 2019

Как видно из заголовка, у меня возникли трудности в моем проекте Java + Spring / Hibernate, когда при переходе к обновлению и информации о сотрудниках или клиентах они удаляют их роль из таблицы employee_roles / customer_roles в базе данных.

У меня была такая же проблема с удалением имени пользователя, однако я смог обойти это, создав скрытую форму ввода имени пользователя на html-странице.

Файлы для запуска этого проекта могут бытьниже, если вы обнаружите, что не можете заставить его работать должным образом на Mac, это может быть связано с тем, что вам нужно изменить jdbc.url на просто: jdbc: mysql: // localhost: 3306 / spring_pie_deal

https://drive.google.com/file/d/1YAdaGCQXH-tjDy8EfnV0WagcV33I8ADM/view?usp=sharing

Сотрудник:

@Entity
@Table(name = "employee")

public class Employee {

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

@Column(name = "username")
private String userName;

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

@Column(name = "first_name")
private String firstName;

@Column(name = "last_name")
private String lastName;

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

@Column(name = "phone_number")
private String phoneNumber;

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

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


@ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
@JoinTable(name = "employee_roles",
        joinColumns = @JoinColumn(name = "employee_id"),
        inverseJoinColumns = @JoinColumn(name = "role_id"))
private Collection<Role> roles;

public Employee() {
}

public Employee(String userName, String password, String firstName, String lastName, String email, String phoneNumber, String address, String zipcode) {
    this.userName = userName;
    this.password = password;
    this.firstName = firstName;
    this.lastName = lastName;
    this.email = email;
    this.phoneNumber = phoneNumber;
    this.address = address;
    this.zipcode = zipcode;
}

public Employee(String userName, String password, String firstName, String lastName, String email, String phoneNumber, String address, String zipcode, Collection<Role> roles) {
    this.userName = userName;
    this.password = password;
    this.firstName = firstName;
    this.lastName = lastName;
    this.email = email;
    this.phoneNumber = phoneNumber;
    this.address = address;
    this.zipcode = zipcode;
    this.roles = roles;
}

public Long getId() {
    return id;
}

public void setId(Long 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 String getFirstName() {
    return firstName;
}

public void setFirstName(String firstName) {
    this.firstName = firstName;
}

public String getLastName() {
    return lastName;
}

public void setLastName(String lastName) {
    this.lastName = lastName;
}

public String getEmail() {
    return email;
}

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

public String getPhoneNumber() {
    return phoneNumber;
}

public void setPhoneNumber(String phoneNumber) {
    this.phoneNumber = phoneNumber;
}

public String getAddress() {
    return address;
}

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

public String getZipcode() {
    return zipcode;
}

public void setZipcode(String zipcode) {
    this.zipcode = zipcode;
}

public Collection<Role> getRoles() {
    return roles;
}

public void setRoles(Collection<Role> roles) {
    this.roles = roles;
}


@Override
public String toString() {
    return "Employee{" +
            "id=" + id +
            ", userName='" + userName + '\'' +
            ", password='" + password + '\'' +
            ", firstName='" + firstName + '\'' +
            ", lastName='" + lastName + '\'' +
            ", email='" + email + '\'' +
            ", phoneNumber='" + phoneNumber + '\'' +
            ", address='" + address + '\'' +
            ", zipcode='" + zipcode + '\'' +
            ", roles=" + roles +
            '}';
}
}

Роль:

@Entity
@Table(name = "role")
public class Role {

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

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

public Role() {
}

public Role(String name) {
    this.name = name;
}

public Long getId() {
    return id;
}

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

public String getName() {
    return name;
}

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

@Override
public String toString() {
    return "Role{" + "id=" + id + ", name='" + name + '\'' + '}';
}
}

EmployeeDAOImpl:

@Repository
public class EmployeeDaoImpl implements EmployeeDAO{

@Autowired
private SessionFactory sessionFactory;

// define getEmployee method
@Override
public Employee getEmployee(Long theId) {
    // get current hibernate session
    Session currentSession = sessionFactory.getCurrentSession();

    // get Employee by the id
    Employee theEmployee = currentSession.get(Employee.class, theId);

    // return the employee
    return theEmployee;
}

// define saveEmployee method
@Override
public void saveEmployee(Employee theEmployee) {
    // get current hibernate session
    Session currentSession = sessionFactory.getCurrentSession();

    // save Employee by the id
    currentSession.saveOrUpdate(theEmployee);
}

// define deleteEmployee method
@Override
public void deleteEmployee(Long theId) {
    // get current hibernate session
    Session currentSession = sessionFactory.getCurrentSession();

    // delete Employee by id
    currentSession.delete(theId);
}

@Override
public List<Employee> getEmployees() {
    // get current hibernate session
    Session currentSession = sessionFactory.getCurrentSession();

    // create query
    Query<Employee> theQuery =
            currentSession.createQuery("from Employee order by lastName", Employee.class);

    // apply result list to variable list
    List<Employee> theEmployees = theQuery.getResultList();

    // return the result list variable
    return theEmployees;
}

@Override
public Employee findByUserName(String userName) {
    // get current hibernate session
    Session currentSession = sessionFactory.getCurrentSession();

    // now create query... where username(from database) matches uName(direct relationship with userName1)
    Query<Employee> theQuery = currentSession.createQuery("from Employee where username=:uName", Employee.class);
    theQuery.setParameter("uName", userName);

    Employee theEmployee = null;
    try {
        theEmployee = theQuery.getSingleResult();
    }
    catch (Exception e) {
        theEmployee =null;
    }
    return theEmployee;
}

@Override
public void save(Employee employee) {
    // get current hibernate session
    Session currentSession = sessionFactory.getCurrentSession();

    // create or save user
    currentSession.saveOrUpdate(employee);
}


}

Employee-form.jsp:

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix="security" uri="http://www.springframework.org/security/tags" %>

<!DOCTYPE html>
<html>

<head>
<title>Update Employee</title>

<link type="text/css"
      rel="stylesheet"
      href="${pageContext.request.contextPath}/resources/css/style.css">

<link type="text/css"
      rel="stylesheet"
      href="${pageContext.request.contextPath}/resources/css/add-customer-style.css">
</head>

<body>

<div id="wrapper">
<div id="header">
    <h2>ERM - Employee Relationship Manager</h2>
</div>
</div>

<div id="container">
<h3>Update Employee</h3>

<form:form action="saveEmployee"
           modelAttribute="employee">

    <!-- need to associate this data with a employee id -->
    <form:hidden path="id" />

    <table>
        <tbody>

        <tr>
            <td><form:input type="hidden" path="userName" /></td>

        </tr>

        <tr>
            <td><form:input type="hidden" path="password" /></td>
        </tr>
        <tr>
            <td><label>First name:</label></td>
            <td><form:input path="firstName" /></td>
        </tr>

        <tr>
            <td><label>Last name:</label></td>
            <td><form:input path="lastName" /></td>
        </tr>

        <tr>
            <td><label>Email:</label></td>
            <td><form:input path="email" /></td>
        </tr>

        <tr>
            <td><label>Phone Number:</label></td>
            <td><form:input path="phoneNumber" /></td>
        </tr>

        <tr>
            <td><label>Address:</label></td>
            <td><form:input path="address" /></td>
        </tr>

        <tr>
            <td><label>Zip Code:</label></td>
            <td><form:input path="zipcode" /></td>
        </tr>

        <tr>
            <td><label></label></td>
            <td><input type="submit" value="Save" class="save" /></td>
        </tr>


        </tbody>
    </table>


</form:form>

<div style="clear; both;"></div>

<!-- Add a logout button -->
<form:form action="${pageContext.request.contextPath}/logout"
           method="POST">

    <input type="submit" value="Logout" />

</form:form>

<p>
    <a href="${pageContext.request.contextPath}/customer/list">Back to List</a>
</p>

</div>

</body>

</html>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...