网站建设推进会,联合会网站建设,小公司做网站还是微博,慧聪网登录Mybatis 文章目录 Mybatis搭建环境创建Maven工程将数据库中的表转换为对应的实体类配置文件核心配置文件mybatis-config.xml创建Mapper接口映射文件xxxMapper.xmllog4j日志功能 Mybatis操纵数据库示例及要点说明获取参数的两种方式${}#{} 各种类型的参数处理单个字面量参数多个…Mybatis 文章目录 Mybatis搭建环境创建Maven工程将数据库中的表转换为对应的实体类配置文件核心配置文件mybatis-config.xml创建Mapper接口映射文件xxxMapper.xmllog4j日志功能 Mybatis操纵数据库示例及要点说明获取参数的两种方式${}#{} 各种类型的参数处理单个字面量参数多个字面量参数map集合类型的参数实体类类型的参数通过Param注解(常用) Mybatis的各种查询功能查询一条数据为实体类对象查询多条数据为一个list集合查询单个数据查询一条数据为Map集合查询多条数据为Map集合 特殊SQL的执行模糊查询批量删除动态设置表名添加功能获取自增的主键 自定义映射resultMap多对一一对多 搭建环境
创建Maven工程
打包模式更改为jar包因为mybatis只是封装了jdbc不需要使用Tomcatpom.xml导入依赖mybatis的核心驱动Mysql驱动junit测试
pom.xml
project xmlnshttp://maven.apache.org/POM/4.0.0 xmlns:xsihttp://www.w3.org/2001/XMLSchema-instancexsi:schemaLocationhttp://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsdmodelVersion4.0.0/modelVersiongroupIdorg.example/groupIdartifactIdMyBaits/artifactIdversion1.0-SNAPSHOT/versionpackagingjar/packagingnameMyBaits/nameurlhttp://maven.apache.org/urlpropertiesproject.build.sourceEncodingUTF-8/project.build.sourceEncoding/propertiesdependencies!-- Mybatis核心 --dependencygroupIdorg.mybatis/groupIdartifactIdmybatis/artifactIdversion3.5.7/version/dependencydependencygroupIdjunit/groupIdartifactIdjunit/artifactIdversion4.13.2/versionscopetest/scope/dependency!-- MySQL驱动 --dependencygroupIdmysql/groupIdartifactIdmysql-connector-java/artifactIdversion8.0.16/version/dependency/dependencies/project
将数据库中的表转换为对应的实体类 User实体类
package com.zhnx.demo1.pojo;
import lombok.Data;
/*** ssm.t_user*/
Data
public class User {private Integer id;private String username;private String password;private Integer age;private String gender;private String email;public User() {}public User(Integer id, String username, String password, Integer age, String gender, String email) {this.id id;this.username username;this.password password;this.age age;this.gender gender;this.email email;}
}补充使用Data注解需要在pom.xml中配置lombok的依赖
lombok依赖!-- lombok简化实体类--dependencygroupIdorg.projectlombok/groupIdartifactIdlombok/artifactIdversion1.18.26/versionscopecompile/scope/dependency配置文件
核心配置文件mybatis-config.xml 核心配置文件主要功能与数据库和映射文件进行绑定 存放位置src/main/resources
mybatis-config.xml
?xml version1.0 encodingUTF-8 ?
!DOCTYPE configurationPUBLIC -//mybatis.org//DTD Config 3.0//ENhttp://mybatis.org/dtd/mybatis-3-config.dtd
configuration!-- Mybatis 核心配置文件标签的顺序properties?,settings?,typeAliases?,typeHandlers?,objectFactory?,objectWrapperFactory?,reflectorFactory?,plugins?,environments?,databaseIdProvider?,mappers?--!--引入properties文件,然后才可以在当前文件中使用的方式访问 --!-- ”jdbc.properties“ 的文件名 --properties resourcejdbc.properties/!--设置类型别名 --typeAliases!-- 比较 好的方式就是以包为单位将报下所有的类型设置成默认的类型别名类名不区分大小写 --!-- 类所在包的全类名com.zhnx.mybatis.pojo--package namecom.zhnx.demo1.pojo//typeAliases!--设置连接数据库的环境--environments defaultdevelopmentenvironment iddevelopmenttransactionManager typeJDBC/dataSource typePOOLED!-- 设置数据库连接的驱动 ${jdbc.driver}--property namedriver value${jdbc.driver}/!-- 设置数据库的连接地址 ${jdbc.url}--property nameurl value${jdbc.url}/!-- 设置连接数据库的用户名 ${jdbc.username}--property nameusername value${jdbc.username}/!-- 设置连接数据库的密码 ${jdbc.password}--property namepassword value${jdbc.password}//dataSource/environment/environments!--引入映射文件--mappers
!-- mapper resourcemappers/UserMapper.xml/--!-- 这种方式一定要保证mapper接口和映射文件在同一个目录下--package namecom.zhnx.demo1.mapper//mappers
/configuration创建Mapper接口
package com.zhnx.demo1.mapper;
import com.zhnx.demo1.pojo.User;public interface UserMapper {/*** 根据用户名查询用户信息* param name* return*/User getUserByUsername(String name);
}映射文件xxxMapper.xml 在映射文件中写SQL语句操作数据库 一个映射文件对应一个实体类一张表mapper接口的全类名和映射文件的namespace要一致Mapper接口中的方法名需要和映射文件中的SQL语句的id保持一致
UserMapper.xml
?xml version1.0 encodingUTF-8 ?
!DOCTYPE mapperPUBLIC -//mybatis.org//DTD Mapper 3.0//ENhttp://mybatis.org/dtd/mybatis-3-mapper.dtd!-- namespace ”当前接口的全类名“ 如com.zhnx.mybatis.mapper.UserMapper--
mapper namespacecom.zhnx.demo1.mapper.UserMapper!--mapper接口和映射文件要保持两个一致1、mapper接口的全类名和映射文件的namespace一致2、mapper接口中的方法的方法名要和映射设文件中的sql的id保持一致--!-- int insertUser();--insert idinsertUserinsert into t_user values (null,admin,00000000,23,男,admin000.qq.com);/insert/mapper
log4j日志功能 在pom.xml中加入log4j的依赖 !-- log4j日志 --dependencygroupIdlog4j/groupIdartifactIdlog4j/artifactIdversion1.2.17/version/dependencyMybatis操纵数据库
示例及要点说明 eg: 1、在UserMapper接口中新增方法 public interface UserMapper{User selectUser();
}2、在UserMapper.xml中配置SQL语句等 select idselectUser resultTypeUserselect * from t_user where id 1;
/selectresultType:设置返回的结果类型就是查询得到数据转换成的对应的Java类型(全类名) 可以在核心配置文件中使用标签设置类型别名 !--设置类型别名 --
typeAliases!-- 比较 好的方式就是以包为单位将包下所有的类型设置成默认的类型别名类名不区分大小写 --package namecom.zhnx.demo1.pojo/
/typeAliasesresultMap:自定义映射处理多对一或者一对多映射关系
获取参数的两种方式
${} 字符串拼接 注意添加单引号
#{} 占位符赋值 不需要添加单引号 可以防止SQL注入
各种类型的参数处理
单个字面量参数
${}和#{}都可以以任意键值就可以获取参数值
需要注意的是${}需要手动添加单引号
多个字面量参数 不可以使用#{username}、#{password}的方式 因为 因为当mapper接口中的方法参数为多个时此时MyBatis会自动将这些参数放在一个map集合中以arg0,arg1…或param1,param2…为键以参数为值
所以多个字面量参数的处理方式应该为#{arg0}…或‘${arg0}’…
map集合类型的参数
这种参数可以直接#{map键值对的键值}
eg:#{username}
实体类类型的参数
这种参数可以直接通过实体类的属性名获取属性值
eg:#{username}
通过Param注解(常用)
User getUserByUsername(param(“name”)String name);以注解的value属性值为键和Param1、Param2…为键eg:#{name}
Mybatis的各种查询功能
查询一条数据为实体类对象
resultType“User”
查询多条数据为一个list集合
resultType“User”
查询单个数据
resultType“integer/int/Int/Integer/_integer”(类型别名不区分大小写)
查询一条数据为Map集合
resultType“map”
查询多条数据为Map集合
resultType“map”
* 查询出来的多个Map集合统一放在list集合中 ** ListMapString, Object getAllUserToMap();** 查询结果 {password123456, sex男 , id1, age23, usernameadmin}
* 查询出来的多个Map集合放在Map集合中Map中嵌套Map** 使用MapKey(id)为外层的Map集合指定键值** MapKey(id)MapString, Object getAllUserToMap();** 查询结果{1{password123456, sex男, id1, age23, usernameadmin},2{password123456, sex男, id2, age23, username张三},3{password123456, sex男, id3, age23, username张三}}特殊SQL的执行
模糊查询 LIKE ‘abc%’ _ LIKE ‘_${mohu}%’LIKE concat(‘%’,#{mohu},‘%’)LIKE “%”#{mohu}“%” 具体情况根据SQL语句来判断
批量删除 delete from t_user where id in (${ids})
动态设置表名
select * from ${tableName}
添加功能获取自增的主键
//useGeneratedKeys“true”
//keyPropertyid
insert idinsertUser useGeneratedKeystrue keyPropertyidinsert into t_user values(null,#{username},#{password},#{age},#{sex})/insert自定义映射resultMap
//resultMap标签的和其中属性的详解
!-- resultMap设置自定义映射属性id表示自定义映射的唯一标识type查询的数据要映射的实体类的类型子标签id设置主键的映射关系result设置普通字段的映射关系association设置多对一的映射关系collection设置一对多的映射关系属性property设置映射关系中实体类中的属性名column设置映射关系中表中的字段名--!--简单例子 --!
resultMap iduserMap typeUserid propertyid columnid/idresult propertyuserName columnuser_name/resultresult propertypassword columnpassword/resultresult propertyage columnage/resultresult propertysex columnsex/result/resultMapselect idselectUser resultMapuserMapselect * from user;select多对一
例子实体类中还有实体类 级联使用 “类名.字段名” 的方式进行映射 resultMap idempDeptMap typeEmp id columneid propertyeid/id result columnename propertyename/resultresult columnage propertyage/resultresult columnsex propertysex/resultresult columndid propertydept.did/resultresult columndname propertydept.dname/result/resultMapassociation resultMap idempDeptMap typeEmpid columneid propertyeid/idresult columnename propertyename/resultresult columnage propertyage/resultresult columnsex propertysex/resultassociation propertydept javaTypeDeptid columndid propertydid/idresult columndname propertydname/result/association/resultMap一对多
例子实体类中有集合 collection resultMap iddeptEmpMap typeDeptid propertydid columndid/idresult propertydname columndname/resultcollection propertyemps ofTypeEmpid propertyeid columneid/idresult propertyename columnename/resultresult propertyage columnage/resultresult propertysex columnsex/result/collection/resultMap