简体   繁体   English

Scala Play框架解析错误

[英]scala play framework parsing error

I have 2 foriegn key with same table and it parse into the program get a compilation error The problem is the 2 Id's are get null 我有2个具有相同表的foriegn键,它解析到程序中会得到编译错误问题是2个ID为空

Model Class MyFriend & functions 模型类MyFriend和功能

case class MyFriend(id: Pk[Long]= NotAssigned,user_Id:Option[Long],friend_Id:Option[Long],is_accepted:Boolean)
object MyFriend{
  /**
   * parse a Myfreind from a ResultSet.
   */
  val simple ={
    get[Pk[Long]]("myfriend.id") ~
    get[Option[Long]]("myfriend.user_Id")~
    get[Option[Long]]("myfriend.friend_Id")~
    get[Boolean]("myfriend.is_accepted") map{
      case id ~ user_Id ~ friend_Id ~ is_accepted => MyFriend(id, user_Id,friend_Id,is_accepted)
    }
   }


 /**
   * Parse a MyFriend from a userProfile
   */
  val withUserProfile =MyFriend.simple ~ (UserProfile.simple ?) map{
    case myfriend  ~ userprofile => (myfriend, userprofile)
  }
  /**
   * create a new MyFriend.
   *
   * @param myfriend 
   */
  def insert(myFriend: MyFriend): Long = {
    DB.withConnection { implicit connection =>
      SQL(
        """
          insert into MY_FRIEND(USER_ID,FRIEND_ID,IS_ACCEPTED) values (
            {user_Id}, {friend_Id},{is_accepted}
          )
        """).on(
          'user_Id -> myFriend.user_Id,
          'friend_Id -> myFriend.friend_Id,
          'is_accepted -> myFriend.is_accepted
          ).executeUpdate()
    }
  }


/**
   * Update a MyFriend
   *
   * @param  MyFriend
   */
  def update(myFriend:MyFriend)={
  DB.withConnection{ implicit connection =>
    SQL(
        """
        update MY_FRIEND
        set FRIEND_ID = {friend_Id}, IS_ACCEPTED={is_accepted} where USER_ID={use_id}
        """).on(
          'user_Id -> myFriend.user_Id,
          'friend_Id -> myFriend.friend_Id,
          'is_accepted -> myFriend.is_accepted
          ).executeUpdate()

  }

}
/**
   * Find myfriendId Via userprofile
   */
  def authenticate(myFriend: MyFriend) = {
    DB.withConnection { implicit connection =>
      val myFriendFound = SQL(
        """
          select * from MY_FRIEND 
          where USER_ID = {user_Id} and FRIEND_ID={friend_Id}
        """).on(
          'user_Id -> myFriend.user_Id,
          'friend_Id ->myFriend.friend_Id
          ).as(MyFriend.simple.singleOpt)
      myFriendFound
    }
  }

Model UserProfile amd Functions 型号UserProfile和功能

case class UserProfile(id: Pk[Long] = NotAssigned, useraccountid: Option[Long], name: String, date_of_birth: Date, gender: String, image: String,status:String)

object UserProfile{

  /**
   * Parse a UserProfile from a ResultSet
   */
  val simple = {
    get[Pk[Long]]("user_profile.id") ~
      get[Option[Long]]("user_profile.user_account_id") ~
      get[String]("user_profile.name") ~
      get[Date]("user_profile.date_of_birth") ~
      get[String]("user_profile.gender") ~
      get[String]("user_profile.image") ~
      get[String]("user_profile.status") map {
        case id ~ user_account_id ~ name ~ date_of_birth ~ gender ~ image ~ status =>
          UserProfile(id, user_account_id, name, date_of_birth, gender, image,status )
      }
  }
 /**
   * Parse a userProfile from a MyFriend
   */
  val withMyFriend =UserProfile.simple ~ (MyFriend.simple ?) map{
    case userprofile  ~ myfriend  => (userprofile, myfriend)
  }
/**
   * Find MyFriend With MyFriend Detail
   */

