manytomany关系无法在play框架的映射表中保存映射的id [英] manytomany relation not able to save mapped id in mapping table in play framework

查看:76
本文介绍了manytomany关系无法在play框架的映射表中保存映射的id的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用play2.2.1并尝试在 Jobads JobCategory 模型之间创建ManyToMany关系.

I am using play2.2.1 and trying to create a ManyToMany relation between Jobads and JobCategory models.

我的 Jobads.java

package models;

@Entity
public class Jobads extends Model {

    @Id
    public Long id;

    @ManyToOne
    public Employers employer;

    @ManyToMany(cascade = CascadeType.ALL)
    @JoinTable(name = "jobads_jobcategories")
    public List<Jobcategories> jobcategory;

    @ManyToOne
    public Joblocations joblocations;

    @Required
    public String jobtype;

    @Required
    public String title;

    @Required
    public String text;

    @Required
    public Long salary;

    @Required
    public String experience;

    @Required
    public String active;

    @Formats.DateTime(pattern="yyyy-MM-dd hh:mm:yy")
    public Date created_time = new Date();

    @Formats.DateTime(pattern="yyyy-MM-dd hh:mm:yy")
    public Date modified_time ;

    @Required
    @Formats.DateTime(pattern="yyyy-MM-dd")
    public Date expire_date ;

    public static Finder<Long,Jobads> find = new Finder<Long,Jobads>(
            Long.class, Jobads.class
    );

    public static Jobads create(Jobads ja) {
        ja.save();  
        ja.saveManyToManyAssociations("jobcategory");    
        return ja; 
    }
}

我的观点:

<form action="@routes.JobAdController.save()" method="post" onsubmit="return checkEmpty();">
    <div class="row">
        <div class="col-md-6">
            <div class="block">
                <div class="header">
                    <h2>Create A New Job</h2>
                </div>
                <div class="content controls">
                    <div class="form-row">
                        <div class="col-md-3">Employer</div>
                        <div class="col-md-9">
                            <select class="form-control" name="employer.id" id="employer_id">
                                <option value="select">Select Employer</option>
                                @for(emp<-employersList) {
                                    <option value="@emp.id">@emp.company_name</option>
                                }
                            </select>
                        </div>
                    </div>
                    <div class="form-row">
                        <div class="col-md-3">Category</div>
                        <div class="col-md-9">
                            <select class="form-control" name="jobcategory.id" id="jobcategory_id">
                                <option value="select">Select Job Category</option>
                                @for(jc<-jobcategoryList) {
                                    <option value="@jc.id">@jc.name</option>
                                }
                            </select>
                        </div>
                    </div>   
                    <div class="form-row">
                        <div class="col-md-3">Location</div>
                        <div class="col-md-9">
                            <select class="form-control" name="joblocations.id" id="joblocation_id">
                                <option value="select">Select Job Location</option>
                                @for(jl<-joblocationList) {
                                    <option value="@jl.id">@jl.country,@jl.state,@jl.city</option>
                                }
                            </select>
                        </div>
                    </div>
                    <div class="form-row">
                        <div class="col-md-3">Job Type</div>
                        <div class="col-md-9">
                            <select class="form-control" name="jobtype" id="jobtype">
                                <option value="select">Select Job Type</option>
                                <option value="parttime">Part Time</option>
                                <option value="fulltime">Full Time</option>
                            </select>
                        </div>
                    </div>
                    <div class="form-row">
                        <div class="col-md-3">Title</div>
                        <div class="col-md-9"><input type="text" class="form-control" placeholder="Title" name="title" required="required"/></div>
                    </div>
                    <div class="form-row">
                        <div class="col-md-3">Text</div>
                        <div class="col-md-9"><textarea class="form-control" name="text" required="required"></textarea></div>
                    </div>
                    <div class="form-row">
                        <div class="col-md-3">salary</div>
                        <div class="col-md-9"><input type="text" class="form-control" placeholder="Salary per month"  name="salary" required="required"/></div>
                    </div>
                    <div class="form-row">
                        <div class="col-md-3">expire date</div>
                        <div class="col-md-9"><input type="date"   class="form-control" placeholder="expiry date" name="expire_date" id="expire_date"  required="required" /></div>
                        <input type="hidden"   class="form-control" placeholder="expiry date" name="exp_date" id="exp_date" />
                    </div>
                    <div class="form-row">
                        <div class="col-md-3">Active</div>
                        <div class="col-md-9">
                            <select class="form-control" name="active" id="active">
                                <option value="active">Active</option>
                                <option value="inactive">Inactive</option>
                            </select>
                        </div>
                    </div>
                    <div class="form-row">
                        <div class="col-md-12">
                            <button type="submit" class="btn btn-default btn-block">Add</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</form>

