玩框架模型关系

时间:2014-06-18 01:23:55

标签: orm playframework entity entity-relationship ebean

我正在研究使用play java编写api的play框架,我做了插入,删除,更新。

当我使用会话制作登录系统时,我对两个模型之间的关系表示怀疑。

我在网上搜索了2天,但我无法理解我该怎么做。

我正在使用ebean,实体模型,并尝试一下:

我的控制器:

package controllers;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import models.AdministratorSessions;
import models.Administrators;
import play.libs.Json;
import play.mvc.*;

import java.util.List;

import static play.libs.Json.toJson;

public class Administrator extends Controller {
    public static Result login(){
        JsonNode json               = request().body().asJson();

        if(json != null){
            String email    = json.findPath("email").asText();
            String password = json.findPath("password").asText();

            AdministratorSessions admSession = Administrators.loginAdm(email, password);

            if(admSession != null) {
                ObjectNode result = Json.newObject();
                result.put("status", "OK");
                result.put("dara", Json.toJson(admSession));
                return ok(toJson(result));
            }else{
                return badRequest("Error loggin administrator");
            }
        }else{
            return badRequest("Expecting Json data");
        }
    }
}

我的管理员模型:

package models;

import javax.persistence.*;
import play.db.ebean.*;
import utils.HashString;

import java.util.*;

/**
 * Created by sidnei on 6/12/14.
 */
@Entity
public class Administrators extends Model {

    @Id
    @Column(name="administrator_id", nullable=false, length=32)
    public String id;

    @Column(name="administrator_email", nullable=false, length=255)
    public String email;

    @Column(name="administrator_name", nullable=false, length=255)
    public String name;

    @Column(name="administrator_password", nullable=false, length=32)
    public String password;

    @Column(name="administrator_date", nullable=false)
    public Date admDate;

    @Column(name="administrator_active", nullable=false)
    public Boolean active;

    @OneToMany(cascade = CascadeType.PERSIST, mappedBy = "administrators")
    public List<AdministratorSessions> administrator_sessions;

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

    public Administrators(String _name, String _email, String _password) {
        this.name       = _name;
        this.email      = _email;
        this.password   = HashString.makeHash(_password);
        this.admDate    = new Date();
        this.active     = true;
        this.id         = HashString.makeHash(_name + _email + password + "locationProjectSecret");
    }

    public static Administrators createAdm(String _name, String _email, String _password){
        try {
            Administrators adm = new Administrators(_name, _email, _password);
            adm.save();
            return adm;
        }catch (Exception e){
            return null;
        }
    }

    public static AdministratorSessions loginAdm(String _email, String _password){
        try {
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("email", _email);
            params.put("password", HashString.makeHash(_password));

            Administrators adm = Administrators.find.where().allEq(params).findUnique();

            if (adm != null){
                AdministratorSessions admSession = AdministratorSessions.create(adm.id);
                return admSession;
            }else{
                return null;
            }
        }catch (Exception e){
            return null;
        }
    }
}

我的管理员会话模型:

package models;

import play.Logger;
import play.db.ebean.Model;
import utils.HashString;

import javax.persistence.*;
import java.util.Date;

/**
 * Created by sidnei on 6/12/14.
 */
@Entity
public class AdministratorSessions extends Model {

    @Id
    @Column(name="administrator_session_key", nullable=false, length=32)
    public String id;

    @Column(name="administrator_session_date", nullable=false)
    public Date sessionDate;

    @Column(name="administrator_session_active", nullable=false)
    public Boolean active;

    @ManyToOne
    @JoinColumn(name = "administrator_id")
    public Administrators administrators;

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

    public AdministratorSessions(String _adminId) {
//        this.administrator_id   = _adminId;
        this.sessionDate        = new Date();
        this.id                 = HashString.makeHash(_adminId + this.sessionDate.toString() + "locationProjectSecretForSession" + Math.random());
        this.active             = true;
    }

