2017-02-16 4 views
2

기본적으로 Slick은 O.AutoInc 플래그가있는 열의 값을 무시하고 데이터베이스가 삽입 작업 중에 해당 값을 채울 수 있도록합니다.Slick에서 AutoInc 열의 값을 명시 적으로 지정하는 방법

가끔은 자동 증가 열에 대한 특정 값을 삽입해야하지만 Slick은 여전히이를 무시합니다. 그것을 할 방법이 있습니까?

나는 두 번째 테이블 정의를 만들 수 있습니다. O.AutoInc 플래그가 없지만보다 우아한 방법을 찾고 있습니다.

업데이트

: 당신이 Option 알로 id 필드를 표시하면

case class Transaction (id: Long, timestamp: LocalDateTime, comment: Option[String]) 
class Transactions(tag: Tag) extends Table[Transaction](tag, "tx") { 
    implicit val localDTtoDate = MappedColumnType.base[LocalDateTime, Timestamp] (
    l => Timestamp.valueOf(l), 
    d => d.toLocalDateTime 
) 

    def id = column[Long]("id", O.PrimaryKey, O.AutoInc) 
    def timestamp = column[LocalDateTime]("ts") 
    def comment = column[Option[String]]("comment") 
    def * = (id, timestamp, comment) <> ((Transaction.apply _).tupled, Transaction.unapply) 
} 
+0

당신은이 작업을 수행 할 수는'*'-projection이 ID를 사용 기둥. 테이블 정의를 복사하여 붙여 넣을 수 있습니까? – jkinkead

+0

@jkinkead 예! – akashihi

답변

0

것은, 당신이 당신의 * 투사에 약간의 조정으로 삽입 할 수 있어야한다 :

여기 내 사건 클래스와 테이블 정의입니다
case class Transaction (id: Option[Long], timestamp: LocalDateTime, 
    comment: Option[String]) 
class Transactions(tag: Tag) extends Table[Transaction](tag, "tx") { 
    // Use the ? method on your id column to map it to an option. 
    def * = (id.?, timestamp, comment) <> (
    (Transaction.apply _).tupled, Transaction.unapply) 
} 

이렇게하면 id=None으로 삽입하는 행은 인 행이로 설정되는 동안 새로운 id을 생성합니다.. 삽입 된 ID를 다시 읽으려면 returning ... into를 사용 매우 유사한 문제로 어려움을 겪고있는 동안

// `tx` is a Transaction instance, `transactions` is a 
// TableQuery[Transactions] instance. 
(transactions.returning(transactions.map(_.id)).into { (_, id) => 
    tx.copy(id = id) 
}) += tx 
+0

불행히도, id : Option [Long] 값은 Some (value)와 None을 사용하여 여전히 자동 생성됩니다. – akashihi

+0

어떻게 행을 삽입합니까? 어떤 데이터베이스를 사용하고 있습니까? 이것은 Slick 3. {0,1} 및 PostgreSQL에서 작동합니다. – jkinkead

+0

삽입 코드는 이해의 일부이며, 관련 부분은 다음과 같습니다. transactions.map (_. id) + = tx 데이터베이스를 반환하는 트랜잭션은 PostgreSQL – akashihi

0

나는이 질문을 발견했다. 슬프게도 제안 된 솔루션을 작동시킬 수 없습니다.

우리는 O.AutoInc 가자로 결정하지만, 그 순서

Column | Type |     Modifiers 
----------+--------+---------------------------------------------- 
id  | bigint | not null default nextval('id_seq'::regclass) 
다음

가 될 필요로 할 때 우리가 삽입시 ID를 생략의 nextval로 순서 및 컬럼의 디폴트 값을 유지 자동으로 생성됩니다. 문서의 관련 부분에

링크 :이 정확한 경우 http://slick.lightbend.com/doc/3.1.0/queries.html#inserting

그것은 다음과 같이 보일 것입니다 : 경우

if (you have an explicit id) transactions += tx 
else transactions.map(t => (t.timestamp, t.comment)) += (tx.timestamp, tx.comment)