So I am extremely new to Scala and seem to be doing something horribly wrong for a simple logic. I need to query database to get all the WebsiteTemplates. I am then trying to access the first element of the sequence (simply for practice) but keep getting the ClassCastException - [Ljava.lang.Object; cannot be cast to models.WebsiteTemplate. Next, I would want to return the entire Seq obtained as Json. Tried Json.arr() but won't work. Searched but none matches the exact use case strangely. Here is relevant the code -
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 of my problem. On getting the type of templates(0) using getClass()
method, it shows as [Ljava.lang.Object
whereas I expect it to be of type WebsiteTemplate
.
0 comments:
Post a Comment