MybatisでJava列挙タイプを使用する

11678 ワード

列挙集合JSONを返す
列挙の定義
package com.test.model;

import java.util.HashMap;
import java.util.Map;

public enum StyleEnum {
	
	A2("AA"),A3("AAA"),A4("AAAA"),A5("AAAAA");

	private String name = null;
	
	StyleEnum(String name)
	{
		this.name = name;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}
	
	public static Map enum2Json(StyleEnum se)
	{
		Map map = new HashMap();
		map.put("id",se.toString());//A2,A3,A4,A5
		map.put("name",se.getName());
		return map;
	}
}


Controllerは列挙JSONを返す
	@RequestMapping("/loadstyle")
	@ResponseBody
	public List getStyle()
	{
		List rtn = new ArrayList();
		rtn.add(StyleEnum.enum2Json(StyleEnum.A2));
		rtn.add(StyleEnum.enum2Json(StyleEnum.A3));
		rtn.add(StyleEnum.enum2Json(StyleEnum.A4));
		rtn.add(StyleEnum.enum2Json(StyleEnum.A5));
		return rtn;
	}

Mybatis操作への参加を列挙
エンティティークラスの定義
package com.test.model;

import java.sql.Timestamp;

import com.fasterxml.jackson.annotation.JsonFormat;

import java.io.Serializable;
import java.sql.Date;

public class StudentInfo implements Serializable{
	private Integer id = null;
	private String name = null;
	private Integer age = null;
	private String province = null;
	private String city = null;
	private String county = null;
	@JsonFormat(pattern="yyyy-MM-dd",timezone = "GMT+8")
	private Date dt = null;
	@JsonFormat(pattern="yyyy-MM-dd HH:mm:ss",timezone = "GMT+8")
	private Timestamp ts = null;
	private String provinceName = null;
	private String cityName = null;
	private String countyName = null;
	private String[] cids = null;
	private StyleEnum style = null;
	private String styleString = null;
	
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public Integer getAge() {
		return age;
	}
	public void setAge(Integer age) {
		this.age = age;
	}
	public String getProvince() {
		return province;
	}
	public void setProvince(String province) {
		this.province = province;
	}
	public String getCity() {
		return city;
	}
	public void setCity(String city) {
		this.city = city;
	}
	public String getCounty() {
		return county;
	}
	public void setCounty(String county) {
		this.county = county;
	}	
	public Date getDt() {
		return dt;
	}
	public void setDt(Date dt) {
		this.dt = dt;
	}
	public Timestamp getTs() {
		return ts;
	}
	public void setTs(Timestamp ts) {
		this.ts = ts;
	}
	public String getProvinceName() {
		return provinceName;
	}
	public void setProvinceName(String provinceName) {
		this.provinceName = provinceName;
	}
	public String getCityName() {
		return cityName;
	}
	public void setCityName(String cityName) {
		this.cityName = cityName;
	}
	public String getCountyName() {
		return countyName;
	}
	public void setCountyName(String countyName) {
		this.countyName = countyName;
	}
	public String[] getCids() {
		return cids;
	}
	public void setCids(String[] cids) {
		this.cids = cids;
	}
	public StyleEnum getStyle() {
		return style;
	}
	public void setStyle(StyleEnum style) {
		this.style = style;
	}
	public String getStyleString() {
		return styleString;
	}
	public void setStyleString(String styleString) {
		this.styleString = styleString;
	}
	public String toString()
	{
		return "StudentInfo[name="+name+",age="+age+",province="+province+",city="+city+",county="+county+",style="+style+",styleString="+styleString+"]";
	}
}


列挙変換器の定義
package com.test.model;

import java.sql.CallableStatement; 
import java.sql.PreparedStatement; 
import java.sql.ResultSet; 
import java.sql.SQLException; 
  
  
import org.apache.ibatis.type.BaseTypeHandler; 
import org.apache.ibatis.type.JdbcType; 
  
public class StyleHandler extends BaseTypeHandler{ 
	private Class type; 
	  
	private StyleEnum[] enums; 
	  
	/** 
	*                    ,              
	* @param type             
	*/
	public StyleHandler(Class type) { 
		if (type == null) 
			throw new IllegalArgumentException("Type argument cannot be null"); 
		this.type = type; 
		this.enums = type.getEnumConstants(); 
		if (this.enums == null) 
			throw new IllegalArgumentException(type.getSimpleName() 
			+ " does not represent an enum type."); 
	} 
	  
	@Override
	public StyleEnum getNullableResult(ResultSet rs, String columnName) throws SQLException { 
		//                ,          String   
		String str = rs.getString(columnName); 
		if (rs.wasNull()) { 
			return null; 
		} else { 
			//        value ,  PersonType   
			return StyleEnum.valueOf(str); 
		} 
	} 
	  