    public static AdministratorSessions create(String _adminId){
        try{
            AdministratorSessions admSessions = new AdministratorSessions(_adminId);
            admSessions.save();
            return admSessions;
        }catch (Exception e){
            Logger.info("aqui");
            Logger.debug(e.getMessage());
            return  null;
        }
    }
}

但是当我保存我的表格时,“administrator_sessions”是这样的:

 session_key | session_date | session_active | administrator_id
-------------+--------------+----------------+-----------------
 f1d4c3296d1 | 2014-06-17   | t              |

(这是一个例子)。

因此,administrator_id永远不会填写管理员模型中的管理员ID。

我该怎么做?做这个api的最佳做法是什么?

如果某人有一个例子或解释它是如何工作的,我会太过分了!

由于

===========编辑已解决

您好,

我解决了这个问题,首先,显然,我需要传递对象管理员而不是管理员的ID。

然后我遇到了json serialize的问题(RuntimeException:java.lang.IllegalArgumentException:Infinite recursion)。

有了这个主题:Infinite Recursion with Jackson JSON and Hibernate JPA issue我解决了我的问题,所以,我的课程现在是这样的:

管理员模型:

package models;

import javax.persistence.*;

import com.fasterxml.jackson.annotation.JsonManagedReference;
import play.Logger;
import play.db.ebean.*;
import utils.HashString;

import java.util.*;

/**
 * Created by sidnei on 6/12/14.
 */
@Entity
public class Administrators extends Model {

    @Id
    @Column(name="administrator_id", nullable=false, length=32)
    public String id;

    @Column(name="administrator_email", nullable=false, length=255)
    public String email;

    @Column(name="administrator_name", nullable=false, length=255)
    public String name;

    @Column(name="administrator_password", nullable=false, length=32)
    public String password;

    @Column(name="administrator_date", nullable=false)
    public Date admDate;

    @Column(name="administrator_active", nullable=false)
    public Boolean active;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "administrators")
    @Column(nullable = true)
    @JsonManagedReference
    public Set<AdministratorSessions> administrator_sessions;

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

    public static AdministratorSessions loginAdm(String _email, String _password){
        try {
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("email", _email);
            params.put("password", HashString.makeHash(_password));

            Administrators adm = Administrators.find.where().allEq(params).findUnique();

            if (adm != null){
                AdministratorSessions admSession = AdministratorSessions.create(adm);
                return admSession;
            }else{
                return null;
            }
        }catch (Exception e){
            return null;
        }
    }
}

管理员会话模型:

package models;

import com.fasterxml.jackson.annotation.JsonBackReference;
import play.Logger;
import play.db.ebean.Model;
import utils.HashString;

import javax.persistence.*;
import java.util.Date;

/**
 * Created by sidnei on 6/12/14.
 */
@Entity
public class AdministratorSessions extends Model {

    @Id
    @Column(name="administrator_session_key", nullable=false, length=32)
    public String key;

    @Column(name="administrator_session_date", nullable=false)
    public Date sessionDate;

    @Column(name="administrator_session_active", nullable=false)
    public Boolean active;

    @ManyToOne
    @JoinColumn(name = "administrator_id")
    @JsonBackReference
    public Administrators administrators;

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

    public AdministratorSessions(Administrators _adm) {
        this.administrators     = _adm;
        this.sessionDate        = new Date();
        this.key                = HashString.makeHash(_adm.id + this.sessionDate.toString() + "locationProjectSecretForSession" + Math.random());
        this.active             = true;
    }

    public static AdministratorSessions create(Administrators _adm){
        try{
            AdministratorSessions admSessions = new AdministratorSessions(_adm);
            admSessions.save();
            return admSessions;
        }catch (Exception e){
            Logger.info("aqui");
            Logger.debug(e.getMessage());
            return  null;
        }
    }
}

现在工作正常,谢谢

0 个答案:

没有答案