scala 之 BaseDao

一·、实体类

package BaseDao

import java.util.Date

case class UseInfos(var userid:Int,var username:String, var birthday:Date) {

 def this()={
    this(0,null,null)
  }

  def setUserid(_userid:Int)={
    userid = _userid
  }

  def setUsername(_username:String)={
    username = _username
  }

  def setBirthday(_birthday:Date)={
    birthday = _birthday
  }

}
object testbase{
  def main(args: Array[String]): Unit = {

 // println(infos.birthday)
    var t = new UseInfos()
    println("=="+t.getClass.getName)
    t.getClass.getMethods.foreach(x=>println(x.getName))


  }
}

二、BaseDao

package BaseDao

import java.lang.reflect.Method
import java.sql.{DriverManager, ResultSetMetaData}
import java.util
import java.util.Map

import sun.invoke.empty.Empty

import scala.util.control.Breaks._
import scala.collection.mutable.ListBuffer


object BaseDao {

  /**
    * 连接数据库获取Connection对象
    */
  def getConnection() ={
    classOf[com.mysql.jdbc.Driver]
    DriverManager.getConnection("jdbc:mysql://192.168.56.111:3306/scala","root","root")
  }

  /**
    * 增删改
    * @param sql
    * @param params
    */
  def update(sql:String,params:Array[String])={
    var pstat = getConnection().prepareStatement(sql)
    for (i:Int <- 0 until params.length){
      pstat.setObject(i+1,params(i))
    }
    pstat.executeUpdate()
  }

  def query(sql:String,params:Array[String])={
    var pstat = getConnection().prepareStatement(sql)
    for (i:Int <- 0 until params.length){
      pstat.setObject(i+1,params(i))
    }
    pstat.executeQuery()
  }


  /**
    * 将resultSet转为List[Userinfos]
    * @param sql
    * @param params
    */
  def resetToList(sql:String,params:Array[String]) ={
    val rs = query(sql,params)
    var lst:ListBuffer[UseInfos] = ListBuffer.empty[UseInfos]
    while (rs.next()){
      lst.append(UseInfos(rs.getInt("userid"),rs.getString("username"),rs.getDate("birthday")))
    }
    lst
  }
  def parseMethod[T](c:Class[T]): Map[String,Method] = {
    var mapmethod: Map[String, Method] = new util.HashMap[String, Method]()
    var methods:Array[Method] = c.getMethods
//    println("======="+c.getName)
//    c.getMethods.foreach(x=>println(x.getName))
    for(i<- 0 until methods.size){

      breakable( {
        val name = methods(i).getName
        if (!name.startsWith("set")) {
          break()
        }
        var name1:String = name.substring(3)
        name1 = name1.substring(0,1).toLowerCase()+name1.substring(1)
        mapmethod.put(name1,methods(i))
      })
    }
    mapmethod
  }

  def parseRstStruc(resultSetMetaData: ResultSetMetaData): Array[String] ={
    val count = resultSetMetaData.getColumnCount
    var array:Array[String] = new Array[String](count)
  //  var strings = ListBuffer.empty[String]
    for(i<- 0 until count){
      array(i) = resultSetMetaData.getColumnLabel(i+1)
    }
    array
  }

  def resetToListReflect[T](sql:String,params:Array[String], c: Class[T]):ListBuffer[T] ={
    val rs = query(sql,params)
    var lst:ListBuffer[T] = ListBuffer.empty[T]
    val toMapMethods = parseMethod(c)
    val strings = parseRstStruc(rs.getMetaData)
    while (rs.next()) {
      //    do {
      var t: T = c.newInstance()
      //     lst.append(Userinfos(rs.getInt("userid"),rs.getString("username"),rs.getString("birthday")))
      for (i <- 0 until strings.length) {
                breakable({
                  if (!toMapMethods.containsKey(strings(i))) {
                    break()
                  }
//                  val method = toMapMethods.get(strings(i)).getName
//                  val value = rs.getObject(strings(i))
//                  println(method+"\t"+value)
                  toMapMethods.get(strings(i)).invoke(t, rs.getObject(strings(i)))
                })
      }
      lst.append(t)
      //  }while (rs.next())
    }
    lst
    }



  def main(args: Array[String]): Unit = {
   // println(resetToList("select * from userinfos",Array()))
    println(resetToListReflect("select * from userinfos",Array(),(new UseInfos).getClass))
  }

}

 

posted @ 2020-09-19 12:58  PEAR2020  阅读(129)  评论(0编辑  收藏  举报