  def myFriend(user_Id:Long) = {
    DB.withConnection { implicit connection =>
      val myFriend = SQL(
        """
          select * from MY_FRIEND
          where USER_ID = {user_id}
        """).on(
          'user_Id -> user_Id).as(MyFriend.simple.singleOpt)
      myFriend
    }
  }
  /**
   * Authonticate
   */
  def authenticate(userprofile: UserProfile) = {
    DB.withConnection { implicit connection =>
      val userProfileFound = SQL(
        """
          select * from USER_PROFILE 
          where ID = (id}
        """).on(
          'Id -> userprofile.id
          ).as(UserProfile.simple.singleOpt)
      userProfileFound
    }
  }

Controller Application method for parse friend and user Id 解析好友和用户id的控制器应用方法

val userprofile:UserProfile=null
        val myfriend:MyFriend=null

   def authenticateFriend = Action { implicit request =>
            val alert: Alert = new Alert("", "")
            Common.setAlert(alert)
            myFriendForm.bindFromRequest.fold(
            errors => BadRequest(views.html.myFriend(errors,userprofile,myfriend)),
        myFriend => {
            val myfriendOpt = MyFriend.authenticate(myFriend)
        myfriendOpt match {

       case Some(authmyfriend: MyFriend) =>
            val userSession = request.session + ("myFriendId" -> authmyfriend.id.toString)
            val friendSession=request.session + ("userProfileId" -> userprofile.id.toString)
            val myFriendOpt = MyFriend.userProfile(authmyfriend.id.get)
       myFriendOpt match {
       case None => Ok(views.html.myFriend(Application.myFriendForm, userprofile,myfriend)).withSession(userSession)
       case Some(userProfileFound: UserProfile) =>
            val myFriendFormWithDetails = Application.myFriendForm.fill(userProfileFound)
            Ok(views.html.myFriend(myFriendFormWithDetails,userprofile,authmyfriend)).withSession(userSession)

            }

          }
      })

  }

Create MyFriend Page function 创建“我的朋友页面”功能

     def createMyFriend = Action { implicit request =>
   if (request.session.get("userId") == None) {
      Results.Redirect("/")
    }
   else {
        val myfriends:MyFriend=null
        val userprofileId = request.session.get("myFriendId").get.toLong//userProfileId
        val userprofile = UserProfile.findUserByAccountId(userprofileId).get
        println(userprofile)
        val myfriendId = request.session.get("userProfileId").get.toLong//myFriendId
        val myfriend = MyFriend.friendidByUserIsAccepted(myfriendId,true)
        println(myfriend)
        myFriendForm.bindFromRequest.fold(
        errors => BadRequest(views.html.myFriend(errors, userprofile,myfriends)),
   myFriend => {
          println("errors")
          val myFriendOpt = UserProfile.myFriend(userprofile.id.get)
          println(myFriendOpt)
   myFriendOpt match {
   case None =>
          val updatedMyFriend = MyFriend(NotAssigned,
          Option(userprofileId), Option(myfriendId),myFriend.is_accepted)
          MyFriend.insert(updatedMyFriend)
          val alert: Alert = new Alert("success", " MyFriend Saved")
          Common.setAlert(alert)
          }
          Results.Redirect("/myFriend")
        })  
        }
    }        

Redirect To myFriend page 重定向到“我的朋友”页面

def myFriend = Action { implicit request =>

   Ok(views.html.myFriend(Application.myFriendForm,userprofile,myfriend))
    }

Whenrun the program get nullpointer for id's 当运行时,程序获取id的nullpointer

I am stuck with this problem with couple of days if any one had the same problem and anyone is solved 如果有人遇到相同的问题并且任何人都解决了,我会在几天之内陷入这个问题

Just add to your pattern matching construct. 只需添加到您的模式匹配结构即可。

case None => // do some if None 

or 要么

case _ => // something in this case

or you can simply ignore this case by omiting right hand side of the arrow 或者您可以通过省略箭头的右侧来简单地忽略这种情况

The problem is that you didn't cover all the posible cases in you function. 问题是您没有在函数中涵盖所有可能的情况。 You've covered Some (authuserProfile:UserProfile) and case Some(authmyfriend: MyFriend) , but not None case and it looks like your method receives None. 您已经介绍了Some (authuserProfile:UserProfile)case Some(authmyfriend: MyFriend) ,但没有None大小写,并且您的方法似乎没有None。

Updated 更新

The error occurres because you have _ which matches all cases, so you pattern matching construct just can't reach anything (Some in your case) after case _ => //... 发生错误是因为您有_匹配所有情况,所以在case _ => //...之后,模式匹配构造根本无法到达任何内容(在您的情况下为某些) case _ => //...

If i understood your code correct, the problem is in this part 如果我正确理解您的代码,则问题出在这部分

userProfileOpt match {
  case _ => Ok(views.html.myFriend(...).withSession(friendSession)
  case _ =>
    val myFriendFound: UserProfile=null
    val useracc:UserAccount=null

Both cases mathes all posible cases, that's an error 两种情况都算出所有可能的情况,这是一个错误

UserProfile.myFriend returns MyFriend , not Option[MyFriend] . UserProfile.myFriend返回MyFriend ,而不是Option[MyFriend] Therefore, your pattern match is incorrect. 因此,您的模式匹配不正确。 You can try to fix the def myFriend to return Option , or remove the pattern match. 您可以尝试修复def myFriend以返回Option ,或删除模式匹配。

(edit): Probably you should change from MyFriend.simple.single to MyFriend.simple.singleOpt . (编辑):可能应该将MyFriend.simple.single更改为MyFriend.simple.singleOpt

As a rule of thumb, always use an explicit return type from public methods. 根据经验,始终使用公共方法中的显式返回类型。 Type inference is very powerful and useful, but use it wisely. 类型推断非常强大且有用,但是要明智地使用它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM