mybatis中实现枚举自动转换方法详解

2025-05-29 0 97

前言

最近在工作中遇到一个问题,在设计数据库的时候,我们有时候会把表里的某个字段的值设置为数字或者为英文来表示他的一些特殊含义。就拿设置成数字来说,假如1对应是学生,2对应是教师,在java里面定义成这样的枚举,但是一般使用mybatis查出来的话,我们想要让它自动装换成我们想要的枚举,不需要再手动根据数值去判断设置成我们想要的枚举。要是实现这样的效果,那么我们就要用到mybatis的basetypehandler了。

basetypehandler介绍

让我们来看看要继承basetypehandler这个抽象类,需要覆写哪些方法:

?

1
2

3

4

5

6

7
public abstract void setnonnullparameter(preparedstatement ps, int i, t parameter, jdbctype jdbctype) throws sqlexception;

public abstract t getnullableresult(resultset rs, string columnname) throws sqlexception;

public abstract t getnullableresult(resultset rs, int columnindex) throws sqlexception;

public abstract t getnullableresult(callablestatement cs, int columnindex) throws sqlexception;

实现了这些抽象类,当得到结果集的时候,程序就会回调这些方法,例如根据名称获取当前行的某一列的值,那么就会直接回调getnullableresult(resultset rs, string columnname)这个方法,根据名称得到当行的当前列的值,然后我们在这里去调用枚举,匹配枚举中的每一个值,相等的话直接返回该枚举,达到自动转换成我们想要的枚举的效果。其他的重载方法类似,只不过是有些根据列索引,有些根据列名称做枚举自动转换而已。

好了,介绍就到这里,让我们来看看具体实现。。

自动转换实现例子

创建数据库表

mybatis中实现枚举自动转换方法详解

创建枚举

?

1
2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44
package net.itaem.less;

import java.util.hashmap;

import java.util.map;

/**

* @author: fighter168

*/

public enum persontype{

student("1","学生"),

teacher("2","教师");

private string value;

private string displayname;

static map<string,persontype> enummap=new hashmap<string, persontype>();

static{

for(persontype type:persontype.values()){

enummap.put(type.getvalue(), type);

}

}

private persontype(string value,string displayname) {

this.value=value;

this.displayname=displayname;

}

public string getvalue() {

return value;

}

public void setvalue(string value) {

this.value = value;

}

public string getdisplayname() {

return displayname;

}

public void setdisplayname(string displayname) {

this.displayname = displayname;

}

public static persontype getenum(string value) {

return enummap.get(value);

}

}

创建po实体类

?

1
2

3

4

5

6

7

8

9

10
/**

* @author: fighter168

*/

public class person {

private string id;

private string name;

//枚举

private persontype persontype;

//set get 方法。。

}

创建dao接口

创建一个简单的测试dao,这里简单的提供一个测试的查询方法。

?

1
2

3

4

5

6

7

8
/**

* @author: fighter168

*/

public interface persondao {

public list<person> query();

}

创建枚举转换处理器

?

1
2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80
package net.itaem.handler;

import java.sql.callablestatement;

import java.sql.preparedstatement;

import java.sql.resultset;

import java.sql.sqlexception;

import net.itaem.less.persontype;

import org.apache.ibatis.type.basetypehandler;

import org.apache.ibatis.type.jdbctype;

/**

* @author: fighter168

*/

