jeudi 28 mai 2015

Play Framework Checkbox Form and JPA Mapping

I have an issue related with my ManyToMany relation. The issue happens when I submit the FORM, my controller saves not only on the JOIN table the mapping, also create a new entry for Type class.

My Code:

VIEW:

@main("Create Form"){


    <h1 class="page-header">New Products Form</h1> 
    <div class="row placeholders div-table">
        <div class="col-xs-12 col-sm-12 div-table-row">
            @helper.form(routes.Products.createProducts){
                <div class="form-group">
                @helper.inputText(form("name"), '_label->"Product Name", 'id->"productName", 'name->"productName", 'class ->"form-control", 'placeholder ->"Enter ProductName") 
                </div><!--End First Form Group-->

                <div class="form-group">

                @for(type <- types) {
                <div class="checkbox">
                    <label>
                        <input type="checkbox" name='@(form("types").name)' id="@type" value="@type">
                        @type
                    </label>
                </div>
                }
                </div>
                <button class="btn btn-default">Submit</button>
                } 

Model: Product Model

@Entity
@Table(name = "Products")
public class Product{

    // Class Attributes
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "PRODUCT_ID")
    public Long id;
    public String name;

    @ManyToMany(cascade = CascadeType.ALL, fetch=FetchType.EAGER)

    public List<Type> types;

public Product save() {
        JPA.em().persist(this);
        return this;
    }

} 

Type Model:

@Entity
@Table(name = "Types")
public class Type{

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "TYPE_ID")
    public Long id;
    public String description;


    public Type(String description) {
        this.description = description;
    }

    public Type(){

    } 
    public Type save() {
        JPA.em().persist(this);
        return this;
    }

Controller:

JPA.withTransaction(new Function0<Rutine>() {
                        @Override
                        public Product apply() throws Throwable {

                            return product.save();
                        }
                    });




Aucun commentaire:

Enregistrer un commentaire