首页 > 其他分享 >MyBatis

MyBatis

时间:2022-10-09 14:33:21浏览次数:67  
标签:xml public mybatis sqlSession MyBatis log4j id

MyBatis 是一个开源、轻量级的数据持久化框架

学习文档:https://www.cnblogs.com/fire-dong/p/13414797.html

 

mybatis工作流程:
-编写核心配置文件,环境信息,日志,缓存,Mapper等
-通过SqlSessionPactorBuild读取核心配置文件构建SqlSession
-通过SqlSessionOactor.getSession构建SqlSession
-使用SqlSession执行SQL语句

<Mapper>标签中加载XML文件几种方式
---URL
---CLASS
---RESOURCE
---PACKAGE


Mapper注意点:
接口和xml名字一样,路径一样(需到核心配置xml中配置<mappers>,因为maven工程约定:配置>编码)
接口的方法名和参数和返回值必须和xml保持一致
xml的命令空间必须全限定名

 

mybatis属性

resultMap:
resultMap 是一种“查询结果集---Bean对象”属性名称映射关系,
使用resultMap关系可将将查询结果集中的列一一映射到bean对象的各个属性
(两者属性名可以不同,配置好映射关系即可),适用与复杂一点的查询。
(1)适用于表的连接查询
(2)适用于表的一对多连接查询
(3)映射的查询结果集中的列标签可以根据需要灵活变化,
并且,在映射关系中,还可以通过typeHandler设置实现查询结果值的类型转换

resultType:
resultType 是一种“查询结果集---Bean对象”数据类型映射关系,使用resultType关系,即可使Bean对象接收查询结果集;
见名知意,该方法是通过查询结果集中每条记录(属性)的数据类型和Bean对象的数据类型作映射,
若两者都相同,则表示匹配成功,Bean可以接收到查询结果。
一般适用于pojo(简单对象)类型数据,简单的单表查询。

ParameterMap:
ParameterMap和resultMap类似,表示将查询结果集中列值的类型一一映射到java对象属性的类型上

parameterType
parameterType直接将查询结果列值类型自动对应到java对象属性类型上,不再配置映射关系一一对应

javaType:
javaType是用来指定pojo中对象属性的类型---(对象映射association用javaType)

ofType:
ofType指定的是映射到list集合属性中泛型的类型---(结果集collection用ofType)

 

mybatis常用动态sql语句

一. 定义 sql 语句
select 标签
属性介绍:

id :唯一的标识符.
parameterType:传给此语句的参数的全路径名或别名 例:com.test.poso.User 或 user
resultType :语句返回值类型或别名。注意,如果是集合,那么这里填写的是集合的泛型,而不是集合本身(resultType 与 resultMap 不能并用)

<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="Object">
select * from student where id=#{id}
</select>

insert 标签
属性介绍:

id :唯一的标识符
parameterType:传给此语句的参数的全路径名或别名 例:com.test.poso.User

<insert id="insert" parameterType="Object">
insert into student
<trim prefix="(" suffix=")" suffixOverrides=",">
<if test="name != null"> NAME, </if>
</trim>
<trim prefix="values(" suffix=")" suffixOverrides=",">
<if test="name != null"> #{name}, </if>
</trim>
</insert>

delete 标签
属性同 insert

<delete id="deleteByPrimaryKey" parameterType="Object">
delete from student where id=#{id}
</delete>

update 标签
属性同 insert

二. 配置 JAVA 对象属性与查询结果集中列名对应关系
resultMap 标签的使用
基本作用:

建立 SQL 查询结果字段与实体属性的映射关系信息
查询的结果集转换为 java 对象,方便进一步操作。
将结果集中的列与 java 对象中的属性对应起来并将值填充进去
!注意:与 java 对象对应的列不是数据库中表的列名,而是查询后结果集的列名

<resultMap id="BaseResultMap" type="com.online.charge.platform.student.model.Student">
<id property="id" column="id" />
<result column="NAME" property="name" />
<result column="HOBBY" property="hobby" />
<result column="MAJOR" property="major" />
<result column="BIRTHDAY" property="birthday" />
<result column="AGE" property="age" />
</resultMap>

