1. 程式人生 > >ORM框架三種映射在Springboot上的使用

ORM框架三種映射在Springboot上的使用

mar enc util 添加 進行 oci lis new 所有

ORM(對象/關系映射)是數據庫層非常重要的一部分,有三種常用的映射關系

1.多對一

tbl_clazz

clazz{
id
name
description
grade_id
charge_id
}

clazz {
id
name
description
grade:{
id:
name:
...
},
charge:{
id
name
gender
}
}

提供多對一的查詢 -------班級表對應年級表和班主任表

bean
extend
ClazzVM.java


dao
extend
ClazzVMMapper.java(接口)

mapper
extend
ClazzVMMapper.xml

ClazzVMMapper主要實現sql語句,是非常重要的一部分,關鍵代碼如下

<select id="selectByPrimaryKey" parameterType="long" resultMap="ClazzVMMapper">
        select * from poll_clazz
        where id=#{id}
    </select>
<resultMap type="com.briup.apps.poll.bean.extend.ClazzVM
" id="ClazzVMMapper"> <id column="id" property="id"/> <result column="name" property="name"/> <result column="description" property="description"/> <association column="grade_id" property="grade" select="com.briup.apps.poll.dao.GradeMapper.selectByPrimaryKey
"> </association> <association column="charge_id" property="charge" select="com.briup.apps.poll.dao.UserMapper.selectByPrimaryKey"> </association> </resultMap>


2.一對多

一對多 查詢 ------一個問題包括多個問題選項

查找所有問題,包括問題選項

bean:

package com.briup.apps.poll.bean.extend;

import java.util.List;

import com.briup.apps.poll.bean.Options;

public class QuestionVM {
    
    private Long id;
    private String name;
    private String questionType;
    
    private List<Options> options;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getQuestionType() {
        return questionType;
    }

    public void setQuestionType(String questionType) {
        this.questionType = questionType;
    }

    public List<Options> getOptions() {
        return options;
    }

    public void setOptions(List<Options> options) {
        this.options = options;
    }
    
}

dao:

public interface QuestionVMMapper {
List<QuestionVM> selectAll() throws Exception;

List<QuestionVM> selectByQuestionnaireId(long id) throws Exception;
}

QuestionVMMapper.xml(對應實現dao層的selectAll功能)

<mapper namespace="com.briup.apps.poll.dao.extend.QuestionVMMapper">
     <select id="selectAll" resultMap="QuestionVMResultMap">
        select * from poll_question
        <!-- id,name,questionType -->
     </select>
 <resultMap type="com.briup.apps.poll.bean.extend.QuestionVM" id="QuestionVMResultMap">
         <id column="id" property="id"/>
         <result column="name" property="name" />
         <result column="questionType" property="questionType"/>
         <collection
            column="id"
            property="options"
            javaType="ArrayList"
             ofType="com.briup.apps.poll.bean.Options"
            select="selectOptionsByQuestionId">
          </collection>
       </resultMap>
            <!-- 通過題目id查詢問題選項 -->
        <select id="selectOptionsByQuestionId" 
            resultType="com.briup.apps.poll.bean.Options"
            parameterType="long">
            select * from poll_options where question_id = #{id}
        </select>
    
</mapper>

service層:

接口

package com.briup.apps.poll.service;

import java.util.List;

import com.briup.apps.poll.bean.Question;
import com.briup.apps.poll.bean.extend.QuestionVM;

public interface IQuestionService {
    //查找所有問題,並查找出問題的所有選項
     List<QuestionVM> findAll() throws Exception; 
     
     //更新或者保存問題,並保存更新問題選項
     void saveOrUpdateQuestionVM(QuestionVM questionVM) throws Exception;
     
     //刪除問題,級聯刪除選項
     void deleteById(long id) throws Exception;
     
     //關鍵字查詢
    List<Question> query(String keywords) throws Exception;
    
    //批量刪除題目
    
    void deleteBach(Long[] id)throws Exception;
}

接口實現層

package com.briup.apps.poll.service.Impl;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.briup.apps.poll.bean.Options;
import com.briup.apps.poll.bean.OptionsExample;
import com.briup.apps.poll.bean.Question;
import com.briup.apps.poll.bean.QuestionExample;
import com.briup.apps.poll.bean.extend.QuestionVM;
import com.briup.apps.poll.dao.OptionsMapper;
import com.briup.apps.poll.dao.QuestionMapper;
import com.briup.apps.poll.dao.extend.QuestionVMMapper;
import com.briup.apps.poll.service.IQuestionService;


@Service
public class QuestionServiceImpl implements IQuestionService {
    @Autowired
    private QuestionVMMapper questionVMMapper;
    @Autowired
    private OptionsMapper optionsMapper;
    @Autowired
    private QuestionMapper questionMapper;
    @Override
    public List<QuestionVM> findAll() throws Exception {
        
        return questionVMMapper.selectAll();
    }
    /*
     * 保存或者修改問題,帶選項
     */
    @Override
    public void saveOrUpdateQuestionVM(QuestionVM questionVM) throws Exception {
       /*
        * 1.得到question和options實體,因為保存是分別保存的
        * 2.判斷是否是保存還是修改操作
        * 3.判斷題目類型(簡答還是選擇)
        *     
        */
        
        Question question=new Question();
        question.setId(questionVM.getId());
        question.setName(questionVM.getName());
        question.setQuestiontype(questionVM.getQuestionType());
        List<Options> options=questionVM.getOptions();
              if(questionVM.getId()==null){
            /*保存操作
             * 1.保存題目
             * 2.保存選型
             */
                      if(questionVM.getQuestionType().equals("簡答題")){
                          //僅僅保存題目
                          questionMapper.insert(question);
                      }else{
                         //先保存題目
                          questionMapper.insert(question);
                          //獲取question的id
                          long id=question.getId();                    
                         //保存選項
                        for(Options option : options){
                            //遍歷所有選項,進行保存
                            option.setQuestionId(id);
                            optionsMapper.insert(option);
                        }
                      }
                  
                  }else{
                      //修改
                      /*
                       * 1.修改題目信息
                       * 2.刪除選項
                       * 3.重新添加選項
                       */
                      questionMapper.updateByPrimaryKey(question);
                      
                      OptionsExample example=new OptionsExample();
                      example.createCriteria().andQuestionIdEqualTo(question.getId());
                      optionsMapper.deleteByExample(example);
                      long id=question.getId();  
                      for(Options option : options){
                        //遍歷所有選項,進行保存
                        option.setQuestionId(id);
                        optionsMapper.insert(option);
                    }
                      
             }   
        
    }
    @Override
    public void deleteById(long id) throws Exception {
        
        questionMapper.deleteByPrimaryKey(id);
    }
    @Override
    public List<Question> query(String keywords) throws Exception {
        
            QuestionExample example=new QuestionExample();
            example.createCriteria().andNameLike(keywords);
            return  questionMapper.selectByExample(example);
        }
    @Override
    public void deleteBach(Long[] ids) throws Exception {
        for(long id : ids){
            questionMapper.deleteByPrimaryKey(id);
        }
        
    }    
    
}

Controll層

