本章的代码建立在第四章《Java框架整合--切分配置文件》的项目代码之上,链接如下:
http://www.cnblogs.com/java-zhao/p/5118184.html
在实际开发中,我们在使用mybatis的时候,会注解与xml形式一起使用。
1、二者的使用场景
xml使用场景(3个):
- 条件不定的查询(eg.下边代码中的getAdminByConditions方法)
- 增加对象返回自增主键(eg.下边代码的insertAdminWithBackId方法)
- 在一个Mapper接口中,出现多个select查询(>=3个),且每个查询都需要写相同的返回@Results内容(这一部分内容通常很多),这样的话,为了使Mapper接口比较整洁,重复代码比较少,我们会将这些select方法的具体实现写在xml文件中,因为在xml文件的顶部我们就会配置与注解@Results异曲同工的东西。(当然,这一点如果嫌配置xml麻烦,这一点可忽略)
注意:前两条是硬性的,是注解所解决不了的,而第三条只是建议。
除了以上这三条之外,其他的都使用去注解就好。
2、代码实现
基本代码不变,这只列出修改过得代码:
2.1、ssmm0-userManagement:
AdminController
1 package com.xxx.web.admin; 2 3 import java.util.List; 4 5 import org.springframework.beans.factory.annotation.Autowired; 6 import org.springframework.stereotype.Controller; 7 import org.springframework.web.bind.annotation.RequestMapping; 8 import org.springframework.web.bind.annotation.RequestParam; 9 import org.springframework.web.bind.annotation.ResponseBody; 10 import org.springframework.web.servlet.ModelAndView; 11 12 import com.xxx.model.userManagement.Admin; 13 import com.xxx.service.userManagement.AdminService; 14 15 /** 16 * adminController 17 */ 18 @Controller 19 @RequestMapping("/admin") 20 public class AdminController { 21 22 @Autowired 23 private AdminService adminService; 24 25 /** 26 * 管理员注册 27 */ 28 @ResponseBody 29 @RequestMapping("/register") 30 public boolean register(@RequestParam("username") String username, 31 @RequestParam("password") String password){ 32 Admin admin = new Admin(); 33 admin.setUsername(username); 34 admin.setPassword(password); 35 36 boolean isRegisterSuccess = adminService.register(admin); 37 38 return isRegisterSuccess; 39 } 40 41 /** 42 * 管理员登录 43 */ 44 @RequestMapping("/login") 45 public ModelAndView login(@RequestParam("username") String username, 46 @RequestParam("password") String password){ 47 Admin admin = adminService.login(username, password); 48 49 ModelAndView modelAndView = new ModelAndView(); 50 if(admin == null){ 51 modelAndView.addObject("message", "用户不存在或者密码错误!请重新输入"); 52 modelAndView.setViewName("error"); 53 }else{ 54 modelAndView.addObject("admin", admin); 55 modelAndView.setViewName("userinfo"); 56 } 57 58 return modelAndView; 59 } 60 61 /*****************************mybatis xml方式解决的问题*******************************/ 62 /** 63 * 根据username或password查找List64 */ 65 @ResponseBody 66 @RequestMapping("/findAdmin") 67 public List findAdmin(@RequestParam(value="username",required=false) String username, 68 @RequestParam(value="password",required=false) String password, 69 @RequestParam("start") int start, 70 @RequestParam("limit") int limit){ 71 List adminList = adminService.findAdmin(username, password, start, limit); 72 return adminList; 73 } 74 75 /** 76 * 插入一个用户并返回主键 77 * 注意:get请求也会自动装配(即将前台传入的username和password传入admin) 78 */ 79 @ResponseBody 80 @RequestMapping("/insert") 81 public Admin insertAdminWithBackId(Admin admin){ 82 return adminService.insertAdminWithBackId(admin); 83 } 84 }
说明:在这里增加了两个方法,具体看代码与注释
注:
- springMVC通过get方式传递的属性值username、password也能自动装配到对象admin中
2.2、ssmm0-data:
AdminService
1 package com.xxx.service.userManagement; 2 3 import java.util.List; 4 5 import org.springframework.beans.factory.annotation.Autowired; 6 import org.springframework.stereotype.Service; 7 8 import com.xxx.dao.userManagement.AdminDao; 9 import com.xxx.model.userManagement.Admin; 10 11 /** 12 * 管理员service 13 */ 14 @Service 15 public class AdminService { 16 @Autowired 17 private AdminDao adminDao; 18 19 public boolean register(Admin admin){ 20 return adminDao.register(admin); 21 } 22 23 public Admin login(String username, String password) { 24 return adminDao.login(username, password); 25 } 26 27 /***********以下方法是为了测试mybatis中使用xml**********/ 28 public ListfindAdmin(String username, String password, int start, int limit){ 29 return adminDao.findAdmin(username, password, start, limit); 30 } 31 32 public Admin insertAdminWithBackId(Admin admin){ 33 int record = adminDao.insertAdminWithBackId(admin); 34 if(record==1){ 35 return admin;//这时的admin已经被赋予主键了 36 } 37 return null; 38 } 39 }
AdminDao
1 package com.xxx.dao.userManagement; 2 3 import java.util.List; 4 5 import org.springframework.beans.factory.annotation.Autowired; 6 import org.springframework.stereotype.Repository; 7 8 import com.xxx.mapper.userManagement.AdminMapper; 9 import com.xxx.model.userManagement.Admin; 10 11 /** 12 * 管理员DAO 13 */ 14 @Repository 15 public class AdminDao { 16 @Autowired 17 private AdminMapper adminMapper; 18 19 public boolean register(Admin admin){ 20 return adminMapper.insertAdmin(admin)==1?true:false; 21 } 22 23 public Admin login(String username ,String password){ 24 return adminMapper.selectAdmin(username, password); 25 } 26 27 public ListfindAdmin(String username, String password, int start, int limit){ 28 return adminMapper.getAdminByConditions(username, password, start, limit); 29 } 30 31 public int insertAdminWithBackId(Admin admin){ 32 return adminMapper.insertAdminWithBackId(admin); 33 } 34 }
AdminMapper
1 package com.xxx.mapper.userManagement; 2 3 import java.util.List; 4 5 import org.apache.ibatis.annotations.Insert; 6 import org.apache.ibatis.annotations.Param; 7 import org.apache.ibatis.annotations.Result; 8 import org.apache.ibatis.annotations.Results; 9 import org.apache.ibatis.annotations.Select; 10 11 import com.xxx.model.userManagement.Admin; 12 13 /** 14 * 管理员Mapper 15 */ 16 public interface AdminMapper { 17 18 /**************注解**************/ 19 @Insert("INSERT INTO userinfo(username, password) VALUES(#{username},#{password})") 20 public int insertAdmin(Admin admin); 21 22 @Select("SELECT * FROM userinfo WHERE username = #{username} AND password = #{password}") 23 @Results(value = { 24 @Result(id = true, column = "id", property = "id"), 25 @Result(column = "username", property = "username"), 26 @Result(column = "password", property = "password") }) 27 public Admin selectAdmin(@Param("username") String username, 28 @Param("password") String password); 29 30 /***************xml**************/ 31 /** 32 * 条件不定式查询 33 * 我们这里使用@Param指定参数,这样的话,在AdminMapper.xml中就不用再使用parameterType属性了;否则得写parameterType属性 34 */ 35 public ListgetAdminByConditions(@Param("username")String username, 36 @Param("password")String password, 37 @Param("start")int start, 38 @Param("limit")int limit); 39 40 /** 41 * 返回主键 42 */ 43 public int insertAdminWithBackId(Admin admin); 44 }
注意:在用xml传参的时候,
- 如果你直接传参,eg.insertAdminWithBackId(Admin admin),则在xml中的insertAdminWithBackId方法处要添加parameterType;
- 如果你用了注解传参的话,eg.getAdminByConditions(@Param("username")String username),则在xml中的getAdminByConditions方法处不用添加parameterType,当然,注解传参的时候,不能传引用类型,一般只传基本类型,eg.insertAdminWithBackId(@Param("admin")Admin admin)就是不行的
接口定义好之后,需要添加两个配置文件+修改两个配置文件。目录结构如下:
AdminMapper.xml(该xml的名字最好与对应接口的接口名完全相同)
1 xml version="1.0" encoding="UTF-8" ?> 2 DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> 3 4 5 <mapper namespace="com.xxx.mapper.userManagement.AdminMapper"> 6 7 <resultMap type="Admin" id="adminResultMap"> 8 <id property="id" column="id" jdbcType="INTEGER" /> 9 <result property="username" column="username" jdbcType="VARCHAR" /> 10 <result property="password" column="password" jdbcType="VARCHAR" /> 11 resultMap> 12 13 <select id="getAdminByConditions" resultMap="adminResultMap"> 14 SELECT * FROM userinfo WHERE 1=1 ]]> 15 <if test="username != null"> AND username = #{username} ]]>if> 16 <if test="password != null"> AND password = #{password} ]]>if> 17 ORDER BY id ASC LIMIT #{start}, #{limit} ]]> 18 select> 19 20 21 <insert id="insertAdminWithBackId" parameterType="Admin" useGeneratedKeys="true" keyProperty="id"> 22 23 INSERT INTO userinfo 24 ( 25 username, 26 password 27 ) 28 VALUES 29 ( 30 #{username, jdbcType=VARCHAR}, 31 #{password, jdbcType=VARCHAR} 32 ) 33 ]]> 34 insert> 35 36 mapper>
注意:
- 该xml的名字最好与对应接口的接口名完全相同(eg.AdminMapper.xml对于应接口AdminMapper)
- parameterType有无参照上边对AdminMapper处所讲的注意点
- 返回自增主键有两种方法,我这里列出了最常用的也是最简单的一种
mybatis.xml
1 xml version="1.0" encoding="UTF-8"?> 2 DOCTYPE configuration 3 PUBLIC "-//mybatis.org//DTD Config 3.0//EN" 4 "http://mybatis.org/dtd/mybatis-3-config.dtd"> 5 6 <configuration> 7 <properties> 8 <property name="dialect" value="mysql" /> 9 properties> 10 11 <typeAliases> 12 13 <package name="com.xxx.model"/> 14 15 16 typeAliases> 17 configuration>
注意:这个文件一般用于指定属性和别名。
- 通常,属性只指定数据库方言即可;
- 有两种别名方式指定,请参照上述代码给出的注释进行选择,一般而言,都会选择package方式的
spring-data.xml
1 xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" 4 xsi:schemaLocation="http://www.springframework.org/schema/beans 5 http://www.springframework.org/schema/beans/spring-beans-3.2.xsd 6 http://www.springframework.org/schema/context 7 http://www.springframework.org/schema/context/spring-context-3.2.xsd"> 8 9 10 <context:component-scan base-package="com.xxx" /> 11 12 13 <bean id="xxxDataSource" class="org.apache.tomcat.jdbc.pool.DataSource" destroy-method="close"> 14 <property name="driverClassName" value="${jdbc.driverClassName}" /> 15 <property name="url" value="${jdbc.url}" /> 16 <property name="username" value="${jdbc.username}" /> 17 <property name="password" value="${jdbc.password}" /> 18 bean> 19 20 21 <bean id="xxxSqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> 22 <property name="dataSource" ref="xxxDataSource" /> 23 24 <property name="configLocation" value="classpath:mybatis.xml"/> 25 <property name="mapperLocations"> 26 <list> 27 <value>classpath*:mapper/admin/*Mapper.xmlvalue> 28 list> 29 property> 30 bean> 31 <bean id="xxxMapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> 32 37 <property name="basePackage" value="com.xxx.mapper" /> 38 <property name="sqlSessionFactoryBeanName" value="xxxSqlSessionFactory" /> 39 bean> 40 41 beans>
说明:只增加了两个属性配置,看代码与注释。
注:关于classpath与classpath*的具体区别自己去查,简单来说就是两句话:classpath只加载第一个找到文件;classpth*加载找到的多个文件。
pom.xml
1 xml version="1.0" encoding="UTF-8"?> 2 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 3 xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> 4 5 <modelVersion>4.0.0modelVersion> 6 7 <groupId>com.xxxgroupId> 8 <artifactId>ssmm0artifactId> 9 <version>1.0-SNAPSHOTversion> 10 11 <name>ssmm0name> 12 <packaging>pompackaging> 13 14 15 <modules> 16 <module>userManagementmodule> 17 <module>datamodule> 18 modules> 19 20 <properties> 21 <project.build.sourceEncoding>UTF-8project.build.sourceEncoding> 22 <project.reporting.outputEncoding>UTF-8project.reporting.outputEncoding> 23 properties> 24 25 26 <dependencyManagement> 27 <dependencies> 28 29 <dependency> 30 <groupId>com.alibabagroupId> 31 <artifactId>fastjsonartifactId> 32 <version>1.1.39version> 33 dependency> 34 35 <dependency> 36 <groupId>javax.servletgroupId> 37 <artifactId>javax.servlet-apiartifactId> 38 <version>3.0.1version> 39 <scope>providedscope> 40 dependency> 41 42 <dependency> 43 <groupId>org.springframeworkgroupId> 44 <artifactId>spring-coreartifactId> 45 <version>3.2.6.RELEASEversion> 46 dependency> 47 <dependency> 48 <groupId>org.springframeworkgroupId> 49 <artifactId>spring-beansartifactId> 50 <version>3.2.6.RELEASEversion> 51 dependency> 52 <dependency> 53 <groupId>org.springframeworkgroupId> 54 <artifactId>spring-contextartifactId> 55 <version>3.2.6.RELEASEversion> 56 dependency> 57 <dependency> 58 <groupId>org.springframeworkgroupId> 59 <artifactId>spring-webartifactId> 60 <version>3.2.6.RELEASEversion> 61 dependency> 62 <dependency> 63 <groupId>org.springframeworkgroupId> 64 <artifactId>spring-webmvcartifactId> 65 <version>3.2.6.RELEASEversion> 66 dependency> 67 68 <dependency> 69 <groupId>org.springframeworkgroupId> 70 <artifactId>spring-context-supportartifactId> 71 <version>3.2.6.RELEASEversion> 72 dependency> 73 74 <dependency> 75 <groupId>mysqlgroupId> 76 <artifactId>mysql-connector-javaartifactId> 77 <version>5.1.27version> 78 <scope>runtimescope> 79 dependency> 80 81 <dependency> 82 <groupId>org.apache.tomcatgroupId> 83 <artifactId>tomcat-jdbcartifactId> 84 <version>7.0.47version> 85 dependency> 86 87 <dependency> 88 <groupId>org.mybatisgroupId> 89 <artifactId>mybatisartifactId> 90 <version>3.1.1version> 91 dependency> 92 <dependency> 93 <groupId>org.mybatisgroupId> 94 <artifactId>mybatis-springartifactId> 95 <version>1.1.1version> 96 dependency> 97 98 <dependency> 99 <groupId>org.apache.velocitygroupId> 100 <artifactId>velocityartifactId> 101 <version>1.5version> 102 dependency> 103 <dependency> 104 <groupId>velocity-toolsgroupId> 105 <artifactId>velocity-tools-genericartifactId> 106 <version>1.2version> 107 dependency> 108 109 <dependency> 110 <groupId>commons-codecgroupId> 111 <artifactId>commons-codecartifactId> 112 <version>1.7version> 113 dependency> 114 <dependency> 115 <groupId>org.bouncycastlegroupId> 116 <artifactId>bcprov-jdk15onartifactId> 117 <version>1.47version> 118 dependency> 119 120 <dependency> 121 <groupId>org.apache.commonsgroupId> 122 <artifactId>commons-collections4artifactId> 123 <version>4.0version> 124 dependency> 125 126 <dependency> 127 <groupId>org.apache.httpcomponentsgroupId> 128 <artifactId>httpclientartifactId> 129 <version>4.2.6version> 130 dependency> 131 dependencies> 132 dependencyManagement> 133 134 135 <dependencies> 136 137 <dependency> 138 <groupId>com.alibabagroupId> 139 <artifactId>fastjsonartifactId> 140 dependency> 141 142 <dependency> 143 <groupId>org.springframeworkgroupId> 144 <artifactId>spring-coreartifactId> 145 dependency> 146 <dependency> 147 <groupId>org.springframeworkgroupId> 148 <artifactId>spring-beansartifactId> 149 dependency> 150 <dependency> 151 <groupId>org.springframeworkgroupId> 152 <artifactId>spring-contextartifactId> 153 dependency> 154 155 <dependency> 156 <groupId>org.apache.commonsgroupId> 157 <artifactId>commons-collections4artifactId> 158 dependency> 159 dependencies> 160 161 <build> 162 <resources> 163 167 <resource> 168 <directory>src/main/resourcesdirectory> 169 <filtering>truefiltering> 170 <includes> 171 <include>*.xmlinclude> 172 includes> 173 resource> 174 183 <resource> 184 <directory>src/main/resourcesdirectory> 185 <filtering>falsefiltering> 186 <includes> 187 188 <include>mapper/**/*.xmlinclude> 189 includes> 190 resource> 191 resources> 192 build> 193 194 200 <profiles> 201 202 <profile> 203 <id>devid> 204 <activation> 205 <activeByDefault>falseactiveByDefault> 206 <property> 207 <name>envname> 208 <value>devvalue> 209 property> 210 activation> 211 <properties> 212 <env>devenv> 213 214 <jdbc.driverClassName>com.mysql.jdbc.Driverjdbc.driverClassName> 215 224 <jdbc.url>jdbc:mysql://127.0.0.1:3306/blog?zeroDateTimeBehavior=convertToNull&useUnicode=true&characterEncoding=utf-8]]>jdbc.url> 225 <jdbc.username>rootjdbc.username> 226 <jdbc.password>123456jdbc.password> 227 properties> 228 profile> 229 230 <profile> 231 <id>rcid> 232 <activation> 233 <activeByDefault>falseactiveByDefault> 234 <property> 235 <name>envname> 236 <value>rcvalue> 237 property> 238 activation> 239 <properties> 240 <env>rcenv> 241 242 <jdbc.driverClassName>com.mysql.jdbc.Driverjdbc.driverClassName> 243 244 <jdbc.url>jdbc:mysql://10.10.10.100:3306/blog?zeroDateTimeBehavior=convertToNull&useUnicode=true&characterEncoding=utf-8]]>jdbc.url> 245 <jdbc.username>root2jdbc.username> 246 <jdbc.password>1234562jdbc.password> 247 properties> 248 profile> 249 250 <profile> 251 <id>prodid> 252 <activation> 253 <activeByDefault>trueactiveByDefault> 254 <property> 255 <name>envname> 256 <value>prodvalue> 257 property> 258 activation> 259 <properties> 260 <env>prodenv> 261 262 <jdbc.driverClassName>com.mysql.jdbc.Driverjdbc.driverClassName> 263 264 <jdbc.url>jdbc:mysql://99.99.99.999:3307/blog?zeroDateTimeBehavior=convertToNull&useUnicode=true&characterEncoding=utf-8]]>jdbc.url> 265 <jdbc.username>sadhijhqwuijdbc.username> 266 <jdbc.password>zxczkchwihcznk=jdbc.password> 267 properties> 268 profile> 269 profiles> 270 project>
说明:只在resource部分增加了一行关于"接口.xml"的过滤配置(作用看注释)
测试:测试的具体操作见前一章。