<?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.cj.jdbc.Driver"/>
<!--连接数据库三要素信息-->
<property name="url" value="jdbc:mysql://localhost:3306/javaweb"/>
<property name="username" value="1210449106"/>
<property name="password" value="qqmmyang1"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="StudentMapper.xml"/>
</mappers>
</configuration>
-
- xxxMapper.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="">
<insert id="insertStu">
INSERT INTO t_student(id,sname,sage,sex,addr_id) VALUES (null,'张十三',18,1,7)
</insert>
</mapper>
-
-
- sql语句最后结尾可以不写“;”
- CarMapper.xml文件的名字不是固定的。可以使用其它名字。
- CarMapper.xml文件的位置也是随意的。这里选择放在resources根下,相当于放到了类的根路径下。
- 将CarMapper.xml文件路径配置到mybatis-config.xml:
- 编写测试类
-
- 定位当前工程中mybatis核心配置文件存储位置
- SqlSessionFacoryBuilder读取配置文件并交给SqlSessionFactory
- SqlSessionFactory为开发人员提供SqlSession对象
- SqlSession对象完成SQL语句推送
public class AppTest {
@Test
public void test1(){
InputStream is = null;
try {
//1.定位当前工程中的mybatis-config-xml配置文件
is = Resources.getResourceAsStream("mybatis-config.xml");
//2.SqlSessionFactoryBuilder读取配置文件信息并交给SqlSessionFactory
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
//3.SqlSessionFactory为开发人员提供SqlSession
SqlSession sqlSession = sqlSessionFactory.openSession(true);
//4.SqoSession对象帮助开发人员完成SQL语句推送
int count = sqlSession.insert("com.wry.pojo.Student.insertStu");
System.out.println(count);
} catch (IOException e) {
throw new RuntimeException(e);
} finally {
//资源关闭
if (is != null) {
try {
is.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
@Test
public void test02(){
InputStream is = null;
try {
//生成SqlSessionFactoryBuilder
SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
//生成SqlSessionFactory对象
SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is = Resources.getResourceAsStream("mybatis-config.xml"));
SqlSession sqlSession = sqlSessionFactory.openSession(true);
//执行sql语句
int count = sqlSession.insert("com.wry.pojo.Student.insertStu");
System.out.println(count);
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
}