package com.briup.apps.poll.web.controller;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.briup.apps.poll.bean.Question;
import com.briup.apps.poll.bean.extend.QuestionVM;
import com.briup.apps.poll.service.IQuestionService;
import com.briup.apps.poll.util.MsgResponse;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Api(description="問題模塊接口")
@RestController
@RequestMapping("/question")
public class QuestionController {
@Autowired
private IQuestionService questionService;

@ApiOperation(value="刪除問題",notes="同時級聯刪除options")
@GetMapping("deleteQuestionById")
public MsgResponse deleteQuestionQuestionById(long id){
try{
questionService.deleteById(id);
return MsgResponse.success("刪除成功", null);
}catch(Exception e){
return MsgResponse.error(e.getMessage());
}
}

@ApiOperation(value="保存或者更新問題",notes="如果id為空,執行保存操作,如果id不為空,執行更新操作")
@PostMapping("saveOrUpdateQuestion")
public MsgResponse saveOrUpdateQuestion(QuestionVM questionVM){
try {
questionService.saveOrUpdateQuestionVM(questionVM);
return MsgResponse.success("success", null);
} catch (Exception e) {

e.printStackTrace();
return MsgResponse.error(e.getMessage());

}

}

@ApiOperation(value="查找所有問題",notes="並查找出所有問題的選項")
@GetMapping("findAllQuestion")
public MsgResponse findAllQuestion(){
try{
List<QuestionVM> list=questionService.findAll();
return MsgResponse.success("success", list);
}catch(Exception e){
e.printStackTrace();
return MsgResponse.error(e.getMessage());
}
}

@ApiOperation(value="批量刪除問題",notes="輸入問題id")
@GetMapping("deleteBatch")
public MsgResponse deleteBatch(Long[] ids){
try{
questionService.deleteBach(ids);
return MsgResponse.success("success", null);
}catch(Exception e){
e.printStackTrace();
return MsgResponse.error(e.getMessage());
}
}

@ApiOperation(value="關鍵字查詢",notes="輸入題目的關鍵字")
@GetMapping("findByQuery")
public MsgResponse findByQuery(String keywords){
try{
List<Question> list=questionService.query(keywords);
return MsgResponse.success("success", list);
}catch(Exception e){
e.printStackTrace();
return MsgResponse.error(e.getMessage());
}
}
}

3.多對多

問卷模塊
1. 查詢所有問卷/通過關鍵字查詢問卷(單表)
2. 預覽問卷、課調
通過問卷id查詢問卷下所有信息(問卷,問題,選項)
2.1 數據庫級別表示多對多
問卷 questionnaire
id name
1 主講問卷
2 輔講問卷

問題 question
id name
1 授課質量
2 技術水平
3 親和力

qq
id questionnaire_id question_id
1 1 1
2 1 2
3 1 3
4 2 1
5 2 3

# 通過問卷id查找問卷信息
select * from poll_questionnaire where id =1;
// id name description
# 通過問卷id查找屬於問卷的問題信息
select * from poll_question where id in (
select question_id
from poll_qq
where questionnaire_id = 1;
);

2.2 面向對象級別上多對多
QuestionnaireVM{

private Long id;
private String name;
private List<Question> questions;
}

QuestionVM{
private Long id
private String name;
private List<Questionnaire> questionnaires;
}

bean層:

package com.briup.apps.poll.bean.extend;

import java.util.List;

public class QuestionnaireVM {
     private Long id;
     private String name;
     private String description;
     
     private List<QuestionVM> questionVMs;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public List<QuestionVM> getQuestionVMs() {
        return questionVMs;
    }

    public void setQuestionVMs(List<QuestionVM> questionVMs) {
        this.questionVMs = questionVMs;
    }

    
     
}

dao層:

package com.briup.apps.poll.dao.extend;

import java.util.List;

import com.briup.apps.poll.bean.extend.QuestionnaireVM;

public interface QuestionnaireVMMapper {
       List<QuestionnaireVM> selectById(long id);
}

QuestionnaireVM.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.briup.apps.poll.dao.extend.QuestionnaireVMMapper">
     <select id="selectById" resultMap="QuestionnaireVMResultMap">
        select * from poll_questionnaire where id = #{id}
        <!-- id,name,description -->
     </select>
     
     <!-- 定義結果集 -->
     <resultMap type="com.briup.apps.poll.bean.extend.QuestionnaireVM" id="QuestionnaireVMResultMap">
         <id column="id" property="id"/>
         <result column="name" property="name" />
         <result column="description" property="description"/>
         <collection
            column="id"
            property="questionVMs"
            javaType="ArrayList"
             ofType="com.briup.apps.poll.bean.extend.QuestionVM"
            select="com.briup.apps.poll.dao.extend.QuestionVMMapper.selectByQuestionnaireId">
          </collection>
       </resultMap>
           
          
    
