0

I have a Spring checkbox:

<spring:url value="/car/save" var="formUrl"/>

  <form:form action="${formUrl}" method="POST" modelAttribute="car">

      <div class="form-group">
                <label for="equipment">Equipment</label>
                <form:checkboxes path="equipment" id="equipment" items="${equipmentList}"/>
      </div>

   <button type="submit" class="btn btn-default">Submit</button>

</form:form>

Controler looks like this:

@RequestMapping(value="/add",method=RequestMethod.GET)
public String addCar(Model model){

    List<String> equipment = new LinkedList<>(Arrays.asList(new String[]{"AC","ABS","ESP","GPS","Cabrio"}));

    model.addAttribute("car",new Car());
    model.addAttribute("equipmentList",equipment);
    return "addCar";
}

and Car entity:

@Entity
@Table(name="CAR")
public class Car {

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

@Column(name="EQUIPMENT")
private String[] equipment;
}

When I first tried to persist the Car entity, I got an exception because value was too long for the db table. I changed it to 200 chars but now I end up with: enter image description here How can I store a value from Spring checkbox?

jarosik
  • 4,136
  • 10
  • 36
  • 53

1 Answers1

0

There are different ways to store a collection of attributes in JPA. You can tell JPA to store String attributes within a VARCHAR cell using a separator (e.g. "|"). Or you can create a more complex association between a Car entity and a Attribute (Equipment) entity (a JOIN). I'd rather go with the latter as per I like the E-R constrain and the flexibility to add fields (e.g. description) to those attributes. Your 'equipment' should be a Set of something, or a List if you allow multiple entries of the same value. While you get back a String[] from the POST form you go through the array and change/populate the Set (JPA field) accordingly. You are probably storing the reference now instead of values, this is why you get that gibberish back.

Similar question JPA: Store a list of integers in a single field

Community
  • 1
  • 1
m c
  • 1,104
  • 1
  • 12
  • 21