Failed to access Seq elements and return all Seq as Json

So, I'm extremely new to Scala and seem to be doing something horribly wrong for simple logic. I need to query the database to get all the WebsiteTemplates. Then I try to access the first element of the sequence (just for practice), but I keep getting a ClassCastException - [Ljava.lang.Object; cannot be attributed to models. WebsiteTemplate . Then I would like to return the entire Seq received as Json. Tried Json.arr () but won't work. Searched but none match a specific use case in a weird way. The code is relevant here -

WebsiteController

@Singleton
class WebsiteTemplateController @Inject()(websiteTemplateDAO: WebsiteTemplateDAO, db: DB) extends Controller{

  def index = Action.async {
    implicit request => db.withTransaction() {
      implicit em => {
        try {

          val templates: Seq[WebsiteTemplate] = websiteTemplateDAO.findAll()
          val template = templates(0)

          Logger.info("The size is " + template.name)
          Future(Ok(Json.obj(
            "message" -> "Success"
          )))
        } catch {

          case e: Exception =>
            e.printStackTrace()
            Future(InternalServerError(s"Lag gaye"))
        }
      }
    }
  }
}

      

WebsiteDAOImpl

@ImplementedBy(classOf[WebsiteTemplateDAOImpl])
trait WebsiteTemplateDAO extends DAO[WebsiteTemplate]{
  def findAll()(implicit em: EntityManager): Seq[WebsiteTemplate]
}

@Singleton
class WebsiteTemplateDAOImpl @Inject()(db: DB) extends DAOImpl(classOf[WebsiteTemplate]) with WebsiteTemplateDAO{

  override def findAll()(implicit em: EntityManager): Seq[WebsiteTemplate] = {

    val query = em.createQuery(s"SELECT idint, name FROM WebsiteTemplate")
    db.executeQuery(query)
  }
}

      

DAOImpl

trait DAO[T] {
  def findById(id:String)(implicit em:EntityManager) : Option[T]
  def create : T
}

class DAOImpl[T](cls:Class[T]) extends DAO[T] {
  def findById(id: String)(implicit em: EntityManager): Option[T] = {
    val query = em.createQuery(s"Select c from ${cls.getName} as c where c.id=:id")
    query.setParameter("id",id)
    val list = query.getResultList
    if (list.nonEmpty) {
      Option(list(0).asInstanceOf[T])
    } else {
      None
    }
  }

  override def create: T = {
    cls.newInstance()
  }
}

      

WebsiteTemplate

@Entity
@Table(name = "templates")
@EntityListeners(Array(classOf[SetForeignKeyOnSave]))
class WebsiteTemplate{

  @Id
  @Column(name = "id")
  @BeanProperty
  var intid: java.lang.Integer = _

  /*@Transient
  override var id: String = _*/

  @BeanProperty
  @Column(name = "name")
  var name: String = _
}

      

A bit more explanation for my problem. When getting the type of templates (0) using the method, getClass()

it is displayed as [Ljava.lang.Object

, whereas I expect it to be of type WebsiteTemplate

.

+3


source to share





All Articles