mysql高可用 持久层_MyBatis持久层框架使用总结 转载

MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis 。

2013年11月迁移到Github,MyBatis的Github地址:https://github.com/mybatis/mybatis-3。

iBATIS一词来源于“internet”和“abatis”的组合,是一个基于Java的持久层框架。iBATIS提供的持久层框架包括SQL Maps和Data Access Objects(DAO)。

MyBatis 是支持普通 SQL查询,存储过程和高级映射的优秀持久层框架。MyBatis 消除了几乎所有的JDBC代码和参数的手工设置以及结果集的检索。MyBatis 使用简单的 XML或注解用于配置和原始映射,将接口和 Java 的POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。

每个MyBatis应用程序主要都是使用SqlSessionFactory实例的,一个SqlSessionFactory实例可以通过SqlSessionFactoryBuilder获得。SqlSessionFactoryBuilder可以从一个xml配置文件或者一个预定义的配置类的实例获得。

1.使用Generator自动生成Dao层,Model层和Mapper层。

以下用mybatis-generator-core-1.3.2.jar插件加jdbc数据库连接包自动导出持久层dao包,model包和mapper包。

需要用到的Java包有:

mybatis-generator-core-1.3.2.jar,

mysql-connector-java-5.1.34.jar,

ojdbc14-10.2.0.1.0.jar,

sqljdbc4-4.0.jar。

配置文件: generator.xml

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

1 <?xml version="1.0" encoding="UTF-8"?>

2

3

4

5

6

9

10

11

12

13

14

15

16

17

20

21

22

25

26

27

42

43

44

45

48

49

54

55

56

57

58

59

60

61

62

66

67

68

72

73

74

75

76

77

81

82

86

87

91

92

96

97

101

102

106

107

111

112

116

117

121

122

123

134

135

136

137

138

139

140

155

156

157

158

159

160

161

162

163

164

165

166

167

168

179

180

181

182

183

184

215

216

217

218

219

220

View Code

打开cmd命令行,转到配置文件所在的文件下,执行如下生成语句:

java -jar mybatis-generator-core-1.3.2.jar -configfile generator.xml -overwrite

命令执行完毕,可以看到对应路径下生成dao包,model包和mapper包文件。

2.MyBatis框架整合

1)MyBatis使用参数配置:sqlMapConfig.xml。

① 缓存配置(Cache):cacheEnabled:全局开关:默认是true,如果它配成false,其余各个Mapper XML文件配成支持cache也没用。

② 延迟加载:

lazyLoadingEnabled:true使用延迟加载,false禁用延迟加载,默认为true,当禁用时, 所有关联对象都会即时加载。

aggressiveLazyLoading:true启用时,当延迟加载开启时访问对象中一个懒对象属性时,将完全加载这个对象的所有懒对象属性。false,当延迟加载时,按需加载对象属性(即访问对象中一个懒对象属性,不会加载对象中其他的懒对象属性)。默认为true。

③ multipleResultSetsEnabled:允许和不允许单条语句返回多个数据集(取决于驱动需求)。默认为true。

④ useColumnLabel:使用列标签代替列名称。不同的驱动器有不同的做法。参考一下驱动器文档,或者用这两个不同的选项进行测试一下。

⑤ useGeneratedKeys:允许JDBC生成主键。需要驱动器支持。如果设为了true,这个设置将强制使用被生成的主键,有一些驱动器不兼容不过仍然可以执行。

⑥ autoMappingBehavior:指定MyBatis 是否并且如何来自动映射数据表字段与对象的属性。PARTIAL将只自动映射简单的,没有嵌套的结果。FULL 将自动映射所有复杂的结果。

⑦ defaultExecutorType:配置和设定执行器,SIMPLE执行器执行其它语句。REUSE执行器可能重复使用prepared statements语句,BATCH执行器可以重复执行语句和批量更新。

⑧ defaultStatementTimeout:设置一个时限,以决定让驱动器等待数据库回应的多长时间为超时。

完整sqlMapConfig.xml配置文件如下:

48304ba5e6f9fe08f3fa1abda7d326ab.png

1 <?xml version="1.0" encoding="UTF-8" ?>

2 /p>

3 PUBLIC "-//mybatis.org//DTD Config 3.0//EN"

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

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

26

37

39

73

74

152

153

154

155

156

157

48304ba5e6f9fe08f3fa1abda7d326ab.png

序列化特殊值处理:SerializableTypeHandler

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

1 package com.ouc.openplatform.dao.mybatis;

2

3 import java.io.Serializable;

4 import java.sql.CallableStatement;

5 import java.sql.PreparedStatement;

6 import java.sql.ResultSet;

7 import java.sql.SQLException;

8

9 import org.apache.ibatis.type.BaseTypeHandler;

10 import org.apache.ibatis.type.JdbcType;

11

12 /**

13 * @author WuPing

14 */