public class persontypehandler extends basetypehandler<persontype>{

private class<persontype> type;

private persontype[] enums;

/**

* 设置配置文件设置的转换类以及枚举类内容,供其他方法更便捷高效的实现

* @param type 配置文件中设置的转换类

*/

public persontypehandler(class<persontype> 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 persontype getnullableresult(resultset rs, string columnname) throws sqlexception {

// 根据数据库存储类型决定获取类型,本例子中数据库中存放string类型

string i = rs.getstring(columnname);

if (rs.wasnull()) {

return null;

} else {

// 根据数据库中的value值,定位persontype子类

return persontype.getenum(i);

}

}

@override

public persontype getnullableresult(resultset rs, int columnindex) throws sqlexception {

// 根据数据库存储类型决定获取类型,本例子中数据库中存放string类型

string i = rs.getstring(columnindex);

if (rs.wasnull()) {

return null;

} else {

// 根据数据库中的value值,定位persontype子类

return persontype.getenum(i);

}

}

@override

public persontype getnullableresult(callablestatement cs, int columnindex) throws sqlexception {

// 根据数据库存储类型决定获取类型,本例子中数据库中存放string类型

string i = cs.getstring(columnindex);

if (cs.wasnull()) {

return null;

} else {

// 根据数据库中的value值,定位persontype子类

return persontype.getenum(i);

}

}

@override

public void setnonnullparameter(preparedstatement ps, int i, persontype parameter, jdbctype jdbctype)

throws sqlexception {

// basetypehandler已经帮我们做了parameter的null判断

ps.setstring(i, parameter.getvalue());

}

}

创建mapper映射文件

persondao对应的personmapper映射文件

?

1
2

3

4

5

6

7

8

9

10

11

12

13

14

15
<?xml version="1.0" encoding="utf-8" ?>

<!doctype mapper public "-//mybatis.org//dtd mapper 3.0//en" "http://www.mybatis.org/dtd/mybatis-3-mapper.dtd" >

<mapper namespace="net.itaem.dao.persondao" >

<resultmap id="resultmap" type="net.itaem.po.person" >

<result column="id" property="id" jdbctype="char" />

<result column="name" property="name" jdbctype="char" />

<result column="type" property="persontype" jdbctype="char" />

</resultmap>

<select id="query" resultmap="resultmap">

select * from person

</select>

</mapper>

其实handler还可以写在personmapper.xml这里,写成下面这样:

?

1
<result column="type" property="persontype" typehandler="net.itaem.handler.persontypehandler"/>

创建spring的配置文件

?

1
2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32
<?xml version="1.0" encoding="utf-8"?>

<beans xmlns="http://www.springframework.org/schema/beans"

xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"

xsi:schemalocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean id="datasource" class="org.apache.commons.dbcp.basicdatasource" destroy-method="close">

<property name="driverclassname" value="com.mysql.jdbc.driver"/>

<property name="url" value="jdbc:mysql://localhost:3306/test"/>

<property name="username" value="root"/>

<property name="password" value="123abc"/>

<!-- 连接池启动时候的初始连接数 -->

<property name="initialsize" value="10"/>

<!-- 最小空闲值 -->

<property name="minidle" value="5"/>

<!-- 最大空闲值 -->

<property name="maxidle" value="20"/>

<property name="maxwait" value="2000"/>

<!-- 连接池最大值 -->

<property name="maxactive" value="50"/>

<property name="logabandoned" value="true"/>

<property name="removeabandoned" value="true"/>

<property name="removeabandonedtimeout" value="180"/>

</bean>

<bean id="sqlsessionfactory" class="org.mybatis.spring.sqlsessionfactorybean">

<property name="configlocation" value="classpath:/resource/cfg.xml"/>

<property name="datasource" ref="datasource"/>

</bean>

<bean class="org.mybatis.spring.mapper.mapperscannerconfigurer">

<property name="basepackage" value="net.itaem.dao"/>

</bean>

</beans>

创建mybatis的配置文件

下面是为mybatis创建配置文件cfg.xml

?

1
2

3

4

5

6

7

8

9

10

11

12

13

14
<?xml version="1.0" encoding="utf-8" ?>

<!doctype configuration

public "-//mybatis.org//dtd config 3.0//en"

"http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>

<typehandlers>

<typehandler handler="net.itaem.handler.persontypehandler"

javatype="net.itaem.less.persontype" jdbctype="char"/>

</typehandlers>

<!-- mapping 文件路径配置 -->

<mappers>

<mapper resource="resource/personmapper.xml" />

</mappers>

</configuration>

创建测试用例

?

1
2

3

4

5

6

7

8

9

10

11

12

13

14
/**

* @author: fighter168

*/

public class springtest {

public static void main(string[] args) {

applicationcontext context=new classpathxmlapplicationcontext("resource/applicationcontext.xml");

persondao persondao=(persondao) context.getbean("persondao");

list<person> list=persondao.query();

for(person p:list){

system.out.println(p.tostring());

}

}

}

测试结果展示

结果是成功自动转换成了我们想要的枚举

mybatis中实现枚举自动转换方法详解

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作能带来一定的帮助,如果有疑问大家可以留言交流,谢谢大家对快网idc的支持。

原文链接:http://blog.csdn.net/fighterandknight/article/details/51520402

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 mybatis中实现枚举自动转换方法详解 https://www.kuaiidc.com/115402.html

相关文章

发表评论
暂无评论