	@Override
	public StyleEnum getNullableResult(ResultSet rs, int columnIndex) throws SQLException { 
		//                ,          String   
		String str = rs.getString(columnIndex); 
		if (rs.wasNull()) { 
			return null; 
		} else { 
			//        value ,  PersonType   
			return StyleEnum.valueOf(str); 
		} 
	} 
	  
	@Override
	public StyleEnum getNullableResult(CallableStatement cs, int columnIndex) throws SQLException { 
		//                ,          String   
		String str = cs.getString(columnIndex); 
		if (cs.wasNull()) { 
			return null; 
		} else { 
			//        value ,  PersonType   
			return StyleEnum.valueOf(str); 
		} 
	} 
	  
	@Override
	public void setNonNullParameter(PreparedStatement ps, int i, StyleEnum parameter, JdbcType jdbcType) 
	throws SQLException { 
		// baseTypeHandler       parameter null   
		ps.setString(i, parameter.toString()); 
	}
}

Mybatisグローバルプロファイルによる変換器の設定
 
 
 
	 
		 
	 



SpringBootプロファイルMybatisグローバルプロファイルの設定
mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.config-locations=classpath:mybatis-cfg.xml

ElementUIVUEフロントエンドWebデザイン
  
    
      
      
    
  


  import axios from 'axios'

  export default {
    data() {
      return {
        courseList:[],//    
        provincelist:[],//      
        citylist:[],//            
        countylist:[],//            
        stylelist:[],//            
        student:{//             
          id:'',//  ID
          name:'',//    
          age:'12',//    
          province:'',//    
          city:'',//    
          county:'',//    
          dt:'',//  
          ts:'',//  ,
          cids:[1,2], //     ,
          style:''
        }
      }
    },
    mounted() {
        var id = this.$route.params.id;
        this.openbyid(id);
        this.doloadaddress();
        this.loadcourse();
        this.loadstyle();
    },
    methods: {
      onSubmit() {
        console.log('submit!');
        this.dosave();
      },
       //    
        loadcourse:function()
        {
            var _this = this;
            axios.get('http://localhost:6060/loadcourse')
            .then(function(result){
              //alert(result.data);
                _this.courseList=result.data;
            })
        },
       //      
        loadstyle:function()
        {
            var _this = this;
            axios.get('http://localhost:6060/loadstyle')
            .then(function(result){
              //alert(result.data);
                _this.stylelist=result.data;
            })
        },
        //    ID,      
        openbyid:function(id)
        {
            var _this = this;
            axios.get('http://localhost:6060/findstudbyid?id='+id)
            .then(function(result){
                _this.student=result.data;
                //  VUE  ,         
                _this.doloadaddress(_this.student.province,_this.student.city,
                        _this.student.county);
            })
        },
        dosave:function()
        {
            console.log('dosave...');
            var _this = this;
            // VUE  student     
            axios.post('http://localhost:6060/savestudent',_this.student)
                .then(function(result){
                    if(result.data)
                    {
                        alert('Successfully');
                        _this.$router.push('/list');
                    }
                    else
                        alert('Failure');
                })
        },
        selectprovince:function()//         
        {
            //    ,     Code
            this.doloadaddress(this.student.province);
        },
        selectcity:function()//         
        {
            //    ,    Code,  Code
            this.doloadaddress(this.student.province,this.student.city);
        },
        //            
        //province         
        //city         
        //county        
        doloadaddress:function(province,city,county)
        {
            console.log('doloadaddress...');
            //  _this  VUE  ,  axios this  
            var _this = this;
            //      
            axios.get('http://localhost:6060/getprovice')
                .then(function(result){
                    _this.provincelist = result.data;
                    if(province != '' && province != null)
                    {
                        console.log('province...'+province);
                        _this.student.province = province;
                    }
                    else
                    {
                        //         ,           
                        _this.student.province = result.data[0].code;
                    }
                    //    Code,      ,    ,            
                    return axios.get('http://localhost:6060/getcity?code='+_this.student.province);
                })
                .then(function(cityResult){
                    //        
                    _this.citylist = cityResult.data;
                    if(city != '' && city != null)
                    {
                        console.log('city...'+city);
                        _this.student.city = city;
                    }
                    else
                    {
                        //         ,           
                        _this.student.city = cityResult.data[0].code;
                    }
                    //    Code,      ,    ,            
                    return axios.get('http://localhost:6060/getcounty?code='+_this.student.city);
                })
                .then(function(countyResult){
                    //        
                    _this.countylist = countyResult.data;
                    console.log('county...'+countyResult.data);
                    if(county != '' && county != null)
                    {
                        console.log('county...'+county);
                        _this.student.county = county;
                    }
                    else
                    {
                        //         ,           
                        _this.student.county = countyResult.data[0].code;
                    }
                })
        }
    }
  }