Spring MVC一对一CRUD与hibernate注释

时间:2017-03-17 10:28:56

标签: spring hibernate spring-mvc

我是Spring和hibernate框架的新手。我需要使用带有hibernate的Spring mvc插入员工详细信息。我需要从resigtrationemployee.jsp获取Employee和地址详细信息,并需要使用Bean类保存到数据库中。但是当从Employee bean获取地址时,我得到空指针异常。还怀疑我需要使用哪个Bean来插入数据。我的方法如下

AppController.java

DECLARE
   COL         VARCHAR2 (200);
   OUTRECORD   VARCHAR2 (200);

   CURSOR COLUMN_NM
   IS
      SELECT COLUMN_NAME
        FROM all_tab_columns
       WHERE     table_name = 'COMPARE_2018_P1'


   CURSOR DIFFERENCE
   IS
      SELECT OUTRECORD
        FROM (SELECT DISTINCT COL
                FROM COMPARE_2018_P1
              MINUS
              SELECT DISTINCT COL
                FROM COMPARE_2017_P1);
BEGIN
   OPEN COLUMN_NM;

   LOOP
      FETCH COLUMN_NM INTO COL;

      DBMS_OUTPUT.put_line (COL);

      OPEN DIFFERENCE;

      LOOP
         FETCH DIFFERENCE INTO OUTRECORD;

         INSERT INTO RESULT_MINUS
              VALUES ('B001',
                      'COMPARE',
                      '2018',
                      COL,
                      OUTRECORD,
                      'NOT PRESENT IN 2017');
                      COMMIT;
      END LOOP;

      CLOSE DIFFERENCE;
       END LOOP;

       CLOSE COLUMN_NM;

    END;

Employee.java

@Controller
@RequestMapping("/")
@SessionAttributes("roles")
public class AppController {

@Autowired
UserService userService;

@Autowired
EmployeeService employeeService;

@Autowired
UserProfileService userProfileService;

@Autowired
MessageSource messageSource;

@Autowired
PersistentTokenBasedRememberMeServices persistentTokenBasedRememberMeServices;

@Autowired
AuthenticationTrustResolver authenticationTrustResolver;
/*@RequestMapping(value = { "/", "/list" }, method = RequestMethod.GET)
public String listUsers(ModelMap model) {

    List<User> users = userService.findAllUsers();
    model.addAttribute("users", users);
    model.addAttribute("loggedinuser", getPrincipal());
    return "userslist";
}*/
@RequestMapping(value = { "/", "/list" }, method = RequestMethod.GET)
public String listUsers(ModelMap model) {

    List<User> users = userService.findAllUsers();
    List<Employee> employees=employeeService.findAllEmployees();
    model.addAttribute("users", users);
    model.addAttribute("employees", employees);
    model.addAttribute("loggedinuser", getPrincipal());
    return "home";
}

@RequestMapping(value = { "/newuser" }, method = RequestMethod.GET)
public String newUser(ModelMap model) {
    User user = new User();
    model.addAttribute("user", user);
    model.addAttribute("edit", false);
    model.addAttribute("loggedinuser", getPrincipal());
    return "registration";
}

@RequestMapping(value = { "/newuser" }, method = RequestMethod.POST)
public String saveUser(@Valid User user, BindingResult result,
        ModelMap model) {

    if (result.hasErrors()) {
        return "registration";
    }

    if(!userService.isUserSSOUnique(user.getId(), user.getSsoId())){
        FieldError ssoError =new FieldError("user","ssoId",messageSource.getMessage("non.unique.ssoId", new String[]{user.getSsoId()}, Locale.getDefault()));
        result.addError(ssoError);
        return "registration";
    }

    userService.saveUser(user);

    model.addAttribute("success", "User " + user.getFirstName() + " "+ user.getLastName() + " registered successfully");
    model.addAttribute("loggedinuser", getPrincipal());
    return "registrationsuccess";
}

@RequestMapping(value = { "/newemployee" }, method = RequestMethod.GET)
public String addEmployee(ModelMap model) {
    Employee employee = new Employee();
    model.addAttribute("employee", employee);
    model.addAttribute("edit", false);
    model.addAttribute("loggedinuser", getPrincipal());
    return "registrationemployee";
}

@RequestMapping(value = { "/newemployee" }, method = RequestMethod.POST)
public String saveEmployee(@Valid Employee employee, BindingResult result,
        ModelMap model) {
    System.out.println("Employee name:"+employee.getEmployeeReferenceId());
    System.out.println("Address of Employee is:"+employee.getAddress().getPlace());
    if (result.hasErrors()) {
        return "registrationemployee";
    }

    if(!employeeService.isEmployeeReferenceIdUnique(employee.getEmployeeId(), employee.getEmployeeReferenceId())){
        FieldError referenceIdError =new FieldError("employee","employeeReferenceId",messageSource.getMessage("non.unique.employeeReferenceId", new String[]{employee.getEmployeeReferenceId()}, Locale.getDefault()));
        result.addError(referenceIdError);
        return "registrationemployee";
    }

    employeeService.saveEmployee(employee);

    model.addAttribute("success", "Employee " + employee.getEmployeeName() + " registered successfully");
    model.addAttribute("loggedinuser", getPrincipal());
    return "registrationsuccess";
}

@RequestMapping(value = { "/edit-user-{ssoId}" }, method = RequestMethod.GET)
public String editUser(@PathVariable String ssoId, ModelMap model) {
    User user = userService.findBySSO(ssoId);
    model.addAttribute("user", user);
    model.addAttribute("edit", true);
    model.addAttribute("loggedinuser", getPrincipal());
    return "registration";
}
@RequestMapping(value = { "/edit-user-{ssoId}" }, method = RequestMethod.POST)
public String updateUser(@Valid User user, BindingResult result,
        ModelMap model, @PathVariable String ssoId) {

    if (result.hasErrors()) {
        return "registration";
    }

    userService.updateUser(user);

    model.addAttribute("success", "User " + user.getFirstName() + " "+ user.getLastName() + " updated successfully");
    model.addAttribute("loggedinuser", getPrincipal());
    return "registrationsuccess";
}

@RequestMapping(value = { "/delete-user-{ssoId}" }, method = RequestMethod.GET)
public String deleteUser(@PathVariable String ssoId) {
    userService.deleteUserBySSO(ssoId);
    return "redirect:/list";
}

@ModelAttribute("roles")
public List<UserProfile> initializeProfiles() {
    return userProfileService.findAll();
}

@RequestMapping(value = "/Access_Denied", method = RequestMethod.GET)
public String accessDeniedPage(ModelMap model) {
    model.addAttribute("loggedinuser", getPrincipal());
    return "accessDenied";
}

@RequestMapping(value = "/login", method = RequestMethod.GET)
public String loginPage() {
    if (isCurrentAuthenticationAnonymous()) {
        return "login";
    } else {
        return "redirect:/list";  
    }
}

@RequestMapping(value="/logout", method = RequestMethod.GET)
public String logoutPage (HttpServletRequest request, HttpServletResponse response){
    Authentication auth = SecurityContextHolder.getContext().getAuthentication();
    if (auth != null){    
        persistentTokenBasedRememberMeServices.logout(request, response, auth);
        SecurityContextHolder.getContext().setAuthentication(null);
    }
    return "redirect:/login?logout";
}
private String getPrincipal(){
    String userName = null;
    Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();

    if (principal instanceof UserDetails) {
        userName = ((UserDetails)principal).getUsername();
    } else {
        userName = principal.toString();
    }
    return userName;
}

private boolean isCurrentAuthenticationAnonymous() {
    final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
    return authenticationTrustResolver.isAnonymous(authentication);
}
}

