「这是我参与2022首次更文挑战的第39天,活动详情查看:2022首次更文挑战」
xml方式配置
- 有了上面的接口和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>
<!--引入外部配置文件-->
<properties resource="config.properties"></properties>
<!--定义别名-->
<typeAliases>
<package name=""/>
</typeAliases>
<!--定义数据库信息,默认使用development数据库构建环境-->
<environments default="development">
<environment id="development">
<!--jdbc事物管理-->
<transactionManager type="JDBC"></transactionManager>
<!--配置数据库连接信息-->
<dataSource type="POOLED">
<property name="driver" value="${database.driver}"/>
<property name="url" value="${database.url}"/>
<property name="username" value="${database.username}"/>
<property name="password" value="${database.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com/github/zxhtom/mapper/StudentMapper.xml"></mapper>
</mappers>
</configuration>
- 然后我们就可以加载这个xml环境配置,构建我们的sqlsession.
//获取mybatis-config.xml位置
InputStream inputStream = Resources.getResourceAsStream(Constant.MYBATIS);
//加载mybatis-config,并创建sqlsessionfactory对象
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//创建sqlsession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
Map<String, Object> paramMap = new HashMap<>();
paramMap.put("id", 1);
//执行select语句,将resultSet映射成对象并返回
StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);
List<Student> students = studentMapper.getStudents();
studentPrint(students);
在数据库方面我们最常用的应该JDBC、Hibernate和Mybatis。通过JDBC方式连接数据库,我们会发现工作量是相当的复杂。我们得处理一些琐碎的关闭。然后入参出参我们都得自己管理。基于次产生了ORM(Object Relational Mapping)模型。
#ORM模型
- 简单的说ORM模型就是数据库表和Java对象的映射模型。数据库和Java对象的相互映射。我们可以操作实体对象进而操作数据库表。这样的好处是我们不需要太了解数据库。减轻了我们的学习代价。 !
代码方式配置
-
官方提供了另外一种Java对象的方式来配置环境。这种配置我们控制的力度更加细腻,但是导致的问题是我们的一些配置将会硬编码在代码里。我们这里通过Properties文件将硬编码的东西挪出去。
-
与接口对应的是xml,里面记录了真是的sql。这里注意下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.github.zxhtom.mapper.StudentMapper">
<select id="getStudents" resultType="com.github.zxhtom.model.Student">
select * from student
</select>
<select id="getStudentByStuId" resultType="com.github.zxhtom.model.Student">
select * from student where id=#{id}
</select>
</mapper>