结构:
Pojo实体类,对应mysql表的结构
mapper,将sql映射成方法,通过demo去调用sql方法
XXXmaaper.xml里面写了具体的sql
logback.xml、mybatis.xml配置信息
使用mapper去代理开发要将XXXmapper.xml配置和mapper方法类放在同一目录下
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="com.leehl.mapper.UserMapper"> <select id="selectAll" resultType="com.leehl.pojo.User"> select * from tb_user </select> </mapper>
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://192.168.10.128:3306/mybatis?useSSL=false"/> <property name="username" value="root"/> <property name="password" value="123456"/> </dataSource> </environment> </environments> <mappers> <!--sql的映射文件--> <mapper resource="com/leehl/mapper/UserMapper.xml"/> </mappers> </configuration>
运行简而言之:
通过输入流InputStream读取mybatis-config文件去构建SqlsessionFactory,
通过SqlsessionFactory去构建sqlsession,然后用sqlsession对象去打开对象流,opensession
然后用sqlsession去运行sql
package com.leehl; import com.leehl.mapper.UserMapper; import com.leehl.pojo.User; 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 82365 * @version 1.0 * @description TODO * @date 2023/6/10 11:22 */ public class MyBatisDemo2 { public static void main(String[] args) throws IOException { //加载mybatis配置文件,通过配置文件构建sqlSessionFactory String resource = "mybatis-config.xml"; InputStream inputStream = Resources.getResourceAsStream(resource); SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream); //获取sqlSession对象,用sqlSession来执行sql SqlSession sqlSession = sqlSessionFactory.openSession(); //使用sqlSession的getmapper去执行sql UserMapper mapper = sqlSession.getMapper(UserMapper.class); List<User> userList = mapper.selectAll(); System.out.println(userList); //关闭session sqlSession.close(); } }
标签:xml,mapper,框架,mybatis,sqlSession,sql,Mybatis,import From: https://www.cnblogs.com/leehl8016/p/17471133.html