还有我的控制器:

public class JobAdController extends Controller {
    public static Result save() {

        Form<Jobads> jobadsFormData = jobadsForm.bindFromRequest();
        if (jobadsFormData.hasErrors()) {
            System.out.println("Error in form");
            return badRequest();
        } else {
            Jobads.create(jobadsFormData.get());
            return redirect(controllers.routes.JobAdController.index());
        }
    }
}

我在Jobcategory模型中没有Jobads的变量,因为我在那里不需要它.因此,将创建一个名为 jobads_jobcategories 的默认表.我的问题是,当我尝试在Jobads表中插入数据时,它可以完美插入,但映射ID不会保存在 jobads_jobcategories 表中.

I don't have a variable for Jobads in Jobcategory model because I dont need it there. So a default table is created named jobads_jobcategories. My problem is that when I am trying to insert a data in jobads table it is inserted perfectly but the mapping ids are not saved in jobads_jobcategories table.

推荐答案

由于 rtruszk 的帮助,我的工作类别列表为空. Play无法将请求中的多值变量绑定到模型许多列表变量(我仍在尝试弄清楚play为什么这样做的原因)

My jobcategorylist was empty thanks to rtruszk for helping me out. Play is not able to bind the mutiple valued variable from request to models manytomany list variable (I am still tryng to figure this out why play is doing that)

因此,我为解决此问题所做的事情,我更改了form方法,以从控制器中的url获取多值变量的值,然后创建了一个新列表,并将其添加到Form变量中.它是可选的,但我添加了getter和setter并更改了列表名称.下面给出的代码

So what I did to solve this problem, I changed the form method to get the value of mutiple valued variable from url in my controller then created a new list and added to my Form variable. It's optional but I added getter and setter and changed my list name. Code given below

对于 GET 请求

public static Result save() {

    List<Long> jobCatList = new ArrayList<Long>();
    final Set<Map.Entry<String, String[]>> entries = request().queryString().entrySet();
    for (Map.Entry<String, String[]> entry : entries) {
        final String key = entry.getKey();
        final String value = Arrays.toString(entry.getValue());
        System.out.println(key + " " + value);
        if (key.equalsIgnoreCase("jobcategories.id")) {
            String val = value;
            val = val.replace("[", "");
            val = val.replace("]", "");
            String[] a = val.split(",");
            for (int i = 0; i < a.length; i++) {
                jobCatList.add(Long.parseLong(a[i].trim()));
            }
        }
    }
    List<Jobcategories> jobCatObList = new ArrayList<Jobcategories>();
    for (Long id : jobCatList) {
        System.out.println("Id are:" + id);
        jobCatObList.add(Jobcategories.findById(id));
    }
    System.out.println(request().getQueryString("jobcategories.id"));
    Form<Jobads> jobadsFormData = jobadsForm.bindFromRequest();
    System.out.println("\nCategory Form are:" + (jobadsFormData.get()).getJobcategories());
   (jobadsFormData.get()).setJobcategories(jobCatObList);
    if (jobadsFormData.hasErrors()) {
        return badRequest();
    } else {
        Jobads.create(jobadsFormData.get());
        return redirect(controllers.routes.JobAdController.index());
    }
}

OR

对于 POST 请求

public static Result save() {

        Form<Jobads> jobadsFormData = jobadForm.bindFromRequest();

        Map<String, String[]> formUrlEncoded = request().body().asFormUrlEncoded();

        List<Jobcategories> fa = new ArrayList<Jobcategories>();


        for (String key : formUrlEncoded.keySet()) {
            String[] values = formUrlEncoded.get(key);
            for (String val : values) {
                if ("jobcategories.id".equals(key)) fa.add(Jobcategories.findById(Long.valueOf(val)));

            }
        }

            if (jobadsFormData.hasErrors()) {
            return badRequest();
        } else {
            (jobadsFormData.get()).setJobcategories(fa);

            Jobads.create(jobadsFormData.get());
            return redirect();

        }
    }

我知道这种方法不是保存多对多关系的正确方法,但是我没有其他选择可以解决我的问题.

I know that this method is not the correct way of saving manytomany relation but I didn't have any other option to resolve my problem.

如果有人有更好的解决方案,那就发布它,因为我已经尝试了好几天,并且已经取得了很多成就.

If anybody have a better solution then do post it because I am trying this for days and have achieves this much.

为什么游戏不能映射或保存许多关系?

And why play is not able to map or save the manytomany relation?

这篇关于manytomany关系无法在play框架的映射表中保存映射的id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