本文主要是介绍MyBatis(XML映射器操作),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
文章目录
- XML映射器操作(XxxMapper.xml)
- 文件目录
- 1.基本介绍
- 1.优点
- 2.常用顶级元素
- 2.环境配置
- 1.在原来的父模块下创建一个子模块
- 2.删除没用的两个文件夹
- 3.创建基本目录
- 4.父模块的pom.xml
- 5.jdbc.properties
- 6.mybatis-config.xml
- 7.测试使用MonsterMapperTest.java
- 3.parameterType(输入参数类型)
- 1.基本介绍
- 2.案例一
- 1.MonsterMapper.java
- 2.MonsterMapper.xml
- 3.测试
- 3.案例二(模糊查询)
- 1.MonsterMapper.java添加方法
- 2.MonsterMapper.xml添加实现类
- 3.测试
- 4.传入HashMap
- 1.基本介绍
- 2.案例一(参数为map)
- 1.MonsterMapper.java添加方法
- 2.MonsterMapper.xml
- 3.测试
- 3.案例二(返回值为map)
- 1.MonsterMapper.java添加方法
- 2.MonsterMapper.xml
- 3.测试
- 5.ResultMap
- 1.基本介绍
- 2.案例
- 1.创建数据表
- 2.创建映射类User.java
- 3.UserMapper.java
- 4.UserMapper.xml
- 5.测试(数据未填充!)
- 6.使用resultMap替换resultType解决,修改UserMapper.xml
- 7.结果
- 3.注意事项与细节
XML映射器操作(XxxMapper.xml)
文件目录
1.基本介绍
1.优点
2.常用顶级元素
2.环境配置
1.在原来的父模块下创建一个子模块
2.删除没用的两个文件夹
3.创建基本目录
4.父模块的pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"><modelVersion>4.0.0</modelVersion><groupId>org.example</groupId><artifactId>mybatis</artifactId><version>1.0-SNAPSHOT</version><packaging>pom</packaging><name>Archetype - mybatis</name><url>http://maven.apache.org</url><modules><module>mybatis_quickstart</module><module>xml-mapper</module></modules><dependencies><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.49</version></dependency><dependency><groupId>org.mybatis</groupId><artifactId>mybatis</artifactId><version>3.5.7</version></dependency><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><!--如果设置scope为test,则只能在test包下使用--><scope>test</scope></dependency></dependencies><!--在父模块中的pom.xml文件中配置在build的时候要扫描的文件,解决某些类型文件拷贝到target目录失败的问题--><build><resources><resource><directory>src/main/java</directory><includes><!--在java文件夹下的多级目录下的xml文件--><include>**/*.xml</include></includes></resource><resource><directory>src/main/resources</directory><includes><!--在resources文件夹下的多级目录下的xml文件和properties文件--><include>**/*.xml</include><include>**/*.properties</include></includes></resource></resources></build>
</project>
5.jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=UTF-8
jdbc.username=root
jdbc.password=root
6.mybatis-config.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configurationPUBLIC "-//mybatis.org//DTD Config 3.0//EN""https://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration><!--引入外部文件jdbc.properties--><properties resource="jdbc.properties"/><!--配置mybatis自带的日志,settings需要放到最前面--><settings><setting name="logImpl" value="STDOUT_LOGGING"/></settings><!--配置类型别名--><typeAliases><!--方式二:这样配置完了在这个包下的所有类都可以直接使用类名表示--><package name="com.sun.entity"/></typeAliases><environments default="development"><environment id="development"><!--配置事务管理器--><transactionManager type="JDBC"/><!--配置数据源--><dataSource type="POOLED"><!--配置驱动--><property name="driver" value="${jdbc.driver}"/><!--配置连接url--><!--1.jdbc:mysql:协议2.127.0.0.1:3306:指定连接mysql的ip+端口3.mybatis:连接的db4.useSSL:使用安全连接5.&:表示&6.useUnicode=true:使用unicode,防止编码错误7.characterEncoding=UTF-8:字符集使用utf-8--><property name="url" value="${jdbc.url}"/><!--用户名--><property name="username" value="${jdbc.username}"/><!--密码--><property name="password" value="${jdbc.password}"/></dataSource></environment></environments><mappers><!--包的方式引入含有Mapper.xml的类--><package name="com.sun.mapper"/></mappers></configuration>
7.测试使用MonsterMapperTest.java
package com.sun.mapper;import com.util.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Before;
import org.junit.Test;/*** @author 孙显圣* @version 1.0*/
public class MonsterMapperTest {//两个属性private SqlSession sqlSession; //相当于连接private MonsterMapper monsterMapper;//编写方法完成初始化@Before //标注了Before之后表示了在执行目标测试方法前会执行该方法public void init() {//获取到sqlSessionsqlSession = MyBatisUtils.getSqlSession();//获取到MonsterMapper对象monsterMapper = sqlSession.getMapper(MonsterMapper.class);System.out.println(monsterMapper.getClass());}@Testpublic void test() {System.out.println("ssss");}
}
3.parameterType(输入参数类型)
1.基本介绍
2.案例一
1.MonsterMapper.java
package com.sun.mapper;import com.sun.entity.Monster;import java.util.List;/*** 这个接口用于声明操作monster表的方法** @author 孙显圣* @version 1.0*/
public interface MonsterMapper {//通过id或者名字查询public List<Monster> findMonsterByNameORId(Monster monster);}
2.MonsterMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--指定该xml文件和哪个接口对应-->
<mapper namespace="com.sun.mapper.MonsterMapper"><!--实现public List<Monster> findMonsterByNameORId(Monster monster);这里能直接写Monster是因为配置文件里配置了类型别名--><select id="findMonsterByNameORId" parameterType="Monster" resultType="Monster">SELECT * FROM monster WHERE id = #{id} OR `name` = #{name}</select>
</mapper>
3.测试
package com.sun.mapper;import com.sun.entity.Monster;
import com.util.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Before;
import org.junit.Test;import java.util.List;/*** @author 孙显圣* @version 1.0*/
public class MonsterMapperTest {//两个属性private SqlSession sqlSession; //相当于连接private MonsterMapper monsterMapper;//编写方法完成初始化@Before //标注了Before之后表示了在执行目标测试方法前会执行该方法public void init() {//获取到sqlSessionsqlSession = MyBatisUtils.getSqlSession();//获取到MonsterMapper对象monsterMapper = sqlSession.getMapper(MonsterMapper.class);System.out.println(monsterMapper.getClass());}@Testpublic void test() {Monster monster = new Monster();monster.setId(1);monster.setName("大象精");List<Monster> monsterList = monsterMapper.findMonsterByNameORId(monster);for (Monster monster1 : monsterList) {System.out.println(monster1);}//关闭sqlsessionif (sqlSession != null) {sqlSession.close();}}
}
3.案例二(模糊查询)
1.MonsterMapper.java添加方法
public List<Monster> findMonsterByName(String name);
2.MonsterMapper.xml添加实现类
<!--实现public List<Monster> findMonsterByName(String name);--><select id="findMonsterByName" parameterType="String" resultType="Monster">SELECT * FROM monster WHERE `name` LIKE '%${name}%'</select>
3.测试
@Testpublic void MonsterMapper() {List<Monster> monsterList = monsterMapper.findMonsterByName("孙");for (Monster monster : monsterList) {System.out.println(monster);}}
4.传入HashMap
1.基本介绍
2.案例一(参数为map)
1.MonsterMapper.java添加方法
//传入mappublic List<Monster> findMonsterByIdAndName_ParamMap(Map<String, Object> map);
2.MonsterMapper.xml
<!--这里如果想要获取到id和name则需要这个Map里面有这两个key--><select id="findMonsterByIdAndName_ParamMap" parameterType="Map" resultType="Monster">SELECT * FROM monster WHERE id = #{id} OR `name` = #{name}</select>
3.测试
@Testpublic void findMonsterByIdAndName_ParamMap() {Map map = new HashMap<String, Object>();map.put("id", 1);map.put("name", "大象精");List<Monster> monsters = monsterMapper.findMonsterByIdAndName_ParamMap(map);for (Monster monster : monsters) {System.out.println(monster);}}
3.案例二(返回值为map)
1.MonsterMapper.java添加方法
//以map作为返回参数public List<Map<String, Object>> findMonsterByIdAndName_ParamMap_returnMap(Map<String, Object> map);
2.MonsterMapper.xml
<!--返回值是List,每一个元素都是一个map,而一个map代表了一条记录,key代表列,value代表值--><select id="findMonsterByIdAndName_ParamMap_returnMap" parameterType="Map" resultType="Map">SELECT * FROM monster WHERE id = #{id} OR `name` = #{name}</select>
3.测试
@Testpublic void findMonsterByIdAndName_ParamMap_returnMap() {Map map = new HashMap<String, Object>();map.put("id", 6);map.put("name", "大象精");List<Map<String, Object>> mapList = monsterMapper.findMonsterByIdAndName_ParamMap_returnMap(map);//取出所有mapfor (Map<String, Object> stringObjectMap : mapList) {for (Map.Entry<String, Object> entry : stringObjectMap.entrySet()) {System.out.println(entry.getKey() + " " + entry.getValue());}}}
5.ResultMap
1.基本介绍
2.案例
1.创建数据表
CREATE TABLE `user` (user_id INT NOT NULL auto_increment,user_email VARCHAR(255) DEFAULT '',user_name VARCHAR(255) DEFAULT'',PRIMARY KEY (user_id)
)
2.创建映射类User.java
package com.sun.entity;/*** @author 孙显圣* @version 1.0*/public class User {private Integer user_id;//下面两个字段与数据表的字段不对应private String username; private String useremail;public User() {}public User(Integer user_id, String username, String useremail) {this.user_id = user_id;this.username = username;this.useremail = useremail;}public Integer getUser_id() {return user_id;}public void setUser_id(Integer user_id) {this.user_id = user_id;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getUseremail() {return useremail;}public void setUseremail(String useremail) {this.useremail = useremail;}@Overridepublic String toString() {return "User{" +"user_id=" + user_id +", username='" + username + '\'' +", useremail='" + useremail + '\'' +'}';}
}
3.UserMapper.java
UserMapper.xmlpackage com.sun.mapper;import com.sun.entity.User;import java.util.List;/*** @author 孙显圣* @version 1.0*/
public interface UserMapper {//查询所有UserMapper.xmlserpublic List<User> findAllUser();
}
4.UserMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--指定该xml文件和哪个接口对应-->
<mapper namespace="com.sun.mapper.UserMapper"><select id="findAllUser" resultType="User">SELECT * FROM user</select>
</mapper>
5.测试(数据未填充!)
package com.sun.mapper;import com.sun.entity.User;
import com.util.MyBatisUtils;
import org.apache.ibatis.session.SqlSession;
import org.junit.Before;
import org.junit.Test;import java.util.List;/*** @author 孙显圣* @version 1.0*/
public class UserMapperTest {//两个属性private SqlSession sqlSession; //相当于连接private UserMapper userMapper;//编写方法完成初始化@Before //标注了Before之后表示了在执行目标测试方法前会执行该方法public void init() {//获取到sqlSessionsqlSession = MyBatisUtils.getSqlSession();//获取到MonsterMapper对象userMapper = sqlSession.getMapper(UserMapper.class);System.out.println(userMapper.getClass());}@Testpublic void findAllUser() {List<User> allUser = userMapper.findAllUser();System.out.println(allUser);}
}
6.使用resultMap替换resultType解决,修改UserMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapperPUBLIC "-//mybatis.org//DTD Mapper 3.0//EN""https://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--指定该xml文件和哪个接口对应-->
<mapper namespace="com.sun.mapper.UserMapper"><!--使用resultMap替换resultType,来进行映射类的属性与表之间的映射--><resultMap id="findAllUserResultType" type="User"><result column="user_email" property="useremail"/><result column="user_name" property="username"/></resultMap><select id="findAllUser" resultMap="findAllUserResultType">SELECT * FROM user</select>
</mapper>
7.结果
3.注意事项与细节
- 如果没有使用resultMap,但是表的列名与映射类的属性不匹配,则返回的结果不会填充,则该位置会是对象属性的默认值
- 解决列名与属性名不同也可以使用别名,简单来说就是查询出来结果的时候使用as,将结果所在的列名设置成跟属性一致的名字,但是不推荐
- MyBatis-Plus可以直接使用@TableField注解或者@TableName注解来解决
这篇关于MyBatis(XML映射器操作)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!