一、基础实验——MyBatis 框架搭建
实验内容及步骤
创建数据库
在MySQL 中创建一个名称为mybatisdb 的数据库,并在该数据库中创建一个名称为user 的数据表,表结构如表5-1 所示:
create table user
(
uid int auto_increment
primary key,
uname varchar(20) null,
usex varchar(20) null
);
创建maven项目
创建持久化类MyUser
创建一个名为com.mybatis.po 包,在该包中创建持久化类MyUser,类中声明的属性与数据表user 的字段一致
@Data
public class MyUser {
String uname;
String usex;
int uid;
}
创建映射文件
创建一个名为com.mybatis.mapper 的包,在该包中创建映射文件UserMapper.xml,并在其中配置操作数据库的SQL 语句,具体代码如下:
<?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">
<mapper namespace="com.mybatis.mapper.UserMapper">
<select id="selectUserById" parameterType="Integer"
resultType="com.mybatis.po.MyUser">
Select * from user where uid = #{uid}
</select>
<select id="selectAllUser" resultType="com.mybatis.po.MyUser">
Select * from user
</select>
<insert id="addUser" parameterType="com.mybatis.po.MyUser">
Insert into user (uname,usex) values(#{uname},#{usex})
</insert>
<update id="updateUser" parameterType="com.mybatis.po.MyUser">
update user set uname=#{uname}, usex=#{usex} where uid=#{uid}
</update>
<delete id="deleteUser" parameterType="Integer">
delete from user where uid = #{uid}
</delete>
</mapper>
创建配置文件
创建MyBatis 的核心配置文件mybatis-config.xml,在该文件中配置了数据库环境和映射文件的位置,具体代码如下:
<?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://????/mybatisdb"/>
<property name="username" value="zhangkun"/>
<property name="password" value="zhangkun"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/mybatis/mapper/UserMapper.xml"/>
</mappers>
</configuration>
创建测试类
创建一个名为com.mybatis.test 的包,在该包中创建测试类MyBatisTest,在其中使用输入流读取配置文件,然后根据配置信息构建SqlSesstionFactory 对象,再通过SqlSessionFactory 对象创建SqlSession 对象,并使用SqlSession 对象的方法执行数据库操作,部分代码如下:
package com.mybatis.test;
import com.mybatis.mapper.UserMapper;
import com.mybatis.po.MyUser;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
/**
* @Author: 张坤
* @DateTime: 2021/11/8 10:47
* @Description: 该类用于 TODO
*/
public class MyBatisTest {
public static void main(String[] args){
try {
InputStream config= Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory ssf= new SqlSessionFactoryBuilder().build(config);
SqlSession ss=ssf.openSession();
//查询一个用户
MyUser mu = ss.selectOne("com.mybatis.mapper.UserMapper.selectUserById", 1);
System.out.println(mu);
//添加一个用户
MyUser addmu=new MyUser();
addmu.setUname("张三");
addmu.setUsex("男");
ss.insert("com.mybatis.mapper.UserMapper.addUser",addmu);
////修改一个用户
mu.setUname("李四");
UserMapper userMapper=ss.getMapper(UserMapper.class);
userMapper.updateUser(mu);
////删除一个用户
userMapper.deleteUser(addmu);
////查询所有用户
List<MyUser> myUserList=userMapper.selectAllUser();
System.out.println(myUserList.toString());
ss.commit();
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
这里有两种方法调用函数
调用session自带的函数
SqlSession ss=ssf.openSession();
MyUser mu = ss.selectOne("com.mybatis.mapper.UserMapper.selectUserById", 1);
调用userMapper的接口
UserMapper userMapper=ss.getMapper(UserMapper.class);
userMapper.updateUser(mu);
实验总结
运行结果截图;
- 简述MyBatis 的工作原理;
- 简述MyBatis 和Hibernate 的异同点和优缺点;
- 碰到的问题及解决方案或思考;
-
二、提高实验——映射器
实验内容及步骤
元素中使用resultMap 属性,代码片段如下:
<select id="selectResultMap" resultMap="myResult">
Select * from user
</select>
修改测试代码,使用id 为selectResultMap 的select 操作完成查询,并记录运行结果;
public class MyBatisTest {
public static void main(String[] args){
try {
InputStream config= Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory ssf= new SqlSessionFactoryBuilder().build(config);
SqlSession ss=ssf.openSession();
List<MapUser> mapUserList=ss.selectList
("com.mybatis.mapper.UserMapper.selectResultMap");
for(MapUser mm:mapUserList){
System.out.println(mm.toString());
}
ss.commit();
ss.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
实验总结
运行结果截图;
- 结合实验过程,总结MyBatis 实现查询时返回的结果集由集中常见的存储
方式;
- 碰到的问题及解决方案或思考;
- 实验收获及总结。
三、扩展实验——级联查询
实验内容及步骤
一对一级联查询
创建数据表
在数据库中创建两张数据表:身份证表idcard,个人信息表person,创建代码如下: ```sql CREATE TABLE idcard ( id tinyint (2) NOT NULL AUTO_INCREMENT, code varchar(18) COLLATE utf8_unicode_ci DEFAULT NULL, PRIMARY KEY (id) ); CREATE TABLE person( id tinyint(2) NOT NULL, name varchar(20) DEFAULT NULL, age int(11) DEFAULT NULL, idcard_id tinyint(2) DEFAULT NULL, PRIMARY KEY (id), KEY idcard_id (idcard_id), CONSTRAINT idcard_id FOREIGN KEY (idcard_id) REFERENCES idcard (id) );
INSERT INTO mybatisdb.idcard (id, code) VALUES (1, ‘11’); INSERT INTO mybatisdb.idcard (id, code) VALUES (2, ‘22’); INSERT INTO mybatisdb.idcard (id, code) VALUES (3, ‘33’); INSERT INTO mybatisdb.person (id, name, age, idcard_id) VALUES (11, ‘张三’, 11, 1); INSERT INTO mybatisdb.person (id, name, age, idcard_id) VALUES (22, ‘李四’, 22, 2); INSERT INTO mybatisdb.person (id, name, age, idcard_id) VALUES (33, ‘王五’, 33, 2); INSERT INTO mybatisdb.person (id, name, age, idcard_id) VALUES (44, ‘赵六’, 44, 3);
<a name="RBfjY"></a>
#### 创建持久化类
创建对应的持久化类Idcard 和Person,代码如下:
```java
package com.mybatis.po;
@Data
public class Idcard {
int id;
String code;
}
package com.mybatis.po;
@Data
public class Person {
Integer id;
String name;
Integer age;
Integer idcard_id;
Idcard idCard;
}@Data
public class Person {
int id;
String name;
int age;
int idcard_id;
}
打开延迟加载开关
在MyBatis 的核心配置文件mybatis-config.xml 中打开延迟加载开关,代码片段如下:
<configuration>
<!--在使用MyBatis嵌套查询方式进行关联查询时,使用MyBatis的延迟加载可以在一定程度上提高查询效率-->
<settings>
<!--打开延迟加载的开关-->
<setting name="lazyLoadingEnabled" value="true"/>
<!--将积极加载改为按需加载-->
<setting name="aggressiveLazyLoading" value="false"/>
</settings>
......
</configuration>
创建映射文件
创建映射文件IdCardMapper.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">
<mapper namespace="com.dao.IdCardDao">
<select id="selectCodeById" parameterType="Intege" resultType="com.po.Idcard">
select* from idcard where id=#{id}
</select>
</mapper>
创建映射文件PersonMapper.xml,并在其中以3 中方式实现“根据id 查询个人信息”的功能,具体代码如下:
<?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">
<mapper namespace="com.mybatis.mapper.PersonMapper">
<resultMap type="com.mybatis.po.Person" id="cardAndPerson1">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="age" column="age"/>
<!--一对一级联查询-->
<association property="idCard" column="idcard_id" javaType="com.mybatis.po.Idcard"
select="com.mybatis.mapper.IdCardMapper.selectCodeById"/>
</resultMap>
<select id="selectPersonById1" parameterType="Integer" resultMap="cardAndPerson1">
select* from person where id=#{id}
</select>
<!--一对一根据id查询个人信息:级联查询的第二种方法:嵌套结果,执行一个SQL-->
<resultMap type="com.mybatis.po.Person" id="cardAndPerson2">
<id property="id" column="id"/>
<result property="name" column="name"/>
<result property="age" column="age"/>
<!--一对一级联查询-->
<association property="idCard" javaType="com.mybatis.po.Idcard">
<id property="id" column="idcard_id"/>
<result property="code" column="code"/>
</association>
</resultMap>
<select id="selectPersonById2" parameterType="Integer" resultMap="cardAndPerson2">
select p.*,ic.code
from person p, idcard ic
where p.idcard_id=ic.id and p.id=#{id}
</select>
<!--一对一根据id查询个人信息:连接查询(使用PoJ0存储结果)-->
<select id="selectPersonById3" parameterType="Integer" resultType="com.mybatis.pojo.SelectPersonById">
select p.*,ic.code
from person p, idcard ic
where p.idcard_id=ic.id and p.id=#{id}
</select>
</mapper>
创建POJO 类
创建POJO 类com.pojo.SelectPersonById,代码片段如下
package com.mybatis.pojo;
@Data
public class SelectPersonById {
private Integer id;
private String name;
private Integer age;
private String code;
}
创建接口类
创建数据操作接口IdCardDao 以及其实现类,接口的具体代码如下:
public interface IdCardMapper {
public Idcard selectCodeById(int id);
}
创建数据操作接口PersonDao 以及其实现类,接口的具体代码如下:
public interface PersonMapper {
public Person selectPersonById1 (Integer id);
public Person selectPersonById2 (Integer id);
public SelectPersonById selectPersonById3(Integer id);
}
创建测试类
导入maven项目 junit用于测试
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>RELEASE</version>
<scope>compile</scope>
</dependency>
创建测试类TestOneToOne 并记录运行结果,代码片段如下:
public class TestOneToOne {
@Test
public void test() {
InputStream config = null;
try {
config = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory ssf = new SqlSessionFactoryBuilder().build(config);
SqlSession ss = ssf.openSession();
PersonMapper personMapper = ss.getMapper(PersonMapper.class);
Person pl = personMapper.selectPersonById1(11);
System.out.println(pl);
System.out.println("==============================");
Person p2 = personMapper.selectPersonById2(11);
System.out.println(p2);
System.out.println("===============================");
SelectPersonById p3 = personMapper.selectPersonById3(11);
System.out.println(p3);
} catch (IOException e) {
e.printStackTrace();
}
}
}
实验总结:
- 运行结果截图;
- 碰到的问题及解决方案或思考;
- 实验收获及总结。