<!--查询时resultMap引用该resultMap -->
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="Object">
select id,name,hobby,major,birthday,age from student where id=#{id}
</select>

标签说明:

主标签:

id:该 resultMap 的标志
type:返回值的类名,此例中返回 Studnet 类
子标签:

id:用于设置主键字段与领域模型属性的映射关系,此处主键为 ID,对应 id。
result:用于设置普通字段与领域模型属性的映射关系
三. 动态 sql 拼接
if 标签
if 标签通常用于 WHERE 语句、UPDATE 语句、INSERT 语句中,通过判断参数值来决定是否使用某个查询条件、判断是否更新某一个字段、判断是否插入某个字段的值。

<if test="name != null and name != ''">
and NAME = #{name}
</if>

foreach 标签
foreach 标签主要用于构建 in 条件,可在 sql 中对集合进行迭代。也常用到批量删除、添加等操作中。

<!-- in查询所有,不分页 -->
<select id="selectIn" resultMap="BaseResultMap">
select name,hobby from student where id in
<foreach item="item" index="index" collection="list" open="(" separator="," close=")">
#{item}
</foreach>
</select>

属性介绍:

collection:collection 属性的值有三个分别是 list、array、map 三种,分别对应的参数类型为:List、数组、map 集合。
item :表示在迭代过程中每一个元素的别名
index :表示在迭代过程中每次迭代到的位置(下标)
open :前缀
close :后缀
separator :分隔符,表示迭代时每个元素之间以什么分隔
choose 标签
有时候我们并不想应用所有的条件,而只是想从多个选项中选择一个。MyBatis 提供了 choose 元素,按顺序判断 when 中的条件出否成立,如果有一个成立,则 choose 结束。当 choose 中所有 when
的条件都不满则时,则执行 otherwise 中的 sql。类似于 Java 的 switch 语句,choose 为 switch,when 为 case,otherwise 则为 default。

if 是与(and)的关系,而 choose 是或(or)的关系。