15 public class SerializableTypeHandler extends BaseTypeHandler {

16

17 @Override

18 public void setNonNullParameter(PreparedStatement ps, int i, Serializable parameter, JdbcType jdbcType)

19 throws SQLException {

20 ps.setObject(i, parameter);

21 }

22

23 @Override

24 public Serializable getNullableResult(ResultSet rs, String columnName)

25 throws SQLException {

26 return (Serializable)rs.getObject(columnName);

27 }

28

29 @Override

30 public Serializable getNullableResult(ResultSet rs, int columnIndex)

31 throws SQLException {

32 return (Serializable)rs.getObject(columnIndex);

33 }

34

35 @Override

36 public Serializable getNullableResult(CallableStatement cs, int columnIndex)

37 throws SQLException {

38 return (Serializable)cs.getObject(columnIndex);

39 }

40

41 }

View Code

2)结果集resultMap:

MyBatis中在查询进行select映射的时候,返回类型可以用resultType,也可以用resultMap,resultType是直接表示返回类型的,而resultMap则是对外部ResultMap的引用,但是resultType跟resultMap不能同时存在。在MyBatis进行查询映射的时候,其实查询出来的每一个属性都是放在一个对应的Map里面的,其中键是属性名,值则是其对应的值。当提供的返回类型属性是resultType的时候,MyBatis会将Map里面的键值对取出赋给resultType所指定的对象对应的属性。所以其实MyBatis的每一个查询映射的返回类型都是ResultMap,只是当我们提供的返回类型属性是resultType的时候,MyBatis对自动的给我们把对应的值赋给resultType所指定对象的属性,而当我们提供的返回类型是resultMap的时候,因为Map不能很好表示领域模型,我们就需要自己再进一步的把它转化为对应的对象,这常常在复杂查询中很有作用。

示例:UserBaseResultMap

48304ba5e6f9fe08f3fa1abda7d326ab.png

48304ba5e6f9fe08f3fa1abda7d326ab.png

model类:User

8f900a89c6347c561fdf2122f13be562.png

961ddebeb323a10fe0623af514929fc1.png

1 package com.ouc.mkhl.platform.authority.model;

2

3 import java.io.Serializable;

4

5 //用户信息

6 public class User implements Serializable {

7

8 private static final long serialVersionUID = 1098321123L;

9

10 private Integer id; //用户Id

11

12 private String userName; //用户名

13

14 private String password; //未加密密码

15

16 private String email; //邮箱

17

18 private String trueName; //真实姓名

19

20 private String sex; //性别

21

22 private Integer age; //年龄

23

24 private String telephone; //手机

25

26 public Integer getId() {

27 return id;

28 }

29

30 public void setId(Integer id) {

31 this.id = id;

32 }

33

34 public String getUserName() {

35 return userName;

36 }

37

38 public void setUserName(String userName) {

39 this.userName = userName == null ? null : userName.trim();

40 }

41

42 public String getPassword() {

43 return password;

44 }

45

46 public void setPassword(String password) {

47 this.password = password == null ? null : password.trim();

48 }

49

50 public String getEmail() {

51 return email;

52 }

53

54 public void setEmail(String email) {

55 this.email = email == null ? null : email.trim();

56 }

57

58 public String getTrueName() {

59 return trueName;

60 }

61

62 public void setTrueName(String trueName) {

63 this.trueName = trueName == null ? null : trueName.trim();

64 }

65

66 public String getSex() {

67 return sex;

68 }

69

70 public void setSex(String sex) {

71 this.sex = sex == null ? null : sex.trim();

72 }

73

74 public Integer getAge() {

75 return age;

76 }

77

78 public void setAge(Integer age) {

79 this.age = age;

80 }

81

82 public String getTelephone() {

83 return telephone;

84 }

85

86 public void setTelephone(String telephone) {

87 this.telephone = telephone == null ? null : telephone.trim();

88 }

89

90 }

View Code

3)增删改查:

(1)select查询:

① id:在这个模式下唯一的标识符,可被其它语句引用。

② parameterType:传给此语句的参数的完整类名或别名。

③ resultType:语句返回值类型的整类名或别名。注意,如果是集合,那么这里填写的是集合的项的整类名或别名,而不是集合本身的类名。(resultType 与resultMap 不能并用)

④ resultMap:引用的外部resultMap名。结果集映射是MyBatis 中最强大的特性。许多复杂的映射都可以轻松解决。(resultType 与resultMap 不能并用)

⑤ flushCache:如果设为true,则会在每次语句调用的时候就会清空缓存。select语句默认设为false。

⑥ useCache:如果设为true,则语句的结果集将被缓存。select语句默认设为false。

⑦ timeout :设置驱动器在抛出异常前等待回应的最长时间,默认为不设值,由驱动器自己决定。

示例:查询所有用户信息:selectUsers

select id,userName,email from user

(2) insert插入:saveUser

此处数据库表使用主键自增,主键为id。

① fetchSize:设置一个值后,驱动器会在结果集数目达到此数值后,激发返回,默认为不设值,由驱动器自己决定。

② statementType:statement,preparedstatement,callablestatement。预准备语句、可调用语句。

③ useGeneratedKeys:使用JDBC的getGeneratedKeys方法来获取数据库自己生成的主键(MySQL、SQLSERVER等关系型数据库会有自动生成的字段)。

