[英]How to parameterize table name in Slick
class MyTable(tag: Tag) extends Table[MyEntity](tag, "1970Table") {
def id = column[Int]("id")
override def * =
(
id
) <> (MyEntity.tupled, MyEntity.unapply)
}
val myTable = TableQuery[MyTable]
class MyRepository(val config: DatabaseConfig[JdbcProfile])
extends MyRepository[MyTable, String] {
override val table: config.profile.api.TableQuery[MyTable] = myTable
def insert(me: MyEntity): Future[Int] = {
db.run(table += me)
}
}
I use this in my other classes like this:我在其他课程中使用它,如下所示:
val myRepository = new MyRepository(dbConfig)
myRepository.insert(myrecord)
Question题
I would like to not have a hardcoded tablename but rather make the tablename dynamic.我不想有硬编码的表名,而是让表名动态化。
I would like to change the insert
method such that it accepts a year (int)
parameter and based on the year parameter it chooses the right table.我想更改insert
方法,使其接受year (int)
参数并根据年份参数选择正确的表。 ie if the year passed in is 1970
then table name is 1970Table
but if the year passed in is 1980
then the table is 1980Table
.即如果传入的年份是1970
则表名是1970Table
但如果传入的年份是1980
则表是1980Table
。
Try尝试
class MyRepository(val config: DatabaseConfig[JdbcProfile]) {
import config._
import profile.api._
abstract class MyTable(tag: Tag, name: String) extends Table[MyEntity](tag, name) {
def id = column[Int]("id")
override def * = (id) <> (MyEntity.tupled, MyEntity.unapply)
}
class Table1970(tag: Tag) extends MyTable[MyEntity](tag, "1970Table")
class Table1980(tag: Tag) extends MyTable[MyEntity](tag, "1980Table")
val table1970 = TableQuery[Table1970]
val table1980 = TableQuery[Table1980]
def insert(me: MyEntity, year: Int): Future[Int] = db.run {
year match {
case "1970" => table1970 += me
case "1980" => table1980 += me
}
}
}
Now现在
val myRepository = new MyRepository(dbConfig)
myRepository.insert(myrecord, "1970")
There is two apply
methods in TableQuery. TableQuery 中有两种apply
方法。 val myTable = TableQuery[MyTable]
- val myTable = TableQuery[MyTable]
-
this one uses macros to create MyTable
.这个使用宏来创建MyTable
。 The other one is defined like this:另一个定义如下:
def apply[E <: AbstractTable[_]](cons: Tag => E): TableQuery[E] =
new TableQuery[E](cons)
So you can do smth like this所以你可以这样做
class MyTable(tag: Tag, tableName: String) extends Table[MyEntity](tag, tableName)
...
def myTable(name: String) = TableQuery[MyTable](tag => new MyTable(tag, name))
Now you can predefine all tables you need and use them or do smth like this现在你可以预定义你需要的所有表并使用它们或像这样做
class MyRepository(val config: DatabaseConfig[JdbcProfile])
extends MyRepository[MyTable, String] {
override def table(year: Int): config.profile.api.TableQuery[MyTable] = myTable(year.toString)
def insert(me: MyEntity, year: Int): Future[Int] = {
db.run(table(year) += me)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.