<select id="getStudentListChoose" parameterType="Student" resultMap="BaseResultMap">
SELECT * from STUDENT WHERE 1=1
<where>
<choose>
<when test="Name!=null and student!='' ">
AND name LIKE CONCAT(CONCAT('%', #{student}),'%')
</when>
<when test="hobby!= null and hobby!= '' ">
AND hobby = #{hobby}
</when>
<otherwise>
AND AGE = 15
</otherwise>
</choose>
</where>
</select>

 

n对n处理与储存缓存

原理:
根据业务进行表设计,确定表的关联关系
一对一两张表,一张表放另一张表的主键

classA{
  B b;
}
classB{
  A a;
}

一对多三张表,两张主表,关联表

classA{
List<b> list;
}
classB{
A a;
}

多对多三张表,两张主表,关联表

classA{
List<b> list;
}
classB{
List<A>list;
}

映射文件(多对一):
关联对象构建:private 被关联实体类类名 名;
resultMap:建立SQL查询结果字段与实体属性的映射关系

<resultMap id="" type="">//id对应sql语句的resulMap属性,type对应查询实体类
<result property="id" column="id"/> //property对应实体类名,column对应数据库字段名
<result property="name" column="name"/>
<!--
对象(多对一):association
集合(一对多):collection
-->
<association property="" column="" javaType="" select=""/>
<result property="" column=""/>
</association>
//property对应关联对象名,column对应对象数据库字段名,javaType对像,select对应sql语句的id

//<collection property="" column=""/>
</resultMap>

一对多:
关联对象构建:private List<被关联实体类类名> 名;
<resultMap id="" type="">//id对应sql语句的resulMap属性,type对应查询实体类包路径
<id property="cid" column="cid" /> //配置到对应的主键
<result property="id" column="id"/> //property对应实体类名,column对应数据库字段名
<result property="name" column="name"/>
<collection property="" ofType="" javaType="" select=""/>
<result property="" column=""/>
</collection>

javaType & ofType
1.javaType :用来指定实体类中的属性。
2.ofType: 指定映射到List或者集合中的pojo类型,泛型中的约束类型。

注意点:
1.属性名誉字段名问题
2.利用log4j排查错误

 

存储过程原理:
---根据业务创建存储过程procedure
---再xml中配置对应的select标签,并声明statementType="CALLABLE",默认参数Hash Map,
配置resultType和resultMap时方法返回值没有任何意义都是null
---调用存储过程用“ Call 存储过程名 ”


//调用存储过程
1.Mysql存储过程:

DROP PROCEDURE IF EXISTS `chucun`;
create procedure 存储名(IN v_id int,OUT v_name varchar(10))
begin
select u.`name` into v_name from user u where id=v_id;
end

2.接口

public Map<String,String> queryCustmoerByid(Map<String,String> map);

3.调用储存过程

<parameterMap id="" type=""> //id对应select的paraterMap,type实体类包名路径
<parameter property="id" mode="IN" jdbcType="INTEGER"/>
<parameter property="name" mode="OUT" jdbcType="VARCHAR"/>
</parameterMap>

<select id="" parameterMap="" statementType="CALLABLE"> //id对应接口名
call cunchu(#{id,mode=IN},#{name,mode=OUT,jdbcType=VARCHAR}) //注意call不能漏
/* cunchu(?,?) */
</select>

4.测试

public void queryNameId(){
SqlSession sqlSession= mybatisUtils.getSqlSession();
UserDao userDao=sqlSession.getMapper(UserDao.class); //获取接口类对象
Map map=new HashMap();
map.put("id",18);
map.put("name",null);
userDao.queryCustmoerByid(map); //接口名
System.out.println(map.get("name"));//接口类对象调用接口
}

问题:
1.Parameter number 2 is not an OUT parameter
解决:url加上:&noAccessToProcedureBodies=true

 

什么是缓存(Cache):
--存在内存中的临时数据
--将用户查询的数据放在缓存(内存)中,用户去查询数据就不用从磁盘上(关系型数据库数据文件)查询,
从缓存中查询提高效率,并解决了该并发系统性能问题

mybatis缓存机制:
mubatis缓存分为一级和二级缓存
一级缓存(本地缓存/会话缓存,默认开启,无法关闭)作用在sqlsession上,执行对一个sql时会执行一遍
步骤:
1.开启日志(mybatis-config.zml的configuration内)

<settings>
<!--标准的日志工厂实现-->
<setting name="logImpl" value="STDOUT_LOGGING"/>
</setting>

2.测试执行两遍sql查询语句,查询同一数据,发现只查询了一次
注意:增删改数据会刷新缓存
3.手动清理缓存:

sqlSession.clearCache();
有关类(了解):
/*
public interface cache{
String getId();
void putObject(Object var1,Object var2);
Object getObject(Object var1);
Object removeObject(Object var1);
void clear();
int getSize();
default ReadWriteLock getReadWriteLock(){
return null;
}
} */

 

二级缓存(全局缓存,需手动开启)作用在sqlsessionFactory,当执行对一个xml中的查询多次时,只会执行一次,当执行修改时会清除缓存
为提高扩展性,Mybatis定义了缓存接口Cache,通过实现Cache接口自定义二级缓存
---基于namespace级别的缓存,一个名称空间,对应一个二级缓存;
工作机制:
--一个对话查询一条数据,此数据就会放于一级缓存中
--会话关闭,一级缓存的数据会被保存在二级缓存中
--新的会话查询信息就可以从二级缓存中获取信息
--不同的mapper查出的数据会放在自己对应的缓存(map)中
1.开启全局缓存(mybatis-config.zml的configuration内):

<settings>
<setting name="cacheEnable" value="true"/>
</setting>

2.使用全局缓存( 再Mapper.xml的<mapper>中)

<!--在当前Mapper.xml使用二级缓存-->
<cache
eviction="FIFO"
flushInterval="60000" //刷新时间
size="512"
readOnly="true"/> //自定义参数可不写
<selecet ... useCache=""></select> //userCache值:true,flase

3.测试
---将实体类序列化,否则会报错:
Caused by: java.io.NotserialiableException:com.kuang.pojo.User
解决:public class User implement Serializable{...}

自定义缓存(Ehcache)
1.先在子项目pom.xml中导入依赖:

<!-- https://mvnrepository.com/artifact/org.mybatis.caches/mybatis-ehcache -->
<dependency>
<groupId>org.mybatis.caches</groupId>
<artifactId>mybatis-ehcache</artifactId>
<version>1.1.0</version>
</dependency>

2.在 Mapper.xml 中指定使用 ehcache 缓存实现

<!--在当前 Mapper.xml 中使用二级缓存-->
<cache type="org.mybatis.caches.ehcache.EhcacheCache"/>

3.在resource中定义配置文件 ehcache.xml

<?xml version="1.0" encoding="UTF-8" ?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd" updateCheck="false">
<!--
diskStore: 缓存路径, ehcache分为内存和磁盘两级, 此属性定义磁盘的缓存位置
参数:
user.home - 用户主目录
user.dir - 用户当前工作目录
java.io.tmpdir - 默认临时文件路径
-->

<!-- java项目 www.fhadmin.org -->
<!--当二级缓存的对象 超过内存限制时(缓存对象的个数>maxElementsInMemory),存放入的硬盘文件 -->
<diskStore path="./tempdir/Tmp_Ehcache"/>

<!--default 默认缓冲策略, 当ehcache找不到定义的缓存时, 则使用这个缓存策略, 这个只能定义一个-->
<defaultCache
eternal="false"
maxElementsInMemory="10000"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="1800"
timeToLiveSeconds="259200"
memoryStoreEvictionPolicy="LRU"/>

<cache
name="cloud_user"
eternal="false"
maxElementsInMemory="5000"
overflowToDisk="false"
diskPersistent="false"
timeToIdleSeconds="1800"
timeToLiveSeconds="1800"
memoryStoreEvictionPolicy="LRU"/>
<!--
java项目 fhadmin.cn
maxElementsInMemory:设置 在内存中缓存 对象的个数
maxElementsOnDisk:设置 在硬盘中缓存 对象的个数
eternal:设置缓存是否 永远不过期
overflowToDisk:当系统宕机的时候是否保存到磁盘上
maxElementsInMemory的时候,是否转移到硬盘中
timeToIdleSeconds:当2次访问 超过该值的时候,将缓存对象失效
timeToLiveSeconds:一个缓存对象 最多存放的时间(生命周期)
diskExpiryThreadIntervalSeconds:设置每隔多长时间,通过一个线程来清理硬盘中的缓存
clearOnFlush: 内存数量最大时是否清除
memoryStoreEvictionPolicy:当超过缓存对象的最大值时,处理的策略;LRU (最少使用),FIFO (先进先出), LFU (最少访问次数)
-->
</ehcache>

 

 

mybatis练习

1.新建一个普通的maven项目

2.删除src目录

3.在pom.xml中导入maven依赖

<!--导入依赖-->
<dependencies>
<!--mysql驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>

<!--mybatis驱动-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.2</version>
</dependency>

<!--junit驱动-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>

4.创建一个模块module(在原maven文件下再建一个maven文件)

5.在resources中建mybatis-config.xml文件,并编写mybatis核心配置文件--连接数据库

<?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>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
</configuration>

6.编写mybatis工具类--在java文件中建包com.**.dao(接口),com.**.pojo(实体类)和com.**.utils(工具类)
在utils中输入内容:

//SqlSessionFactory -->sqlSession
public class mybatisUtils {
private static SqlSessionFactory sqlSessionFactory;
static {
try {
//获取SqlSessionFactory 对象
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
}
//拥有SqlSessionFactory后,就可获取sqlSession实例了
// sqlSession完全包含面向数据库执行SQL命令的所有方法
public static SqlSession getSqlSession(){
return sqlSessionFactory.openSession();
}
}

7.编写代码
在包com.**下
实体类(pojo)包:

//实体类(快捷键-ALT+ins)
public class User {
private int id;
private String name;
private String pwd;

public User() {
}

public User(int id, String name, String pwd) {
this.id = id;
this.name = name;
this.pwd = pwd;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getPwd() {
return pwd;
}

public void setName(String name) {
this.name = name;
}
public void setId(int id) {
this.id = id;
}

public void setPwd(String pwd) {
this.pwd = pwd;
}

@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", pwd='" + pwd + '\'' +
'}';
}
}

 

dao接口包:
1.UserDao(接口类):

public interface UserDao {
//模糊查询
List<User> getUserLike();

//查询全部用户
List<User> getUserList();

//根据ID查询用户
User getUserById(int id);

//增加(insert)一个用户
int addUser(User user)
Map运用:int addUser(Map<String.Object> map);

//修改update用户
int updateUser(User user);

//删除delete用户
int deleteUser(int id);
}

dao(接口实现类).UserDaoMapper.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace=绑定对应的Dao/Mapper接口-->
<mapper namespace="com.kuang.dao.UserDao">
<!--select查询语句-->
<select id="getUserList" resultType="com.kuang.pojo.User">
select * from mybatis.user
</select>
</mapper>

//Map传递参数,直接在sql中取出key即可。
步骤:编写接口->编写对应的mapper的sql语句->测试
1.namespace,包名和dao/mapper接口包名一致。
2.SQL语句:
a.select:
id:对应namespace中的方法名(接口中的方法)
resultType:sql语句执行的返回值
parameterType:参数类型

//模糊查询
<select id="getUserLike">
select * from mybatis.user where name like "%"#{value}"%";
</select>

1.查询全部:
<select id="getUserList" resultType="com.kuang.pojo.User">
select * from mybatis.user
</select>
2.ID查询:
<select id="getUserById" parameterType="int" resultType="com.kuang.pojo.User">
select *from mybatis.user when id=#{id}
</select>
3.insert增加:
<insert id="addUser" paramterType="com.kuang.pojo.User" >
insert into mybatis.user(id,name,pwd) values(#{id},#{name},#{pwd});
</insert>
Map运用:
<insert id="adduser" parameterType="map">
insert into mybatis.user(id,pwd) values (#{id},#{pwd});
</insert>

4.updaet修改:
<update id="updateUser" parameterType="com.kuang.pojo.User">
update mybatis.user set name=#{name},pwd=#{pwd} where id=#{id};
</update>
5.delete删除:
<delete id="deleteUser" parameterType="int"【可省】)>
delete from mybatis.user where id=#{id};
</delete>

8.测试:
注意点:
错误1:org.apache.ibatis.binding.BindingException:
Type interface com.kuang.dao.UserDao is not known to the MapperRegistry.
解决:在pom.xml文件后加:

<!--每一个mybatis-config.xml都需要Mybatis核心配置文件中注册-->
<mappers>
<mapper resource="com/bo/dao/UserMapper.xml"/>
</mappers>

错误2:The error may exist in com.kuang.dao.UserMapper.xml
解决:1.在父和子pom.xml文件的build中配置resources,来防止资源导出失败问题。

<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>

2.在resources的mybatis-config.xml文件中加:

<typeAliases>
<package name="com.kuang.pojo"/>
</typeAliases>

a.junit
test.java.com.**.dao.UserdaoTest:

public class UserDaoTest {
1.查询全部:
@Test
public void test(){
//获取Sqlsession对象
SqlSession sqlSession= mybatisUtils.getSqlSession();
try{
//执行SQl
UserDao userDao=sqlSession.getMapper(UserDao.class);
List<User> userList=userDao.getUserList();
for(User user:userList){
System.out.println(user);
}
}catch (Exception e){
e.printStackTrace();
}finally {
//关闭SqlSession
sqlSession.close();
}
}

2.id查询:
@Test
public void getUserById(){
SqlSession sqlSession= mybatisUtils.getSqlSession();
UserMapper mapper=sqlSession.getMapper(UserMapper.class);
User user=mapper.getUserById(1);
System.out.println(user);
sqlSession.close();
}
//模糊查询
@Test
public void getUserById(){
SqlSession sqlSession= mybatisUtils.getSqlSession();
UserMapper mapper=sqlSession.getMapper(UserMapper.class);
List<User> userList=mapper.getUserLike(value:"李");
for(User user:userList){
System.out.println(user);
}
sqlSession.close();
}
//增删改需要提交事务
3.insert增加:
@Test
public void addUser(){
SqlSession sqlSession= mybatisUtils.getSqlSession();
UserMapper mapper=sqlSession.getMapper(UserMapper.class);
if res=mapper.addUser(new User(id:4,name:"哈哈",pwd:"123333"));
if(res>0){
System.out.println("插入成功!");
}
//提交事务
sqlSession.commit();
sqlSession.close();
}
Map运用:
@Test
public void addUser(){
SqlSession sqlSession= mybatisUtils.getSqlSession();
UserMapper mapper=sqlSession.getMapper(UserMapper.class);
Map<string,object> map=new HashMap<String,Oobject>
map.put("userid",5);
map.put("password","222333");
mapper.addUser(map);
sqlSession.close();
}

4.update修改:
@Test
public void updateUser(){
SqlSession sqlSession=MybatisUtils.getSqlSession();
userMapper mapper=sqlSession.getMapper(UserMapper.class);
mapper.updateUser(new User(id:4,name:"呵呵",pwd:"123333"));
if(res>0){
System.out.println("修改成功!");
}
//提交事务
sqlSession.commit();
sqlSession.close();
}

5.delete删除:
@Test
public void deleteUser(){
SqlSession sqlSession=MybatisUtils.getSqlSession();
userMapper mapper=sqlSession.getMapper(UserMapper.class);
mapper.deleteUser(id:4);
}
if(res>0){
System.out.println("删除成功!");
}
//提交事务
sqlSession.commit();
sqlSession.close();
}
}

 

//通过properties属性引用配置文件
1.在resources文件中建db.properties文件:

driver=com.kuang.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"
username=root
password=123456

2.在核心配置文件中引入(注意插入位置)

1. <properties resource="db.properties"/>

2. 

<properties resource="db.properties">
<property name="username" value="root"/>
<property name="password" value="123456"/>
</properties>
//插入后,修改mybatis-config.xml:
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="${driver}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/> //最优级,优于properties
</dataSource>
</environment>

//类型(实体类)别名(typeAliases)
1. 在mybatis-conifg.xml中插入:
<!--为实体类取别名-->
<typeAliases>
<typeAlias type="com.kuang.pojo.User" alias="User"/> //为type取别名
</typeAliases>
//修改UserDaoMapper.xml文件为
<mapper namespace="User"> //User
<!--select查询语句-->
<select id="getUserList" resultType="User">
select * from mybatis.user
</select>

2.
<typeAliases>
<package name="com.kuang.pojo"/> //限实体类包,没注解时,默认为pojo类名如"user"(注意是小写)
</typeAliases>
//注解:
@Alias("User");
public class User{...}


//映射器(mappers)
<!--每一个Mapper.xml都需要到Mybatis核心配置中注册(mybatis-config.xml)-->
<!--引入外部配置文件文件-->
<properties resource="db.properties"/>
1:<!-- 使用相对于类路径的资源引用-->

<mappers>
<mapper resource="com/kuang/dao/UserMapper.xml"/>
</mappers>

2:<!-- 使用映射器接口实现类的完全限定类名(-->

<mappers>
<mapper class="com.kuang.dao.UserMapper"/>
</mappers>

3.<!-- 将包内的映射器接口实现全部注册为映射器 -->

<mappers>
<package name="com.kuang.dao"/>
</mappers>

注意点:接口和他的Mapper配置文件必须同名,接口和它的Mapper配置文件必须在同一个包下

//属性名与字段名不一样
1:起别名

<select id="getIserById" resultType="com.kuang.pojo.User">
select id,name,pwd as password from mybatis.user where id=#{id}
</select>

2.resultMap

<!--结果集映射-->
<resultMap id="UserMap" type="User">
<!--column数据库中的字段,property实体类中的字段-->
<result column="pwd" property="password"/>
</resultMap >
<select id="getIserById" resultMap="UserMap"> //
select * from mybatis.user where id=#{id}
</select>

3.日志 //排错

<settings>
<!--标准的日志工厂实现-->
<setting name="logImpl" value="STDOUT_LOGGING">
</setting>

a.log4j
1.先导包:
//在子pom.xm中插入依赖

<dependencies>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.12</version>
</dependency>
</dependencies>

2.在resouces中创建log4j.properties
配置:

{
#将等级为DEBUG的日志信息输出为console和file两个目的地
log4j.rootLogger=DEBUG,Console,file
#输出到控制台
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.encoding=utf-8
log4j.appender.Console.Target=System.out
log4j.appender.Console.layout=DEBUG
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=[%c]-%m%n

#文件输出设置
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.encoding=utf-8
log4j.appender.file.File=../log/kuang.log
log4j.appender.file.MaxFileSize=10MB
log4j.appender.file.MaxBackupIndex=50
log4j.appender.file.Threshold=DEBUG
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=[%p][%d{yyyy-MM-dd}][%c]%m%n

#日志输出设置
log4j.logger.org.mybatus=DEBUG
log4j.logger.java.sql=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.ResultSet=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG

} //注意utf-8和db.properties的name,password空格错误

3.在mybatis-config中配置

<settings>
<setting name="logImpl" value="LOG4J"/>
</settings>

4.log4j使用
在UserDaoTest加:
a.导包:import org.apache.log4j.Logger;
b.日志对象:static Logger Logger=Logger.getLogger(UserDaoTest.class);

@Test
public void testLog4j(){
Logger.info("info:进入testLog4j");
Logger.debug("debug:进入testLog4j");
Logger.error("error:进入testLog4j");
}

7.分页:
select * from user limit 0,2; (从第0个开始查,每页2个【-1代表最后一个-!】)

步骤:
1.接口(UserDao):

List<User> getUserByLimit(Map<String,Integer> map);

[
//注解开发(简单sql语句),Mapper.xml无需配置

@Select("select * from user")
List<User> getUsers();

]
2.Mapper.xml(UserDaoMapper.xml):

<select id="getUserByLimit" resultType="user" parameterType="map">
select * from mybatis.user limit #{startIndex},#{pageSize};
</select>

3.测试:

@Test
public void getUserByLimit(){
SqlSession sqlSession = mybatisUtils.getSqlSession();
UserDao mapper=sqlSession.getMapper(UserDao.class);
HashMap<String,Integer> map=new HashMap<String,Integer>();
map.put("startIndex",0);
map.put("pageSize",2);
List<User> userList=mapper.getUserByLimit(map);
for(User user : userList){
System.out.println(user);
}
sqlSession.close();
}

//RowBounds分页(不适应SQL实现分页)
1.接口UserDao配置:
//RowBound分页

List<User> getUserByRowBounds();

2.UserDaoMapper.xml配置:

<select id="getUserByRowBounds" resultMap="UserMap">
select * from mybatis.user
</select>

3.在测试UserDaoTest加(有误):

@Test
public void getUserByRowBounds(){
SqlSession sqlSession = mybatisUtils.getSqlSession();
RowBounds rowBounds=new RowBounds(1,2);

List<User> userList=sqlSession.selectList("mapper.UserDaoMapper.getUserByRowBounds",null,rowBounds);
for(User user:userList){
System.out.println(user);
}
sqlSession.close();
}

动态SQl(根据不同条件生成不同sql语句):
搭建环境:mysql建表Blog
1.导包.

2.编写配置文件(resouces.mapper.BlogMapper.xml):

<settings>
<setting name="mapUnderscoreToCamelCase" value="true"/>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>
<!--注册Mapper.xml-->
<mappers>
<mapper resource="mapper/BlogMapper.xml"/>
</mappers>

3.编写实体类(pojo):

@Data
public class Blog{
private int id;
private string title;
private string author;
private Date createTime;
private int views;
}

工具类(utils):

public class IDUtil {
public static String genId(){
return UUID.randomUUID().toString().replaceAll("-","");
}
}

4.编写实体类Mapper接口和Mapper.xml文件:
Mapper接口:

public interface BlogMapper{
//插入数据
int addBlog(Blog blog);
//查询
List<Blog> queryBlogIF();
}

Mapper.xml文件:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<!--namespace=绑定对应的Dao/Mapper接口-->
<mapper namespace="com.yuan.dao.UserDao">
<!--insert语句-->
<insert id="addBlog" parameterType="blog" resultType="blog">
insert into mybatis.blog(id,title,auther,create_time,views)
values(#{id},#{title},#{auther},#{create_time},#{views})
</insert>
【 
注解:parameterType与resultType: 使用 resultType : 主要针对于从数据库中提取相应的数据出来。 使用parameterType : 主要针对于 将信息存入到数据库中 】 <!--seletc查询语句--> <insert id="queryBlogIF" parameterType="map"> select * from mybatis.blog 1=1 <if test="title != null"> AND title like #{title} </if> <if test="auther!= null"> AND auther like #{auther} </if> </insert> </mapper>

5.test测试:

public class Mytest{
@Test
public void addInitBlog(){
//获取Sqlsession对象
SqlSession sqlSession= mybatisUtils.getSqlSession();
try{
//执行SQl
BlogMapper mapper=sqlSession.getMapper(BlogMapper.class); //根据Mapper.xml实例化对象
Blog blog=new Blog(); //新建实体类
blog.set**();
mapper.addBlog(blog);

blog.setId(IDutils.getId()); //
blog.setTitle("...");
mapper.addBlog(blog);

}catch (Exception e){
e.printStackTrace();
}finally {
//关闭SqlSession
sqlSession.close();
}
}

//if语句测试
@Test
public void queryBlogIF(){
SqlSession sqlSession= mybatisUtils.getSqlSession();
BlogMapper mapper=sqlSession.getMapper(BlogMapper.class);
HastMap map=new HashMap();
map.put("title","...");
map.put("auther","...");
List<Blog> blogs=mapper.queryBlogIF(map);
for(Blog blog : blogs){
System.out.println(blog);
}
sqlSession.close();
}
}

 

标签:xml,public,mybatis,sqlSession,MyBatis,log4j,id
From: https://www.cnblogs.com/xinyu-yudian/p/16772008.html

相关文章

  • spring boot项目使用mybatis-plus代码生成实例
    前言mybatis-plus官方地址https://baomidou.commybatis-plus是mybatis的增强,不对mybatis做任何改变,涵盖了代码生成,自定义ID生成器,快速实现CRUD,自动分页,逻辑删除等功......
  • Mybatis的返回值类型resultMap
    Mybatis的查询结果除了可以设置为resultType以外,还可以设置为resultMap.1.方式一:把resultType的值设置为Mapmapper文件:<selectid="selectReturnMap"resultType="j......
  • Mybatis的返回值类型resultType
     resultType在select查询语句当中都需要返回值类型,mybatis的返回值类型就reulstType和resultMap两种。resultType的mapper示例(Mybatis的xml配置文件):resultType是Jav......
  • Mybatis的#和$的区别
    1.#:占位符,告诉mybatis使用实际的参数值代替。并使用PreparedSatement对象执行sql语句,#{...}代替sql语句的"?"。这样更安全,更迅速,也是通常的做法。mapper文件<select......
  • Mybatis传递参数的各种方式:简单类型,@Param,map,java对象等等
    本文演示了给mybatis的mapper文件当中的SQL语句传递参数或者参数值的各种方式.xml格式mapper文件:<?xmlversion="1.0"encoding="UTF-8"?><!DOCTYPEmapper......
  • MyBatis的三种分页方式
    一、Limit分页<select id="getUserInfo1" parameterType="map" resultType="dayu">    select * from user    <if test="startPos!=null and pageSize!......
  • MyBatis框架:第三章:传统方式mybatis的增,删,改,查实现
    传统方式mybatis的增,删,改,查实现准备工作创建javaProject项目,建库建表插入数据,到数据库中执行,导入jar包添加mybatis的核心jar添加mysql数据库连接驱动添加log4j日记需......
  • 05. MyBatis的底层原理
    一、使用dom4j解析配置文件1.1、引入依赖<?xmlversion="1.0"encoding="UTF-8"?><projectxmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://ww......
  • MyBatis框架:第五章:源码解析及Mapper接口方式的mybatis的增,删,改,查实现
    Mapper接口编程的命名习惯Mapper接口方式的编程,需要先有一个接口。这个接口的命名一般是xxxxMapper。比如:User模块的Mapper,接口命名为UserMapper。Book模块的Mapper,接......
  • mybatis-plus还可以这样分表
    mybatis-plus还可以这样分表 为什么要分表Mysql是当前互联网系统中使用非常广泛的关系数据库,具有ACID的特性。但是mysql的单表性能会受到表中数据量的限制,主要原因......