④ keyProperty:标识一个将要被MyBatis设置进getGeneratedKeys的key所返回的值,或者为insert语句使用一个selectKey子元素。

insert into user (userName, password, email, trueName, sex, age, telephone)

values (#{userName,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR},

#{email,jdbcType=VARCHAR}, #{trueName,jdbcType=VARCHAR},

#{sex,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER}, #{telephone,jdbcType=VARCHAR})

(3)update更新:动态更新SQL:updateUser

48304ba5e6f9fe08f3fa1abda7d326ab.png

update user

userName = #{userName,jdbcType=VARCHAR},

password = #{password,jdbcType=VARCHAR},

email = #{email,jdbcType=VARCHAR},

trueName = #{trueName,jdbcType=VARCHAR},

sex = #{sex,jdbcType=VARCHAR},

age = #{age,jdbcType=INTEGER},

telephone = #{telephone,jdbcType=VARCHAR},

where id = #{id,jdbcType=INTEGER}

48304ba5e6f9fe08f3fa1abda7d326ab.png

(4)delete删除:deleteUser

delete from user

where id = #{id,jdbcType=INTEGER}

(5)sql: Sql元素用来定义一个可以复用的SQL语句段,供其它语句调用。

48304ba5e6f9fe08f3fa1abda7d326ab.png

userName, password, email, telephone

select

from user

48304ba5e6f9fe08f3fa1abda7d326ab.png

(6)参数:parameters:MyBatis可以使用基本数据类型和Java的复杂数据类型。

基本数据类型,String,int,date等。

使用基本数据类型,只能提供一个参数,所以需要使用Java实体类,或Map类型做参数类型。通过#{}可以直接得到其属性。

① 基本数据类型参数:String

select id, userName, email from user

where userName = #{userName,jdbcType=VARCHAR}

Java代码:

public User getUserByName(String name); // 根据用户名获取用户信息

② Java实体类型参数:User

insert into user (userName, password, email, trueName, sex, age, telephone)

values (#{userName,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR},

#{email,jdbcType=VARCHAR}, #{trueName,jdbcType=VARCHAR},

#{sex,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER}, #{telephone,jdbcType=VARCHAR})

Java代码:

public int saveUser(User user); // 插入用户信息

③ Map参数:Map recordMap

48304ba5e6f9fe08f3fa1abda7d326ab.png

select count(*) from groupinfo

and id in

#{ids}

and name LIKE CONCAT(CONCAT('%', #{name}),'%')

AND description LIKE CONCAT(CONCAT('%', #{description}),'%')

AND type = #{type,jdbcType=INTEGER}

AND category = #{category,jdbcType=INTEGER}

48304ba5e6f9fe08f3fa1abda7d326ab.png

Java代码:

//获取子组总记录数

public int selectChildGroupTotalNum(Map recordMap);

48304ba5e6f9fe08f3fa1abda7d326ab.png

Map recordMap = new HashMap();

recordMap.put("idStr", group.getChildgroupids().split(","));

recordMap.put("name", name);

recordMap.put("description", description);

recordMap.put("type", -1);

recordMap.put("category", -1);

childGroupTotalNum = groupDao.selectChildGroupTotalNum(recordMap);

48304ba5e6f9fe08f3fa1abda7d326ab.png

④ 多参数:

方法一:按顺序传递参数。

select SensorNo from sensorconfig

where Name = #{0} and TestunitNo = #{1} and LABCODE = #{2}

Java代码:

//根据参数名查询参数ID

public int selectSensorNobySensorName(String sensorName, int testUnitNo, String labCode);

方法二:接口参数上添加@Param注解。

48304ba5e6f9fe08f3fa1abda7d326ab.png

select id, userName from user

and userName LIKE CONCAT(CONCAT('%', #{userName}),'%')

and supplierNo LIKE CONCAT(CONCAT('%', #{supplierno}),'%')

and supplierNo != 'test'

LIMIT #{startIndex},#{pageSize}

48304ba5e6f9fe08f3fa1abda7d326ab.png

Java代码:

// 根据用户名和V码查询用户信息

public List selectByUserNameAndVCode(

@Param("userName") String userName,

@Param("supplierno") String supplierno,

@Param("startIndex") int startIndex, @Param("pageSize") int pageSize);

4)动态SQL语句:

selectKey标签,if标签,if + where的条件判断,if + set的更新语句,if + trim代替where/set标签,trim代替set,choose (when, otherwise),foreach标签。动态SQL语句算是MyBatis最灵活的部分吧,用好了非常方便。

示例:selectTotalNumByAccountType

48304ba5e6f9fe08f3fa1abda7d326ab.png

select count(*) from user

and id not in

#{ids}

and userName LIKE CONCAT(CONCAT('%', #{userName}),'%')

and supplierNo LIKE CONCAT(CONCAT('%', #{supplierno}),'%')

and trueName LIKE CONCAT(CONCAT('%', #{trueName}),'%')

AND accountType = #{accountType}

48304ba5e6f9fe08f3fa1abda7d326ab.png

可以查看的文章:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值