2 m0 37365614 m0_37365614 于 2018.02.12 16:33 提问

关于hibernate循环添加的问题多对多关系。。。

现在有question表,paper表paper_question表,hibernate查询出question表和paper表
的ID,循环插入到paper_question表中,请问各位大神该怎么做,希望可以写出代码

1个回答

u013221181
u013221181   2018.02.12 20:42
已采纳
@Entity
data class Question(
        @Id
        @GeneratedValue
    var id: Long? = null
)
interface QuestionRepository: CrudRepository<Question, Long>

@Entity
data class Paper(
        @Id
        @GeneratedValue
    var id: Long? = null
)
interface PaperRepository: CrudRepository<Paper, Long>

@Entity
data class PaperQuestion(
    @Id
    @GeneratedValue
    var id: Long? = null,
    @ManyToOne
    @JoinColumn(name="paper_id")
    val paper: Paper,
    @ManyToOne
    @JoinColumn(name = "question_id")
    val question: Question
)
interface PaperQuestionRepository: CrudRepository<PaperQuestion, Long>

@Service
class TestService(
    val paperQuestionRepository:PaperQuestionRepository,
    val paperRepository:PaperRepository,
    val questionRepository: QuestionRepository
){
    fun test(){
        val papers = paperQuestionRepository.findAll()
        val questions = paperQuestionRepository.findAll()
        val paperQuestions = mutableListOf<PaperQuestion>()
        papers.forEach{ paper ->
            questions.forEach{ question ->
                paperQuestions.add(PaperQuestion(paper=paper,question=question))
            }
        }
        paperQuestionRepository.save(paperQuestions)
    }
}

@SpringBootApplication
class Application

fun main(args: Array<String>){
    SpringApplication.run(Application::class.java, *args)
}

用的springboot 和jpa规范,spring-data-jpa作为dao层实现,然后语言是和java差不多的kotlin,只是为了写起来简单点,少写些public getter/setter什么的,
用java写逻辑也是那样,hibernate作为jpa的实现,也是可以直接使用jpa的规范的

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!