</mapper>
  <select id="selectByQuestionnaireId" parameterType="long" resultMap="QuestionVMResultMap">
       select * from poll_question where id in(
       select question_id from poll_qq where questionnaire_id = #{id}
       )
        <!-- id,name,questionType -->
     </select>

根據問卷id查找所有該問卷的問題,在QuestionVMMapper.java中聲名了一個根據問卷id查找所有問題的方法

該方法在QuestionVMMapper.xml中對應的代碼為:

<select id="selectByQuestionnaireId" parameterType="long" resultMap="QuestionVMResultMap">
       select * from poll_question where id in(
       select question_id from poll_qq where questionnaire_id = #{id}
       )
        <!-- id,name,questionType -->
     </select>

service層

接口

package com.briup.apps.poll.service;

import java.util.List;

import com.briup.apps.poll.bean.Questionnaire;
import com.briup.apps.poll.bean.extend.QuestionnaireVM;

public interface IQuestionnaireVMService {
    //查詢所有問卷
   List<Questionnaire> findAll();
   
   //查詢所有問卷及問卷的問題
   List<QuestionnaireVM> findQuestionById(long id);
   
   
}

實現

package com.briup.apps.poll.service.Impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.briup.apps.poll.bean.Questionnaire;
import com.briup.apps.poll.bean.QuestionnaireExample;
import com.briup.apps.poll.bean.extend.QuestionnaireVM;
import com.briup.apps.poll.dao.QuestionnaireMapper;
import com.briup.apps.poll.dao.extend.QuestionnaireVMMapper;
import com.briup.apps.poll.service.IQuestionnaireVMService;
@Service
public class QuestionnaireVMServiceImpl implements IQuestionnaireVMService{
@Autowired
private QuestionnaireMapper questionnaireMapper;

@Autowired
private QuestionnaireVMMapper questionnaireVMMapper;

    @Override
    public List<Questionnaire> findAll() {
        QuestionnaireExample example=new QuestionnaireExample();
        return questionnaireMapper.selectByExampleWithBLOBs(example);
        
    }

    @Override
    public List<QuestionnaireVM> findQuestionById(long id) {
        return questionnaireVMMapper.selectById(id);    
    }

}

controll層

package com.briup.apps.poll.web.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.briup.apps.poll.bean.Questionnaire;
import com.briup.apps.poll.bean.extend.QuestionnaireVM;
import com.briup.apps.poll.service.IQuestionnaireVMService;
import com.briup.apps.poll.util.MsgResponse;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Api(description="問卷模塊接口")
@RestController
@RequestMapping("/questionnaire")
public class QuestionnaireVMController {
@Autowired
private IQuestionnaireVMService qnvs;

@ApiOperation(value="查找所有問卷",notes="僅僅只查找問卷")
@PostMapping("findAllQuestionnaire")

public MsgResponse findAllQuestionnaire(){
         try{
             List<Questionnaire> list=qnvs.findAll();
            return MsgResponse.success("success", list);
         }catch(Exception e){
             e.printStackTrace();
             return MsgResponse.error(e.getMessage());
         }
}

@ApiOperation(value="預覽問卷信息",notes="預覽包括問卷上的問題")
@GetMapping("findAllQuestionnaireById")
public MsgResponse findAllQuestionnaireById(long id){
    try{
        List<QuestionnaireVM> list=qnvs.findQuestionById(id);
        return MsgResponse.success("success", list);
    }catch(Exception e){
        e.printStackTrace();
        return MsgResponse.error(e.getMessage());
    }
}
}

ORM框架三種映射在Springboot上的使用