Address.java

@Entity
@Table(name="employee")

public class Employee implements Serializable{
/**
 * 
 */
private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="employee_id")
private int employeeId=0;

@NotEmpty
@Column(name="emloyee_reference_id",length=10)
private String employeeReferenceId=null;


@NotEmpty
@Column(name="employee_name",length=30)
private String employeeName=null;

@NotEmpty
@Column(name="blood_group",length=2)
private String bloodGroup=null;

@OneToOne(mappedBy="parent")
private Address address;

public int getEmployeeId() {
    return employeeId;
}

public void setEmployeeId(int employeeId) {
    this.employeeId = employeeId;
}

public String getEmployeeName() {
    return employeeName;
}

public void setEmployeeName(String employeeName) {
    this.employeeName = employeeName;
}


public String getEmployeeReferenceId() {
    return employeeReferenceId;
}

public void setEmployeeReferenceId(String employeeReferenceId) {
    this.employeeReferenceId = employeeReferenceId;
}

public String getBloodGroup() {
    return bloodGroup;
}

public void setBloodGroup(String bloodGroup) {
    this.bloodGroup = bloodGroup;
}

public Address getAddress() {
    return address;
}

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

EmployeeService.java

@Entity
@Table(name="address")

public class Address implements Serializable {

/**
 * 
 */
private static final long serialVersionUID = 1L;


@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="employee_address_id")
private int employeeAddressId=0;

public void setEmployeeAddressId(int employeeAddressId) {
    this.employeeAddressId = employeeAddressId;
}



@Column(name="address",length=255)
private String place=null;


@OneToOne(targetEntity=Employee.class,fetch=FetchType.EAGER , cascade=CascadeType.ALL, orphanRemoval=true)
@JoinColumn(name="employee_id",referencedColumnName="employee_id")
private Employee parent;


public String getPlace() {
    return place;
}

public void setPlace(String place) {
    this.place = place;
}

public Employee getParent() {
    return parent;
}

public void setParent(Employee parent) {
    this.parent = parent;
}

