Spring MVC with Hibernate - OneToMany mapping in form
Asked Answered
E

2

7

I have Car and Rental models conntected OneToMany relation:

@Entity
public class Rental {

private Long id;
private Car car;
private User user;

@Id
@GeneratedValue
@Column(name = "RENTAL_ID")
public Long getId() {
    return id;
}

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

@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "CAR_ID")
public Car getCar() {
    return car;
}

public void setCar(Car car) {
    this.car = car;
}

@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "USER_ID")
public User getUser() {
    return user;
}

public void setUser(User user) {
    this.user = user;
}
}





@Entity
public class Car {

private Long id;
private String name;
private String description;

@Id
@GeneratedValue
@Column(name = "CAR_ID")
public Long getId() {
    return id;
}

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

And I want to set car during rental creation:

<form:form method="POST" commandName="rental">
<form:errors path="*" cssClass="errorblock" element="div" />
<table cellspacing="10">
    <tr>
        <td>Car</td>
        <td>
        <form:select path="car" multiple="false" items="${cars}" itemLabel="name" itemValue="id"/></td>
    </tr>
    <tr>
        <td colspan="2"><input type="submit" value="Create"></td>
    </tr>
</table>

Form:select tag displays correctly available cars, but after submit Car instance variable of Rental is null.

@Controller
@RequestMapping("/make-rental.htm")
public class MakeRentalController {

private CarDAO carDAO;
private UserDAO userDAO;
private RentalDAO rentalDAO;

@Autowired
public void setCarDAO(CarDAO carDAO) {
    this.carDAO = carDAO;
}

@Autowired
public void setUserDAO(UserDAO userDAO) {
    this.userDAO = userDAO;
}

@Autowired
public void setRentalDAO(RentalDAO rentalDAO) {
    this.rentalDAO = rentalDAO;
}

@RequestMapping(method = RequestMethod.GET)
public String initForm(ModelMap mapModel) {
    Rental rental = new Rental();

    // command object
    mapModel.addAttribute("cars", carDAO.getAll());
    mapModel.addAttribute("rental", rental);

    // return form view
    return "makeRentalFormView";
}

@RequestMapping(method = RequestMethod.POST)
public String processSubmit(@ModelAttribute("rental") Rental rental,
        BindingResult result, SessionStatus status, HttpSession session) {
    Object userId = session.getAttribute("userId");
    if (userId != null) {
        rental.setUser(userDAO.getById((Long) userId));
        rentalDAO.save(rental);

        // clear the command object from the session
        status.setComplete();
    }

    // form success
    return "redirect:/index.htm";
}
}

What's wrong?

Envelopment answered 29/3, 2012 at 16:49 Comment(0)
F
8

You should implement a Service Layer into you application

For example:

public interface RentalService {
    void addRental(Rental rental, Long userId, Long carId);
}

Implementation:

@Service
@Transactional
class DefaultRentalService implement RentalService {

    @Autowired
    private CarDAO carDAO;
    @Autowired
    private UserDAO userDAO;
    @Autowired
    private RentalDAO rentalDAO;

    @Override
    void addRental(Rental rental, Long userId, Long carId) {
        User user = userDAO.getById(userId);
        Car car = carDAO.getById(carId);
        rental.setUser(user);
        rental.setCar(car);
        rentalDao.save(rental);
    }
}

HTML:

<form:form method="POST" commandName="rental">
<form:errors path="*" cssClass="errorblock" element="div" />
<table cellspacing="10">
    <tr>
        <td>Car</td>
        <td>
        <select name="carId" >
            <c:forEach items="${cars}" var="car">
               <option value="${car.id}">${car.name}
            </c:forEach>
        </select>
     </td>
    </tr>
    <tr>
        <td colspan="2"><input type="submit" value="Create"></td>
    </tr>
</table>

Controller:

@AutoWired
private RentalService rentalService;

// ..
// ..

@RequestMapping(method = RequestMethod.POST)
public String processSubmit(@ModelAttribute("rental") Rental rental, @RequestParam Long carId,
        BindingResult result, SessionStatus status, HttpSession session) {
    Object userId = session.getAttribute("userId");
    if (userId != null) {
        rentalService.add(rental, (Long)userId, carId);
        status.setComplete();
    }

    // form success
    return "redirect:/index.htm";
}
Fipple answered 30/3, 2012 at 5:6 Comment(2)
I thought that it can be served by view layer with JSTL. It's kind of workaround, but it worksEnvelopment
Your answer works, but in the long-term, it will eventually fade the purpose of the ORM in the application development process. However, I like the idea that you pushed the userId and carId to the service layer.Goeselt
G
1

You can use Spring converters.....Here is a link http://docs.spring.io/spring/docs/current/spring-framework-reference/html/validation.html

Grope answered 24/5, 2016 at 14:47 Comment(1)
This is actually the right way to do this. It is also possible to write a hierarchy of converters. It is a pity that the OP has selected another answer.Goeselt

© 2022 - 2024 — McMap. All rights reserved.