public int getEmployeeAddressId() {
    return employeeAddressId;
}

}

EmployeeServiceImpl.java

public interface EmployeeService {

Employee findById(int id);
Employee findByReferenceId(String employeeRefernceId);
void saveEmployee(Employee employee);
void updateEmployee(Employee employee);
void deleteEmployeeByReferenceId(String employeeRefernceId);
List<Employee> findAllEmployees(); 
boolean isEmployeeReferenceIdUnique(Integer id, String employeeRefernceId);
}

EmployeeDao.java

@Service("employeeService")
@Transactional
public class EmployeeServiceImpl implements EmployeeService{

@Autowired
private EmployeeDao dao;

@Override
public Employee findById(int id) {
    return dao.findById(id);
}

@Override
public Employee findByReferenceId(String employeeRefernceId) {
    return dao.findByReferenceId(employeeRefernceId);
}

@Override
public void saveEmployee(Employee employee) {
    dao.save(employee);
}

@Override
public void updateEmployee(Employee employee) {
    Employee entity=dao.findById(employee.getEmployeeId());
    if(entity!=null){
        entity.setEmployeeReferenceId(employee.getEmployeeReferenceId());
        entity.setEmployeeName(employee.getEmployeeName());
        entity.setBloodGroup(employee.getBloodGroup());
        entity.setAddress(employee.getAddress());
    }
}

@Override
public void deleteEmployeeByReferenceId(String employeeRefernceId) {
    dao.deleteByReferenceId(employeeRefernceId);
}

@Override
public List<Employee> findAllEmployees() {
    return dao.findAllEmployees();
}

@Override
public boolean isEmployeeReferenceIdUnique(Integer id, String         employeeRefernceId) {
    Employee employee = findByReferenceId(employeeRefernceId);
    return ( employee == null || ((id != null) && (employee.getEmployeeId() == id)));
}
}

EmployeeDaoImpl.java

public interface EmployeeDao {

Employee findById(int id);
Employee findByReferenceId(String employeeRefernceId);
void save(Employee employee);
void deleteByReferenceId(String employeeRefernceId);
List<Employee> findAllEmployees();
}

我的堆栈跟踪是

@Repository("employeeDao")
public class EmployeeDaoImpl extends AbstractDao<Integer, Employee>     implements EmployeeDao {

static final Logger logger = LoggerFactory.getLogger(EmployeeDaoImpl.class);

public Employee findById(int id) {
    Employee employee = getByKey(id);
    if(employee!=null){
        Hibernate.initialize(employee.getAddress());
    }
    return employee;
}

public Employee findByReferenceId(String employeeReferenceId) {
    logger.info("employeeReferenceId : {}", employeeReferenceId);
    Criteria crit = createEntityCriteria();
    crit.add(Restrictions.eq("employeeReferenceId", employeeReferenceId));
    Employee employee = (Employee)crit.uniqueResult();
    if(employee!=null){
        Hibernate.initialize(employee.getAddress());
    }
    return employee;
}

public void save(Employee employee) {
    persist(employee);
}

@Override
public void deleteByReferenceId(String employeeReferenceId) {
    Criteria crit = createEntityCriteria();
    crit.add(Restrictions.eq("employeeReferenceId", employeeReferenceId));
    Employee employee = (Employee)crit.uniqueResult();
    delete(employee);
}

@Override
public List<Employee> findAllEmployees() {
    Criteria criteria = createEntityCriteria().addOrder(Order.asc("employeeReferenceId"));
    criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);//To avoid duplicates.
    @SuppressWarnings("unchecked")
    List<Employee> users = (List<Employee>) criteria.list();
    return users;
}
}

我真的觉得我错过了这个。纠正我的错误

2 个答案:

答案 0 :(得分:0)

您需要检查如何以jsp格式绑定员工模型。

示例代码应如下所示: -

<form:form action="${pageContext.request.contextPath}/register"
                   method="post" commandName="employee">

         <div>
            <label for="name">Name</label>
            <form:errors path="employeeName" cssStyle="color: #ff0000" />
            <form:input path="employeeName" id="employeeName" class="form-Control"  />
        </div>
        <div>
            <label for="address.placeName">Street Name</label>
            <form:input path="address.placeName" id="placeName" class="form-Control" />
        </div>
</form:form>

希望这能解决您的问题。

答案 1 :(得分:0)

回答以下问题: -

  

那是我的地址表没有值。但是员工的细节得到了   插入。我应该坚持地址对象而不是Employee   对象实现这一点(通过关系映射)

对于两个表上的数据,您需要使用双向关系映射,示例如下: -

Employee.class

   @OneToOne
    @JoinColumn(name = "addressId")
    private Address address;
//getter setter

Address.class

    @OneToOne
    private Customer customer;
//getter setter

然后在您的控制器中,您可以调用服务即时以仅保留员工,然后当员工数据持续存在时,地址数据也会持续存在。